max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
sbx/ui/controls.py
JaDogg/sbx
4
6623651
""" Reusable controls, components, classes used in SBX """ import abc from abc import ABCMeta from prompt_toolkit import Application from prompt_toolkit.clipboard import ClipboardData from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import Float, FloatContainer from prompt_toolkit.layout.processors import ( DisplayMultipleCursors, TabsProcessor, ) from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.widgets import Button, Dialog, Label, TextArea from sbx.ui.mdlexer import CustomMarkdownLexer class MarkdownArea(TextArea): """ Pre configured markdown component for prompt_toolkit """ def __init__(self, readonly=False): super().__init__( lexer=PygmentsLexer(CustomMarkdownLexer), scrollbar=True, line_numbers=True, focus_on_click=not readonly, input_processors=[TabsProcessor(), DisplayMultipleCursors()], wrap_lines=True, read_only=readonly, focusable=not readonly, ) def indent(self): """ Insert a tab """ if self.read_only: return current_doc = self.document self.document = current_doc.paste_clipboard_data( ClipboardData(text="\t") ) class BaseUi(metaclass=ABCMeta): """ Core UI class for Editor & Study interfaces to inherit from """ def __init__(self): self._layout_stack = [] self._focus_stack = [] self._float = None self.kb = KeyBindings() def hide_current_dialog(self): """ Hide current displayed dialog box """ # Nothing to hide, ignore if not self._float.floats: return # WHY: Ensure that we restore previous focused item prev_focus = self._focus_stack.pop() if prev_focus: self.get_current_layout().focus(prev_focus) # Garbage clean up float_dialog = self._float.floats.pop() del float_dialog self.get_current_app().invalidate() def exit_clicked(self, _=None): self.get_current_app().exit() @abc.abstractmethod def get_current_app(self) -> Application: pass @abc.abstractmethod def get_current_layout(self) -> Layout: pass @abc.abstractmethod def get_actions(self) -> dict: pass @abc.abstractmethod def get_keybindings(self) -> dict: pass def create_key_bindings(self): actions = self.get_actions() for action, keys in self.get_keybindings().items(): if callable(keys): keys(self.kb, actions[action]) continue for key in keys.split(","): try: self.kb.add(key.strip())(actions[action]) except KeyError: pass def create_root_layout(self, container, focused_element): self._float = FloatContainer(container, floats=[]) return Layout(self._float, focused_element=focused_element) def message_box(self, title: str, text: str): """ Show a message box * `title` - title of the message box * `text` - text of the message box """ self.custom_dialog( title, Label(text=text, dont_extend_height=True), show_ok=True ) def confirm_box(self, title: str, text: str, on_yes, on_no): """ Show a message box with yes/no confirmation * `title` - title of the message * `text` - text asking a question * `on_yes` - call back function (no args) * `on_no` - call back function (no args) """ body = Label(text=text, dont_extend_height=True) yes_btn = Button(text="Yes", handler=self._hide_then_call(on_yes)) no_btn = Button(text="No", handler=self._hide_then_call(on_no)) self.custom_dialog( title, body, focus_element=yes_btn, buttons=[yes_btn, no_btn] ) def _hide_then_call(self, fnc): def callback(): self.hide_current_dialog() fnc() return callback def custom_dialog( self, title: str, body, show_ok=False, focus_element=None, buttons=None ): """ Create a custom dialog * `title` - title of the message * `body` - prompt_toolkit widget to display as body * `show_ok` - show OK button (use this if you don't want to provide your own buttons) * `focus_element` - prompt_toolkit element to focus on. * `buttons` = list of prompt_toolkit buttons to show Note: * Please note that you need to call `hide_current_dialog` after a button is clicked and you no longer want to show a dialog. * All custom dialog are stored in a stack. If `n` dialog are shown then you need to call `hide_current_dialog` exactly `n` times. * Refer to code in `confirm_box` & `message_box` for samples. """ ok = None if show_ok: ok = Button(text="OK", handler=self.hide_current_dialog) btns = [ok] elif buttons: btns = buttons else: btns = [] dialog = Dialog( title=title, body=body, buttons=btns, with_background=False, ) self._focus_stack.append(self.get_current_layout().current_window) self._float.floats.append(Float(dialog, allow_cover_cursor=True)) if show_ok and ok: self.get_current_layout().focus(ok) if focus_element: self.get_current_layout().focus(focus_element) self.get_current_app().invalidate()
""" Reusable controls, components, classes used in SBX """ import abc from abc import ABCMeta from prompt_toolkit import Application from prompt_toolkit.clipboard import ClipboardData from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout import Layout from prompt_toolkit.layout.containers import Float, FloatContainer from prompt_toolkit.layout.processors import ( DisplayMultipleCursors, TabsProcessor, ) from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.widgets import Button, Dialog, Label, TextArea from sbx.ui.mdlexer import CustomMarkdownLexer class MarkdownArea(TextArea): """ Pre configured markdown component for prompt_toolkit """ def __init__(self, readonly=False): super().__init__( lexer=PygmentsLexer(CustomMarkdownLexer), scrollbar=True, line_numbers=True, focus_on_click=not readonly, input_processors=[TabsProcessor(), DisplayMultipleCursors()], wrap_lines=True, read_only=readonly, focusable=not readonly, ) def indent(self): """ Insert a tab """ if self.read_only: return current_doc = self.document self.document = current_doc.paste_clipboard_data( ClipboardData(text="\t") ) class BaseUi(metaclass=ABCMeta): """ Core UI class for Editor & Study interfaces to inherit from """ def __init__(self): self._layout_stack = [] self._focus_stack = [] self._float = None self.kb = KeyBindings() def hide_current_dialog(self): """ Hide current displayed dialog box """ # Nothing to hide, ignore if not self._float.floats: return # WHY: Ensure that we restore previous focused item prev_focus = self._focus_stack.pop() if prev_focus: self.get_current_layout().focus(prev_focus) # Garbage clean up float_dialog = self._float.floats.pop() del float_dialog self.get_current_app().invalidate() def exit_clicked(self, _=None): self.get_current_app().exit() @abc.abstractmethod def get_current_app(self) -> Application: pass @abc.abstractmethod def get_current_layout(self) -> Layout: pass @abc.abstractmethod def get_actions(self) -> dict: pass @abc.abstractmethod def get_keybindings(self) -> dict: pass def create_key_bindings(self): actions = self.get_actions() for action, keys in self.get_keybindings().items(): if callable(keys): keys(self.kb, actions[action]) continue for key in keys.split(","): try: self.kb.add(key.strip())(actions[action]) except KeyError: pass def create_root_layout(self, container, focused_element): self._float = FloatContainer(container, floats=[]) return Layout(self._float, focused_element=focused_element) def message_box(self, title: str, text: str): """ Show a message box * `title` - title of the message box * `text` - text of the message box """ self.custom_dialog( title, Label(text=text, dont_extend_height=True), show_ok=True ) def confirm_box(self, title: str, text: str, on_yes, on_no): """ Show a message box with yes/no confirmation * `title` - title of the message * `text` - text asking a question * `on_yes` - call back function (no args) * `on_no` - call back function (no args) """ body = Label(text=text, dont_extend_height=True) yes_btn = Button(text="Yes", handler=self._hide_then_call(on_yes)) no_btn = Button(text="No", handler=self._hide_then_call(on_no)) self.custom_dialog( title, body, focus_element=yes_btn, buttons=[yes_btn, no_btn] ) def _hide_then_call(self, fnc): def callback(): self.hide_current_dialog() fnc() return callback def custom_dialog( self, title: str, body, show_ok=False, focus_element=None, buttons=None ): """ Create a custom dialog * `title` - title of the message * `body` - prompt_toolkit widget to display as body * `show_ok` - show OK button (use this if you don't want to provide your own buttons) * `focus_element` - prompt_toolkit element to focus on. * `buttons` = list of prompt_toolkit buttons to show Note: * Please note that you need to call `hide_current_dialog` after a button is clicked and you no longer want to show a dialog. * All custom dialog are stored in a stack. If `n` dialog are shown then you need to call `hide_current_dialog` exactly `n` times. * Refer to code in `confirm_box` & `message_box` for samples. """ ok = None if show_ok: ok = Button(text="OK", handler=self.hide_current_dialog) btns = [ok] elif buttons: btns = buttons else: btns = [] dialog = Dialog( title=title, body=body, buttons=btns, with_background=False, ) self._focus_stack.append(self.get_current_layout().current_window) self._float.floats.append(Float(dialog, allow_cover_cursor=True)) if show_ok and ok: self.get_current_layout().focus(ok) if focus_element: self.get_current_layout().focus(focus_element) self.get_current_app().invalidate()
en
0.656342
Reusable controls, components, classes used in SBX Pre configured markdown component for prompt_toolkit Insert a tab Core UI class for Editor & Study interfaces to inherit from Hide current displayed dialog box # Nothing to hide, ignore # WHY: Ensure that we restore previous focused item # Garbage clean up Show a message box * `title` - title of the message box * `text` - text of the message box Show a message box with yes/no confirmation * `title` - title of the message * `text` - text asking a question * `on_yes` - call back function (no args) * `on_no` - call back function (no args) Create a custom dialog * `title` - title of the message * `body` - prompt_toolkit widget to display as body * `show_ok` - show OK button (use this if you don't want to provide your own buttons) * `focus_element` - prompt_toolkit element to focus on. * `buttons` = list of prompt_toolkit buttons to show Note: * Please note that you need to call `hide_current_dialog` after a button is clicked and you no longer want to show a dialog. * All custom dialog are stored in a stack. If `n` dialog are shown then you need to call `hide_current_dialog` exactly `n` times. * Refer to code in `confirm_box` & `message_box` for samples.
2.355313
2
prf_api/arquivo.py
nymarya/prf_api
6
6623652
from io import BytesIO from zipfile import ZipFile from rarfile import RarFile import os def extrair_rar(rf: RarFile, caminho: str): """ Extrai csvs de um arquivo . rar. Parâmetros ---------- rf: Rarfile conteúdo do arquivo compactado. caminho: str caminho para pasta onde os arquivos devem ser salvos. """ ano = caminho.split('/')[-1] n_arquivos = len(rf.infolist()) for f in rf.infolist(): # Filtra arquivos csvs comprimidos if f.filename.endswith('csv'): filename = f.filename.split('/')[-1] print("\033[94m>> Baixando {}/{}\033[0m".format(ano, filename)) with open(caminho + '/' + filename, "wb") as of: of.write(rf.read(f.filename)) def extrair_zip(zp: ZipFile, caminho: str): """ Extrai csvs de um arquivo .zip. Parâmetros ---------- zp: ZipFile conteúdo do arquivo compactado. caminho: str caminho para pasta onde os arquivos devem ser salvos. """ ano = caminho.split('/')[-1] for f in zp.namelist(): if f.endswith('csv'): filename = f.split('/')[-1] print("\033[94m>> Baixando {}/{}\033[0m".format(ano, filename)) with open(caminho + '/' + filename, "wb") as of: of.write(zp.read(f)) def extrair_arquivos(tipo: str, caminho: str, conteudo): """ Extrai csvs de um arquivo compactado. Parâmetros ---------- tipo: str tipo do arquivo: rar ou zip. caminho: str caminho para pasta onde os arquivos devem ser salvos. conteudo bytes do arquivo compactado. """ if tipo == "x-rar-compressed": # Salva temporariamente o .rar with open('file.rar', 'wb') as f: f.write(conteudo) # Extrai arquivos csv with RarFile("file.rar") as rf: extrair_rar(rf, caminho) # Apaga .rar os.remove('file.rar') else: zipfile = ZipFile(BytesIO(conteudo)) with zipfile as zp: extrair_zip(zp, caminho)
from io import BytesIO from zipfile import ZipFile from rarfile import RarFile import os def extrair_rar(rf: RarFile, caminho: str): """ Extrai csvs de um arquivo . rar. Parâmetros ---------- rf: Rarfile conteúdo do arquivo compactado. caminho: str caminho para pasta onde os arquivos devem ser salvos. """ ano = caminho.split('/')[-1] n_arquivos = len(rf.infolist()) for f in rf.infolist(): # Filtra arquivos csvs comprimidos if f.filename.endswith('csv'): filename = f.filename.split('/')[-1] print("\033[94m>> Baixando {}/{}\033[0m".format(ano, filename)) with open(caminho + '/' + filename, "wb") as of: of.write(rf.read(f.filename)) def extrair_zip(zp: ZipFile, caminho: str): """ Extrai csvs de um arquivo .zip. Parâmetros ---------- zp: ZipFile conteúdo do arquivo compactado. caminho: str caminho para pasta onde os arquivos devem ser salvos. """ ano = caminho.split('/')[-1] for f in zp.namelist(): if f.endswith('csv'): filename = f.split('/')[-1] print("\033[94m>> Baixando {}/{}\033[0m".format(ano, filename)) with open(caminho + '/' + filename, "wb") as of: of.write(zp.read(f)) def extrair_arquivos(tipo: str, caminho: str, conteudo): """ Extrai csvs de um arquivo compactado. Parâmetros ---------- tipo: str tipo do arquivo: rar ou zip. caminho: str caminho para pasta onde os arquivos devem ser salvos. conteudo bytes do arquivo compactado. """ if tipo == "x-rar-compressed": # Salva temporariamente o .rar with open('file.rar', 'wb') as f: f.write(conteudo) # Extrai arquivos csv with RarFile("file.rar") as rf: extrair_rar(rf, caminho) # Apaga .rar os.remove('file.rar') else: zipfile = ZipFile(BytesIO(conteudo)) with zipfile as zp: extrair_zip(zp, caminho)
pt
0.859976
Extrai csvs de um arquivo . rar. Parâmetros ---------- rf: Rarfile conteúdo do arquivo compactado. caminho: str caminho para pasta onde os arquivos devem ser salvos. # Filtra arquivos csvs comprimidos Extrai csvs de um arquivo .zip. Parâmetros ---------- zp: ZipFile conteúdo do arquivo compactado. caminho: str caminho para pasta onde os arquivos devem ser salvos. Extrai csvs de um arquivo compactado. Parâmetros ---------- tipo: str tipo do arquivo: rar ou zip. caminho: str caminho para pasta onde os arquivos devem ser salvos. conteudo bytes do arquivo compactado. # Salva temporariamente o .rar # Extrai arquivos csv # Apaga .rar
3.224482
3
SIGCOMM_2016/heavy_hitter/receive.py
ptcrews/p4-mininet-tutorials
23
6623653
<gh_stars>10-100 #!/usr/bin/python # Copyright 2013-present Barefoot Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from scapy.all import sniff from scapy.all import IP, TCP VALID_IPS = ("10.0.0.1", "10.0.0.2", "10.0.0.3") totals = {} def handle_pkt(pkt): if IP in pkt and TCP in pkt: src_ip = pkt[IP].src dst_ip = pkt[IP].dst proto = pkt[IP].proto sport = pkt[TCP].sport dport = pkt[TCP].dport id_tup = (src_ip, dst_ip, proto, sport, dport) if src_ip in VALID_IPS: if id_tup not in totals: totals[id_tup] = 0 totals[id_tup] += 1 print ("Received from %s total: %s" % (id_tup, totals[id_tup])) def main(): sniff(iface = "eth0", prn = lambda x: handle_pkt(x)) if __name__ == '__main__': main()
#!/usr/bin/python # Copyright 2013-present Barefoot Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from scapy.all import sniff from scapy.all import IP, TCP VALID_IPS = ("10.0.0.1", "10.0.0.2", "10.0.0.3") totals = {} def handle_pkt(pkt): if IP in pkt and TCP in pkt: src_ip = pkt[IP].src dst_ip = pkt[IP].dst proto = pkt[IP].proto sport = pkt[TCP].sport dport = pkt[TCP].dport id_tup = (src_ip, dst_ip, proto, sport, dport) if src_ip in VALID_IPS: if id_tup not in totals: totals[id_tup] = 0 totals[id_tup] += 1 print ("Received from %s total: %s" % (id_tup, totals[id_tup])) def main(): sniff(iface = "eth0", prn = lambda x: handle_pkt(x)) if __name__ == '__main__': main()
en
0.831285
#!/usr/bin/python # Copyright 2013-present Barefoot Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
2.361855
2
desafio1.py
elizabethesantos/Python3-Curso-em-video
1
6623654
nome=input('Qual é seu nome?') print(nome+'! Prazer em te conhecer!')
nome=input('Qual é seu nome?') print(nome+'! Prazer em te conhecer!')
none
1
3.464713
3
pygsuite/drive/__init__.py
gitter-badger/pygsuite
0
6623655
from .drive import Drive, FileTypes __all__ = ["Drive", "FileTypes"]
from .drive import Drive, FileTypes __all__ = ["Drive", "FileTypes"]
none
1
1.454287
1
mgxsim/genome_index.py
patrickwest/mgx-sim
0
6623656
from typing import Callable, List, Union from abc import abstractmethod from pathlib import Path import pandas as pd from .genome import Genome class GenomeIndex: def __init__(self): self.metadata = None @abstractmethod def build_index(self) -> pd.DataFrame: pass def __getitem__(self, genome: Genome) -> pd.Series: return self.metadata[self.metadata.genome_path == genome.abs_path] def query( self, query_fn: Callable[[pd.DataFrame], List[Union[Path, str]]] ) -> List[Genome]: genome_paths = query_fn(self.metadata) genomes = [Genome(path) for path in genome_paths] return genomes
from typing import Callable, List, Union from abc import abstractmethod from pathlib import Path import pandas as pd from .genome import Genome class GenomeIndex: def __init__(self): self.metadata = None @abstractmethod def build_index(self) -> pd.DataFrame: pass def __getitem__(self, genome: Genome) -> pd.Series: return self.metadata[self.metadata.genome_path == genome.abs_path] def query( self, query_fn: Callable[[pd.DataFrame], List[Union[Path, str]]] ) -> List[Genome]: genome_paths = query_fn(self.metadata) genomes = [Genome(path) for path in genome_paths] return genomes
none
1
2.834124
3
dkist/io/tests/test_fits.py
DKISTDC/dkist
21
6623657
from pathlib import Path import numpy as np import pytest from numpy.testing import assert_allclose import asdf from dkist.data.test import rootdir from dkist.io.file_manager import FileManager from dkist.io.loaders import AstropyFITSLoader eitdir = Path(rootdir) / 'EIT' @pytest.fixture def relative_ear(): return asdf.ExternalArrayReference("efz20040301.000010_s.fits", 0, "float64", (128, 128)) @pytest.fixture def absolute_ear(): return asdf.ExternalArrayReference(eitdir / "efz20040301.000010_s.fits", 0, "float64", (128, 128)) @pytest.fixture def relative_ac(relative_ear): return FileManager([relative_ear.fileuri], relative_ear.target, relative_ear.dtype, relative_ear.shape, loader=AstropyFITSLoader, basepath=eitdir) @pytest.fixture def relative_fl(relative_ac): return relative_ac._loader_array.flat[0] @pytest.fixture def absolute_ac(absolute_ear): return FileManager([absolute_ear.fileuri], absolute_ear.target, absolute_ear.dtype, absolute_ear.shape, loader=AstropyFITSLoader, basepath=eitdir) @pytest.fixture def absolute_fl(absolute_ac): return absolute_ac._loader_array.flat[0] def test_construct(relative_fl, absolute_fl): for fl in [relative_fl, absolute_fl]: assert fl.shape == (128, 128) assert fl.dtype == "float64" assert fl.absolute_uri == eitdir /"efz20040301.000010_s.fits" for contain in ("efz20040301.000010_s.fits", str(fl.shape), fl.dtype): assert contain in repr(fl) assert contain in str(fl) def test_array(absolute_fl): a = absolute_fl.fits_array assert isinstance(a, np.ndarray) for contain in ("efz20040301.000010_s.fits", str(absolute_fl.shape), absolute_fl.dtype): assert contain in repr(absolute_fl) assert contain in str(absolute_fl) def test_nan(relative_ac, tmpdir): relative_ac.basepath = tmpdir array = relative_ac._generate_array() assert_allclose(array[10:20, :], np.nan) def test_np_array(absolute_fl): narr = np.array(absolute_fl) assert_allclose(narr, absolute_fl.fits_array) assert narr is not absolute_fl.fits_array def test_slicing(absolute_fl): aslice = np.s_[10:20, 10:20] sarr = absolute_fl[aslice] assert_allclose(sarr, absolute_fl.fits_array[aslice])
from pathlib import Path import numpy as np import pytest from numpy.testing import assert_allclose import asdf from dkist.data.test import rootdir from dkist.io.file_manager import FileManager from dkist.io.loaders import AstropyFITSLoader eitdir = Path(rootdir) / 'EIT' @pytest.fixture def relative_ear(): return asdf.ExternalArrayReference("efz20040301.000010_s.fits", 0, "float64", (128, 128)) @pytest.fixture def absolute_ear(): return asdf.ExternalArrayReference(eitdir / "efz20040301.000010_s.fits", 0, "float64", (128, 128)) @pytest.fixture def relative_ac(relative_ear): return FileManager([relative_ear.fileuri], relative_ear.target, relative_ear.dtype, relative_ear.shape, loader=AstropyFITSLoader, basepath=eitdir) @pytest.fixture def relative_fl(relative_ac): return relative_ac._loader_array.flat[0] @pytest.fixture def absolute_ac(absolute_ear): return FileManager([absolute_ear.fileuri], absolute_ear.target, absolute_ear.dtype, absolute_ear.shape, loader=AstropyFITSLoader, basepath=eitdir) @pytest.fixture def absolute_fl(absolute_ac): return absolute_ac._loader_array.flat[0] def test_construct(relative_fl, absolute_fl): for fl in [relative_fl, absolute_fl]: assert fl.shape == (128, 128) assert fl.dtype == "float64" assert fl.absolute_uri == eitdir /"efz20040301.000010_s.fits" for contain in ("efz20040301.000010_s.fits", str(fl.shape), fl.dtype): assert contain in repr(fl) assert contain in str(fl) def test_array(absolute_fl): a = absolute_fl.fits_array assert isinstance(a, np.ndarray) for contain in ("efz20040301.000010_s.fits", str(absolute_fl.shape), absolute_fl.dtype): assert contain in repr(absolute_fl) assert contain in str(absolute_fl) def test_nan(relative_ac, tmpdir): relative_ac.basepath = tmpdir array = relative_ac._generate_array() assert_allclose(array[10:20, :], np.nan) def test_np_array(absolute_fl): narr = np.array(absolute_fl) assert_allclose(narr, absolute_fl.fits_array) assert narr is not absolute_fl.fits_array def test_slicing(absolute_fl): aslice = np.s_[10:20, 10:20] sarr = absolute_fl[aslice] assert_allclose(sarr, absolute_fl.fits_array[aslice])
none
1
2.066391
2
vqa_txt_data/get_answers.py
billyang98/UNITER
0
6623658
<reponame>billyang98/UNITER<gh_stars>0 import json from lz4.frame import compress, decompress import lmdb import msgpack import numpy as np from tqdm import tqdm f_name = '/scratch/cluster/billyang/vqa_dataset/txt_db/oov_datasets/oov_test_set.db' print("Doing {}".format(f_name)) env = lmdb.open(f_name, readonly=True, create=True, map_size=4*1024**4) txn = env.begin() cursor = txn.cursor() ans2label = json.load(open('../utils/ans2label.json')) label2ans = {label: ans for ans, label in ans2label.items()} id_ans = {} for key, value in tqdm(cursor): q = msgpack.loads(decompress(value)) k = key.decode() answer_ids = q['target']['labels'] scores = q['target']['scores'] id_ans[k] = {'ids': answer_ids, 'strings': [label2ans[a] for a in answer_ids], 'scores': scores} json.dump(id_ans, open('oov_test_full_answers.json', 'w'))
import json from lz4.frame import compress, decompress import lmdb import msgpack import numpy as np from tqdm import tqdm f_name = '/scratch/cluster/billyang/vqa_dataset/txt_db/oov_datasets/oov_test_set.db' print("Doing {}".format(f_name)) env = lmdb.open(f_name, readonly=True, create=True, map_size=4*1024**4) txn = env.begin() cursor = txn.cursor() ans2label = json.load(open('../utils/ans2label.json')) label2ans = {label: ans for ans, label in ans2label.items()} id_ans = {} for key, value in tqdm(cursor): q = msgpack.loads(decompress(value)) k = key.decode() answer_ids = q['target']['labels'] scores = q['target']['scores'] id_ans[k] = {'ids': answer_ids, 'strings': [label2ans[a] for a in answer_ids], 'scores': scores} json.dump(id_ans, open('oov_test_full_answers.json', 'w'))
none
1
2.207752
2
harnessed_jobs/tearing_detection/v0/producer_tearing_detection.py
duncanwood/EO-analysis-jobs
2
6623659
<reponame>duncanwood/EO-analysis-jobs<gh_stars>1-10 #!/usr/bin/env ipython """ Producer script for raft-level flat pairs analysis. """ def run_tearing_detection(sensor_id): """ Loop over the acquisition jobs and perform tearing analysis on each. """ import pickle import lsst.eotest.image_utils as imutils import lsst.eotest.sensor as sensorTest import siteUtils from tearing_detection import tearing_detection file_prefix = '%s_%s' % (sensor_id, siteUtils.getRunNumber()) tearing_stats = [] # Create a super bias frame. bias_files = siteUtils.dependency_glob('S*/%s_flat_bias*.fits' % sensor_id, jobname=siteUtils.getProcessName('flat_pair_raft_acq'), description='Bias files:') if bias_files: bias_frame = '%s_superbias.fits' % sensor_id amp_geom = sensorTest.makeAmplifierGeometry(bias_files[0]) imutils.superbias_file(bias_files[:10], amp_geom.serial_overscan, bias_frame) else: bias_frame = None acq_jobs = {('flat_pair_raft_acq', 'N/A'): 'S*/%s_flat*flat?_*.fits', ('qe_raft_acq', 'N/A'): 'S*/%s_lambda_flat_*.fits', ('sflat_raft_acq', 'low_flux'): 'S*/%s_sflat_500_flat_L*.fits', ('sflat_raft_acq', 'high_flux'): 'S*/%s_sflat_500_flat_H*.fits'} for job_key, pattern in acq_jobs.items(): job_name, subset = job_key flats = siteUtils.dependency_glob(pattern % sensor_id, jobname=siteUtils.getProcessName(job_name), description='Flat files:') tearing_found, _ = tearing_detection(flats, bias_frame=bias_frame) tearing_stats.append((job_name, subset, sensor_id, len(tearing_found))) with open('%s_tearing_stats.pkl' % file_prefix, 'wb') as output: pickle.dump(tearing_stats, output) if __name__ == '__main__': import os import json import matplotlib.pyplot as plt import siteUtils import camera_components import lsst.eotest.raft as raftTest from multiprocessor_execution import sensor_analyses processes = 9 # Reserve 1 process per CCD. sensor_analyses(run_tearing_detection, processes=processes) # Divisidero tearing analysis. run = siteUtils.getRunNumber() raft_unit_id = siteUtils.getUnitId() files = siteUtils.dependency_glob('*median_sflat.fits', jobname='dark_defects_raft', description='Superflat files:') raft = camera_components.Raft.create_from_etrav(raft_unit_id, db_name='Prod') det_map = dict([(sensor_id, slot) for slot, sensor_id in raft.items()]) sflat_files = dict() for item in files: slot = det_map[os.path.basename(item).split('_')[0]] sflat_files[slot] = item max_divisidero_tearing \ = raftTest.ana_divisidero_tearing(sflat_files, raft_unit_id, run) plt.savefig(f'{raft_unit_id}_{run}_divisidero.png') with open(f'{raft_unit_id}_{run}_max_divisidero.json', 'w') as fd: json.dump(max_divisidero_tearing, fd)
#!/usr/bin/env ipython """ Producer script for raft-level flat pairs analysis. """ def run_tearing_detection(sensor_id): """ Loop over the acquisition jobs and perform tearing analysis on each. """ import pickle import lsst.eotest.image_utils as imutils import lsst.eotest.sensor as sensorTest import siteUtils from tearing_detection import tearing_detection file_prefix = '%s_%s' % (sensor_id, siteUtils.getRunNumber()) tearing_stats = [] # Create a super bias frame. bias_files = siteUtils.dependency_glob('S*/%s_flat_bias*.fits' % sensor_id, jobname=siteUtils.getProcessName('flat_pair_raft_acq'), description='Bias files:') if bias_files: bias_frame = '%s_superbias.fits' % sensor_id amp_geom = sensorTest.makeAmplifierGeometry(bias_files[0]) imutils.superbias_file(bias_files[:10], amp_geom.serial_overscan, bias_frame) else: bias_frame = None acq_jobs = {('flat_pair_raft_acq', 'N/A'): 'S*/%s_flat*flat?_*.fits', ('qe_raft_acq', 'N/A'): 'S*/%s_lambda_flat_*.fits', ('sflat_raft_acq', 'low_flux'): 'S*/%s_sflat_500_flat_L*.fits', ('sflat_raft_acq', 'high_flux'): 'S*/%s_sflat_500_flat_H*.fits'} for job_key, pattern in acq_jobs.items(): job_name, subset = job_key flats = siteUtils.dependency_glob(pattern % sensor_id, jobname=siteUtils.getProcessName(job_name), description='Flat files:') tearing_found, _ = tearing_detection(flats, bias_frame=bias_frame) tearing_stats.append((job_name, subset, sensor_id, len(tearing_found))) with open('%s_tearing_stats.pkl' % file_prefix, 'wb') as output: pickle.dump(tearing_stats, output) if __name__ == '__main__': import os import json import matplotlib.pyplot as plt import siteUtils import camera_components import lsst.eotest.raft as raftTest from multiprocessor_execution import sensor_analyses processes = 9 # Reserve 1 process per CCD. sensor_analyses(run_tearing_detection, processes=processes) # Divisidero tearing analysis. run = siteUtils.getRunNumber() raft_unit_id = siteUtils.getUnitId() files = siteUtils.dependency_glob('*median_sflat.fits', jobname='dark_defects_raft', description='Superflat files:') raft = camera_components.Raft.create_from_etrav(raft_unit_id, db_name='Prod') det_map = dict([(sensor_id, slot) for slot, sensor_id in raft.items()]) sflat_files = dict() for item in files: slot = det_map[os.path.basename(item).split('_')[0]] sflat_files[slot] = item max_divisidero_tearing \ = raftTest.ana_divisidero_tearing(sflat_files, raft_unit_id, run) plt.savefig(f'{raft_unit_id}_{run}_divisidero.png') with open(f'{raft_unit_id}_{run}_max_divisidero.json', 'w') as fd: json.dump(max_divisidero_tearing, fd)
en
0.702006
#!/usr/bin/env ipython Producer script for raft-level flat pairs analysis. Loop over the acquisition jobs and perform tearing analysis on each. # Create a super bias frame. # Reserve 1 process per CCD. # Divisidero tearing analysis.
2.318041
2
fabfile.py
azkarmoulana/pycon
154
6623660
import json import os import re from fabric.api import cd, env, get, hide, local, put, require, run, settings, sudo, task from fabric.colors import red from fabric.contrib import files, project from fabric.utils import abort, error # Directory structure PROJECT_ROOT = os.path.dirname(__file__) env.project = 'pycon' env.project_user = os.environ['LOGNAME'] env.shell = '/bin/bash -c' env.settings = 'symposion.settings' env.use_ssh_config = True @task def staging(): env.environment = 'staging' env.hosts = ['pycon-staging.iad1.psf.io'] env.site_hostname = 'staging-pycon.python.org' env.root = '/srv/pycon' env.branch = 'staging' setup_path() @task def production(): env.environment = 'production' env.hosts = ['pycon-prod.iad1.psf.io'] env.site_hostname = 'us.pycon.org' env.root = '/srv/pycon' env.branch = 'production' setup_path() def setup_path(): env.home = '/home/psf-users/%(project_user)s/' % env env.code_root = os.path.join(env.root, 'pycon') env.virtualenv_root = os.path.join(env.root, 'env') env.media_root = os.path.join(env.root, 'media') @task def manage_run(command): """Run a Django management command on the remote server.""" if command == 'dbshell': # Need custom code for dbshell to work dbshell() return require('environment') manage_cmd = ("{env.virtualenv_root}/bin/python " "manage.py {command}").format(env=env, command=command) dotenv_path = os.path.join(env.root, 'shared') with cd(env.code_root): sudo(manage_cmd) @task def manage_shell(): """Drop into the remote Django shell.""" manage_run("shell") @task def deploy(): """Deploy to a given environment.""" # NOTE: salt will check every 15 minutes whether the # repo has changed, and if so, redeploy. Or you can use this # to make it run immediately. require('environment') sudo('salt-call state.highstate') @task def ssh(): """Ssh to a given server""" require('environment') local("ssh %s" % env.hosts[0]) @task def dbshell(): require('environment') dsn = sudo('/srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -R default 2>/dev/null', user='pycon').stdout host = '%s@%s' % (env.user, env.hosts[0]) psql = 'psql "%s"' % dsn local("ssh -t %s \'%s\'" % (host, psql)) @task def get_db_dump(dbname, clean=True): """Overwrite your local `dbname` database with the data from the server. The name of your local db is required as an argument, e.g.: fab staging get_db_dump:dbname=mydbname """ require('environment') run('sudo -u pycon /srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -s pgpass -R default 2>/dev/null > ~/.pgpass') run('chmod 600 ~/.pgpass') dump_file = '%(project)s-%(environment)s.sql' % env flags = '-Ox' dsn = sudo('/srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -R default 2>/dev/null', user='pycon').stdout if clean: flags += 'c' pg_dump = 'pg_dump "%s" %s' % (dsn, flags) host = '%s@%s' % (env.user, env.hosts[0]) # save pg_dump output to file in local home directory local('ssh -C %s \'%s\' > ~/%s' % (host, pg_dump, dump_file)) local('dropdb %s; createdb %s' % (dbname, dbname)) local('psql %s -f ~/%s' % (dbname, dump_file)) @task def get_media(root='site_media/media'): """Syncs media files from server to a local dir. Defaults to ./site_media/media; you can override by passing a different relative path as root: fab server get_media:root=my_dir/media/foo Local dir ought to exist already. """ rsync = 'rsync -rvaz %(user)s@%(host)s:%(media_root)s/' % env cmd = '%s ./%s' % (rsync, root) local(cmd) @task def load_db_dump(dump_file): """Given a dump on your home dir on the server, load it to the server's database, overwriting any existing data. BE CAREFUL!""" require('environment') run('sudo -u pycon /srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -s pgpass -R default 2>/dev/null > ~/.pgpass') run('chmod 600 ~/.pgpass') temp_file = os.path.join(env.home, '%(project)s-%(environment)s.sql' % env) put(dump_file, temp_file) dsn = sudo('/srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -R default 2>/dev/null', user='pycon').stdout run('psql "%s" -f %s' % (dsn, temp_file)) @task def make_messages(): """Extract English text from code and templates, and update the .po files for translators to translate""" # Make sure gettext is installed local("gettext --help >/dev/null 2>&1") if os.path.exists("locale/fr/LC_MESSAGES/django.po"): local("python manage.py makemessages -a") else: local("python manage.py makemessages -l fr") @task def compile_messages(): """Compile the translated .po files into more efficient .mo files for runtime use""" # Make sure gettext is installed local("gettext --help >/dev/null 2>&1") local("python manage.py compilemessages")
import json import os import re from fabric.api import cd, env, get, hide, local, put, require, run, settings, sudo, task from fabric.colors import red from fabric.contrib import files, project from fabric.utils import abort, error # Directory structure PROJECT_ROOT = os.path.dirname(__file__) env.project = 'pycon' env.project_user = os.environ['LOGNAME'] env.shell = '/bin/bash -c' env.settings = 'symposion.settings' env.use_ssh_config = True @task def staging(): env.environment = 'staging' env.hosts = ['pycon-staging.iad1.psf.io'] env.site_hostname = 'staging-pycon.python.org' env.root = '/srv/pycon' env.branch = 'staging' setup_path() @task def production(): env.environment = 'production' env.hosts = ['pycon-prod.iad1.psf.io'] env.site_hostname = 'us.pycon.org' env.root = '/srv/pycon' env.branch = 'production' setup_path() def setup_path(): env.home = '/home/psf-users/%(project_user)s/' % env env.code_root = os.path.join(env.root, 'pycon') env.virtualenv_root = os.path.join(env.root, 'env') env.media_root = os.path.join(env.root, 'media') @task def manage_run(command): """Run a Django management command on the remote server.""" if command == 'dbshell': # Need custom code for dbshell to work dbshell() return require('environment') manage_cmd = ("{env.virtualenv_root}/bin/python " "manage.py {command}").format(env=env, command=command) dotenv_path = os.path.join(env.root, 'shared') with cd(env.code_root): sudo(manage_cmd) @task def manage_shell(): """Drop into the remote Django shell.""" manage_run("shell") @task def deploy(): """Deploy to a given environment.""" # NOTE: salt will check every 15 minutes whether the # repo has changed, and if so, redeploy. Or you can use this # to make it run immediately. require('environment') sudo('salt-call state.highstate') @task def ssh(): """Ssh to a given server""" require('environment') local("ssh %s" % env.hosts[0]) @task def dbshell(): require('environment') dsn = sudo('/srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -R default 2>/dev/null', user='pycon').stdout host = '%s@%s' % (env.user, env.hosts[0]) psql = 'psql "%s"' % dsn local("ssh -t %s \'%s\'" % (host, psql)) @task def get_db_dump(dbname, clean=True): """Overwrite your local `dbname` database with the data from the server. The name of your local db is required as an argument, e.g.: fab staging get_db_dump:dbname=mydbname """ require('environment') run('sudo -u pycon /srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -s pgpass -R default 2>/dev/null > ~/.pgpass') run('chmod 600 ~/.pgpass') dump_file = '%(project)s-%(environment)s.sql' % env flags = '-Ox' dsn = sudo('/srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -R default 2>/dev/null', user='pycon').stdout if clean: flags += 'c' pg_dump = 'pg_dump "%s" %s' % (dsn, flags) host = '%s@%s' % (env.user, env.hosts[0]) # save pg_dump output to file in local home directory local('ssh -C %s \'%s\' > ~/%s' % (host, pg_dump, dump_file)) local('dropdb %s; createdb %s' % (dbname, dbname)) local('psql %s -f ~/%s' % (dbname, dump_file)) @task def get_media(root='site_media/media'): """Syncs media files from server to a local dir. Defaults to ./site_media/media; you can override by passing a different relative path as root: fab server get_media:root=my_dir/media/foo Local dir ought to exist already. """ rsync = 'rsync -rvaz %(user)s@%(host)s:%(media_root)s/' % env cmd = '%s ./%s' % (rsync, root) local(cmd) @task def load_db_dump(dump_file): """Given a dump on your home dir on the server, load it to the server's database, overwriting any existing data. BE CAREFUL!""" require('environment') run('sudo -u pycon /srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -s pgpass -R default 2>/dev/null > ~/.pgpass') run('chmod 600 ~/.pgpass') temp_file = os.path.join(env.home, '%(project)s-%(environment)s.sql' % env) put(dump_file, temp_file) dsn = sudo('/srv/pycon/env/bin/python /srv/pycon/pycon/manage.py sqldsn -q -R default 2>/dev/null', user='pycon').stdout run('psql "%s" -f %s' % (dsn, temp_file)) @task def make_messages(): """Extract English text from code and templates, and update the .po files for translators to translate""" # Make sure gettext is installed local("gettext --help >/dev/null 2>&1") if os.path.exists("locale/fr/LC_MESSAGES/django.po"): local("python manage.py makemessages -a") else: local("python manage.py makemessages -l fr") @task def compile_messages(): """Compile the translated .po files into more efficient .mo files for runtime use""" # Make sure gettext is installed local("gettext --help >/dev/null 2>&1") local("python manage.py compilemessages")
en
0.786331
# Directory structure Run a Django management command on the remote server. # Need custom code for dbshell to work Drop into the remote Django shell. Deploy to a given environment. # NOTE: salt will check every 15 minutes whether the # repo has changed, and if so, redeploy. Or you can use this # to make it run immediately. Ssh to a given server Overwrite your local `dbname` database with the data from the server. The name of your local db is required as an argument, e.g.: fab staging get_db_dump:dbname=mydbname # save pg_dump output to file in local home directory Syncs media files from server to a local dir. Defaults to ./site_media/media; you can override by passing a different relative path as root: fab server get_media:root=my_dir/media/foo Local dir ought to exist already. Given a dump on your home dir on the server, load it to the server's database, overwriting any existing data. BE CAREFUL! Extract English text from code and templates, and update the .po files for translators to translate # Make sure gettext is installed Compile the translated .po files into more efficient .mo files for runtime use # Make sure gettext is installed
2.068181
2
links/views.py
moshthepitt/product.co.ke
1
6623661
<reponame>moshthepitt/product.co.ke<filename>links/views.py from django.views.generic.edit import CreateView from django.views.generic.edit import UpdateView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import DeleteView from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext as _ from django.contrib import messages from core.mixins import CachePageOnAuthMixin from .models import Link from .forms import LinkForm class LinkUpdate(UpdateView): model = Link form_class = LinkForm template_name = "links/link_edit.html" success_url = reverse_lazy('home') def form_valid(self, form): form.instance.user = self.request.user messages.add_message(self.request, messages.SUCCESS, _('Successfully updated. Should be live shortly.')) return super(LinkAdd, self).form_valid(form) class LinkAdd(CreateView): model = Link form_class = LinkForm success_url = reverse_lazy('home') template_name = "links/link_add.html" def form_valid(self, form): form.instance.user = self.request.user messages.add_message(self.request, messages.SUCCESS, _('Successfully added, it should be live shortly')) return super(LinkAdd, self).form_valid(form) class UserLinksView(ListView, CachePageOnAuthMixin): model = Link template_name = "links/my_links.html" paginate_by = 50 def get_queryset(self): return Link.objects.active().filter(user=self.request.user) def dispatch(self, *args, **kwargs): return super(UserLinksView, self).dispatch(*args, **kwargs) class LinkView(DetailView, CachePageOnAuthMixin): template_name = "links/link.html" model = Link class UserLinkDelete(DeleteView): model = Link success_url = reverse_lazy('links:user_links') def form_valid(self, form): messages.add_message(self.request, messages.SUCCESS, _('Successfully deleted!')) return super(UserLinkDelete, self).form_valid(form)
from django.views.generic.edit import CreateView from django.views.generic.edit import UpdateView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import DeleteView from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext as _ from django.contrib import messages from core.mixins import CachePageOnAuthMixin from .models import Link from .forms import LinkForm class LinkUpdate(UpdateView): model = Link form_class = LinkForm template_name = "links/link_edit.html" success_url = reverse_lazy('home') def form_valid(self, form): form.instance.user = self.request.user messages.add_message(self.request, messages.SUCCESS, _('Successfully updated. Should be live shortly.')) return super(LinkAdd, self).form_valid(form) class LinkAdd(CreateView): model = Link form_class = LinkForm success_url = reverse_lazy('home') template_name = "links/link_add.html" def form_valid(self, form): form.instance.user = self.request.user messages.add_message(self.request, messages.SUCCESS, _('Successfully added, it should be live shortly')) return super(LinkAdd, self).form_valid(form) class UserLinksView(ListView, CachePageOnAuthMixin): model = Link template_name = "links/my_links.html" paginate_by = 50 def get_queryset(self): return Link.objects.active().filter(user=self.request.user) def dispatch(self, *args, **kwargs): return super(UserLinksView, self).dispatch(*args, **kwargs) class LinkView(DetailView, CachePageOnAuthMixin): template_name = "links/link.html" model = Link class UserLinkDelete(DeleteView): model = Link success_url = reverse_lazy('links:user_links') def form_valid(self, form): messages.add_message(self.request, messages.SUCCESS, _('Successfully deleted!')) return super(UserLinkDelete, self).form_valid(form)
none
1
2.081106
2
server/books/api/views.py
zubeir68/my-library
0
6623662
<filename>server/books/api/views.py<gh_stars>0 from rest_framework import generics, mixins from books.models import Book from .serializers import bookSerializer class bookAPIView(mixins.CreateModelMixin, generics.ListAPIView): resource_name = 'books' serializer_class = bookSerializer serializer_class = bookSerializer def get_queryset(self): return Book.objects.all() def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class bookRudView(generics.RetrieveUpdateDestroyAPIView): resource_name = 'books' lookup_field = 'id' serializer_class = bookSerializer def get_queryset(self): return Book.objects.all()
<filename>server/books/api/views.py<gh_stars>0 from rest_framework import generics, mixins from books.models import Book from .serializers import bookSerializer class bookAPIView(mixins.CreateModelMixin, generics.ListAPIView): resource_name = 'books' serializer_class = bookSerializer serializer_class = bookSerializer def get_queryset(self): return Book.objects.all() def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class bookRudView(generics.RetrieveUpdateDestroyAPIView): resource_name = 'books' lookup_field = 'id' serializer_class = bookSerializer def get_queryset(self): return Book.objects.all()
none
1
2.283364
2
2020/14/14-python.py
allengarvin/adventofcode
0
6623663
#!/usr/bin/python import sys, os, argparse, operator, re from parse import parse def apply_mask1(num, mask): num |= mask[0] num &= mask[1] return num def apply_mask2(addr, num, mask, core): masks = [0] for n, b in enumerate(mask[0]): if b == "X": for m in masks[:]: masks.append(m | (2**(35-n))) for m in masks: core[addr | m] = num def problem1(fn): core = dict() mask = [ 0, 0xfffffffff] for line in open(fn): line = line.strip() if line.startswith("mask"): mask = [ 0, 0xfffffffff] for n, bit in enumerate(list(line.split(" = ")[1])): if bit.isdigit(): if bit == "1": mask[0] |= 2**(35-n) elif bit == "0": mask[1] ^= 2**(35-n) if line.startswith("mem"): mem = parse("mem[{:d}] = {:d}", line) core[mem[0]] = apply_mask1(mem[1], mask) return sum(core.values()) def problem2(fn): core = dict() for line in open(args.file): line = line.strip() if line.startswith("mask"): m = line.split(" = ")[1] mask = [["X" if x == "X" else 0 for x in list(m)], 0] for n, bit in enumerate(list(m)): if bit.isdigit() and bit == "1": mask[1] |= 2**(35-n) if line.startswith("mem"): addr, num = parse("mem[{:d}] = {:d}", line) addr |= int(m.replace("X", "0"), 2) addr &= 0xfffffffff & int(m.replace("0", "1").replace("X", "0"),2) apply_mask2(addr, num, mask, core) return sum(core.values()) def main(args): print("Problem 1: %d" % problem1(args.file)) print("Problem 2: %d" % problem2(args.file)) if __name__ == "__main__": default_file = sys.argv[0].split("-")[0] + "-input.txt" ap = argparse.ArgumentParser(description="2020 Day 14 AOC: Docking data") ap.add_argument("file", help="Input file", default=default_file, nargs="?") args = ap.parse_args() main(args)
#!/usr/bin/python import sys, os, argparse, operator, re from parse import parse def apply_mask1(num, mask): num |= mask[0] num &= mask[1] return num def apply_mask2(addr, num, mask, core): masks = [0] for n, b in enumerate(mask[0]): if b == "X": for m in masks[:]: masks.append(m | (2**(35-n))) for m in masks: core[addr | m] = num def problem1(fn): core = dict() mask = [ 0, 0xfffffffff] for line in open(fn): line = line.strip() if line.startswith("mask"): mask = [ 0, 0xfffffffff] for n, bit in enumerate(list(line.split(" = ")[1])): if bit.isdigit(): if bit == "1": mask[0] |= 2**(35-n) elif bit == "0": mask[1] ^= 2**(35-n) if line.startswith("mem"): mem = parse("mem[{:d}] = {:d}", line) core[mem[0]] = apply_mask1(mem[1], mask) return sum(core.values()) def problem2(fn): core = dict() for line in open(args.file): line = line.strip() if line.startswith("mask"): m = line.split(" = ")[1] mask = [["X" if x == "X" else 0 for x in list(m)], 0] for n, bit in enumerate(list(m)): if bit.isdigit() and bit == "1": mask[1] |= 2**(35-n) if line.startswith("mem"): addr, num = parse("mem[{:d}] = {:d}", line) addr |= int(m.replace("X", "0"), 2) addr &= 0xfffffffff & int(m.replace("0", "1").replace("X", "0"),2) apply_mask2(addr, num, mask, core) return sum(core.values()) def main(args): print("Problem 1: %d" % problem1(args.file)) print("Problem 2: %d" % problem2(args.file)) if __name__ == "__main__": default_file = sys.argv[0].split("-")[0] + "-input.txt" ap = argparse.ArgumentParser(description="2020 Day 14 AOC: Docking data") ap.add_argument("file", help="Input file", default=default_file, nargs="?") args = ap.parse_args() main(args)
ru
0.258958
#!/usr/bin/python
2.988604
3
tests/krankshaft/test_serializer.py
VeritasOS/krankshaft
0
6623664
<gh_stars>0 from __future__ import absolute_import from datetime import date, datetime, time, timedelta from decimal import Decimal from django.core.handlers.wsgi import WSGIRequest from django.test.client import FakePayload from krankshaft.serializer import Serializer from tests.base import TestCaseNoDB from urlparse import urlparse import pytz class SerializerConvertTest(TestCaseNoDB): dt = datetime(2013, 6, 8, 14, 34, 28, 121251) dt_expect = '2013-06-08T14:34:28.121251' td = timedelta(1, 2, 3) tz = pytz.timezone('America/Chicago') def do(self, obj, expect): self.assertEquals(expect, self.serializer.convert(obj)) def setUp(self): self.serializer = Serializer() def test_date(self): self.do(self.dt.date(), self.value(self.dt_expect.split('T')[0])) def test_datetime(self): self.do(self.dt, self.value(self.dt_expect)) def test_datetime_with_timezone(self): self.do( self.tz.normalize(self.tz.localize(self.dt)), self.value(self.dt_expect + '-05:00') ) def test_decimal(self): self.do(Decimal('1.7921579150'), self.value('1.7921579150')) def test_dict(self): self.do( {'key': self.dt}, {'key': self.dt_expect} ) def test_list(self): self.do( [self.dt], [self.dt_expect] ) def test_primitive(self): for value in self.serializer.primitive_values + (1, 1L, 1.1, 'a', u'a'): self.assertEquals(value, self.serializer.convert(value)) def test_serializer_default_content_type(self): serializer = Serializer( default_content_type='application/json' ) content, content_type = serializer.serialize({'key': 'value'}) self.assertEquals(content, '{"key": "value"}') self.assertEquals(content_type, 'application/json') def test_time(self): self.do(self.dt.time(), self.value(self.dt_expect.split('T')[1])) def test_timedelta(self): self.do(self.td, self.value(86402.000003)) def test_tuple(self): self.do( (self.dt,), [self.dt_expect] ) def test_unserializable(self): self.assertRaises(TypeError, self.serializer.convert, object()) def value(self, val): return val class SerializerJSONTest(SerializerConvertTest): def do(self, obj, expect): self.assertEquals(expect, self.serializer.to_json(obj)) def setUp(self): self.serializer = Serializer() def test_dict(self): self.do( {'key': self.dt}, '{"key": "%s"}' % self.dt_expect ) def test_list(self): self.do( [self.dt], '["%s"]' % self.dt_expect ) def test_tuple(self): self.do( (self.dt,), '["%s"]' % self.dt_expect ) def test_unserializable(self): self.assertRaises(TypeError, self.serializer.to_json, object()) def value(self, val): if isinstance(val, basestring): return '"%s"' % val else: return str(val) class SerializerSerializeTest(TestCaseNoDB): def setUp(self): self.dt = SerializerConvertTest.dt self.dt_expect = SerializerConvertTest.dt_expect self.serializer = Serializer() self.data = {'key': self.dt} def test_application_json(self): content, content_type = \ self.serializer.serialize(self.data, 'application/json') self.assertEquals(content_type, 'application/json') self.assertEquals( content, '{"key": "%s"}' % self.dt_expect ) def test_application_json_indent(self): content, content_type = \ self.serializer.serialize(self.data, 'application/json; indent=4') self.assertEquals(content_type, 'application/json') self.assertEquals( content, '{\n "key": "%s"\n}' % self.dt_expect ) def test_application_json_indent_invalid(self): content, content_type = \ self.serializer.serialize(self.data, 'application/json; indent=a') self.assertEquals(content_type, 'application/json') self.assertEquals( content, '{"key": "%s"}' % self.dt_expect ) def test_application_json_q(self): content, content_type = \ self.serializer.serialize(self.data, 'application/json; q=0.5') self.assertEquals(content_type, 'application/json') self.assertEquals( content, '{"key": "%s"}' % self.dt_expect ) def test_default(self): content, content_type = \ self.serializer.serialize(self.data) self.assertEquals(content_type, self.serializer.default_content_type) self.assertEquals( content, '{"key": "%s"}' % self.dt_expect ) def test_unsupported(self): self.assertRaises( self.serializer.Unsupported, self.serializer.get_format, 'unsupported/content-type' ) class SerializerDeserializeTest(TestCaseNoDB): def setUp(self): self.data = {'key': 'value'} self.serializer = Serializer() def test_application_json(self): self.assertEquals( self.data, self.serializer.deserialize('{"key": "value"}', 'application/json') ) def test_application_json_indent(self): self.assertEquals( self.data, self.serializer \ .deserialize('{"key": "value"}', 'application/json; indent=4') ) def test_invalid_data(self): for content_type in self.serializer.content_types.keys(): if content_type.startswith('multipart/'): continue self.assertRaises( ValueError, self.serializer.deserialize, 'invalid body data', content_type ) def test_invalid_multipart_boundary(self): data = 'data' boundary = '\xffinvalid boundary' parsed = urlparse('/path/') environ = self.client._base_environ(**{ 'CONTENT_TYPE': 'multipart/form-data; boundary=%s' % boundary, 'CONTENT_LENGTH': len(data), 'PATH_INFO': self.client._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(data), }) request = WSGIRequest(environ) for content_type in self.serializer.content_types.keys(): if not content_type.startswith('multipart/'): continue self.assertRaises( ValueError, self.serializer.deserialize_request, request, request.META['CONTENT_TYPE'] ) def test_invalid_multipart_content_length(self): data = 'data' boundary = 'boundary' parsed = urlparse('/path/') environ = self.client._base_environ(**{ 'CONTENT_TYPE': 'multipart/form-data; boundary=%s' % boundary, 'CONTENT_LENGTH': -1, 'PATH_INFO': self.client._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(data), }) request = WSGIRequest(environ) for content_type in self.serializer.content_types.keys(): if not content_type.startswith('multipart/'): continue self.assertRaises( ValueError, self.serializer.deserialize_request, request, request.META['CONTENT_TYPE'] ) class SerializerFormatTest(TestCaseNoDB): def setUp(self): self.serializer = Serializer() def test_get_content_type_json(self): self.assertEquals( self.serializer.get_content_type('json'), 'application/json' )
from __future__ import absolute_import from datetime import date, datetime, time, timedelta from decimal import Decimal from django.core.handlers.wsgi import WSGIRequest from django.test.client import FakePayload from krankshaft.serializer import Serializer from tests.base import TestCaseNoDB from urlparse import urlparse import pytz class SerializerConvertTest(TestCaseNoDB): dt = datetime(2013, 6, 8, 14, 34, 28, 121251) dt_expect = '2013-06-08T14:34:28.121251' td = timedelta(1, 2, 3) tz = pytz.timezone('America/Chicago') def do(self, obj, expect): self.assertEquals(expect, self.serializer.convert(obj)) def setUp(self): self.serializer = Serializer() def test_date(self): self.do(self.dt.date(), self.value(self.dt_expect.split('T')[0])) def test_datetime(self): self.do(self.dt, self.value(self.dt_expect)) def test_datetime_with_timezone(self): self.do( self.tz.normalize(self.tz.localize(self.dt)), self.value(self.dt_expect + '-05:00') ) def test_decimal(self): self.do(Decimal('1.7921579150'), self.value('1.7921579150')) def test_dict(self): self.do( {'key': self.dt}, {'key': self.dt_expect} ) def test_list(self): self.do( [self.dt], [self.dt_expect] ) def test_primitive(self): for value in self.serializer.primitive_values + (1, 1L, 1.1, 'a', u'a'): self.assertEquals(value, self.serializer.convert(value)) def test_serializer_default_content_type(self): serializer = Serializer( default_content_type='application/json' ) content, content_type = serializer.serialize({'key': 'value'}) self.assertEquals(content, '{"key": "value"}') self.assertEquals(content_type, 'application/json') def test_time(self): self.do(self.dt.time(), self.value(self.dt_expect.split('T')[1])) def test_timedelta(self): self.do(self.td, self.value(86402.000003)) def test_tuple(self): self.do( (self.dt,), [self.dt_expect] ) def test_unserializable(self): self.assertRaises(TypeError, self.serializer.convert, object()) def value(self, val): return val class SerializerJSONTest(SerializerConvertTest): def do(self, obj, expect): self.assertEquals(expect, self.serializer.to_json(obj)) def setUp(self): self.serializer = Serializer() def test_dict(self): self.do( {'key': self.dt}, '{"key": "%s"}' % self.dt_expect ) def test_list(self): self.do( [self.dt], '["%s"]' % self.dt_expect ) def test_tuple(self): self.do( (self.dt,), '["%s"]' % self.dt_expect ) def test_unserializable(self): self.assertRaises(TypeError, self.serializer.to_json, object()) def value(self, val): if isinstance(val, basestring): return '"%s"' % val else: return str(val) class SerializerSerializeTest(TestCaseNoDB): def setUp(self): self.dt = SerializerConvertTest.dt self.dt_expect = SerializerConvertTest.dt_expect self.serializer = Serializer() self.data = {'key': self.dt} def test_application_json(self): content, content_type = \ self.serializer.serialize(self.data, 'application/json') self.assertEquals(content_type, 'application/json') self.assertEquals( content, '{"key": "%s"}' % self.dt_expect ) def test_application_json_indent(self): content, content_type = \ self.serializer.serialize(self.data, 'application/json; indent=4') self.assertEquals(content_type, 'application/json') self.assertEquals( content, '{\n "key": "%s"\n}' % self.dt_expect ) def test_application_json_indent_invalid(self): content, content_type = \ self.serializer.serialize(self.data, 'application/json; indent=a') self.assertEquals(content_type, 'application/json') self.assertEquals( content, '{"key": "%s"}' % self.dt_expect ) def test_application_json_q(self): content, content_type = \ self.serializer.serialize(self.data, 'application/json; q=0.5') self.assertEquals(content_type, 'application/json') self.assertEquals( content, '{"key": "%s"}' % self.dt_expect ) def test_default(self): content, content_type = \ self.serializer.serialize(self.data) self.assertEquals(content_type, self.serializer.default_content_type) self.assertEquals( content, '{"key": "%s"}' % self.dt_expect ) def test_unsupported(self): self.assertRaises( self.serializer.Unsupported, self.serializer.get_format, 'unsupported/content-type' ) class SerializerDeserializeTest(TestCaseNoDB): def setUp(self): self.data = {'key': 'value'} self.serializer = Serializer() def test_application_json(self): self.assertEquals( self.data, self.serializer.deserialize('{"key": "value"}', 'application/json') ) def test_application_json_indent(self): self.assertEquals( self.data, self.serializer \ .deserialize('{"key": "value"}', 'application/json; indent=4') ) def test_invalid_data(self): for content_type in self.serializer.content_types.keys(): if content_type.startswith('multipart/'): continue self.assertRaises( ValueError, self.serializer.deserialize, 'invalid body data', content_type ) def test_invalid_multipart_boundary(self): data = 'data' boundary = '\xffinvalid boundary' parsed = urlparse('/path/') environ = self.client._base_environ(**{ 'CONTENT_TYPE': 'multipart/form-data; boundary=%s' % boundary, 'CONTENT_LENGTH': len(data), 'PATH_INFO': self.client._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(data), }) request = WSGIRequest(environ) for content_type in self.serializer.content_types.keys(): if not content_type.startswith('multipart/'): continue self.assertRaises( ValueError, self.serializer.deserialize_request, request, request.META['CONTENT_TYPE'] ) def test_invalid_multipart_content_length(self): data = 'data' boundary = 'boundary' parsed = urlparse('/path/') environ = self.client._base_environ(**{ 'CONTENT_TYPE': 'multipart/form-data; boundary=%s' % boundary, 'CONTENT_LENGTH': -1, 'PATH_INFO': self.client._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(data), }) request = WSGIRequest(environ) for content_type in self.serializer.content_types.keys(): if not content_type.startswith('multipart/'): continue self.assertRaises( ValueError, self.serializer.deserialize_request, request, request.META['CONTENT_TYPE'] ) class SerializerFormatTest(TestCaseNoDB): def setUp(self): self.serializer = Serializer() def test_get_content_type_json(self): self.assertEquals( self.serializer.get_content_type('json'), 'application/json' )
none
1
2.175043
2
computer-basic/practice/rock-scissors-paper.py
dearjsmc4/basic
0
6623665
# 절차지향적 프로그래밍 # 1. 상대방으로부터 문자열을 받기. import random def get_player_choice(): """ get_player_choice() --> string 반환 반환값 : "가위" or "바위" or "보" """ li=("가위","바위","보") mine=input("선택해라 휴먼 : ") while mine not in li: mine=input("똑바로 선택해라 휴먼 : ") return mine def get_computer_choice(): """ get_computer_choice() --> string 반환 반환값: "가위" | "바위" | "보" """ li=("가위","바위","보") computer=random.randint(0,2) computer=li[computer] return computer def who_wins(player, com): """ who_wins(player, com) --> string 반환값 : 플레이어가 이기면 문자로 "player" 컴퓨터가 이기면 문자로 "computer" 비기면 None """ if player == com: return None elif (player == "가위" and com == "보")or \ (player == "바위" and com == "가위")or \ (player == "보" and com == "바위"): return "player" elif (player == "가위" and com == "바위")or \ (player == "바위" and com == "보")or \ (player == "보" and com == "가위"): return "computer" def play_one(): """ who_wins(player, com) --> string 반환값 : 플레이어가 이기면 문자로 "player" 컴퓨터가 이기면 문자로 "computer" """ while True: player=get_player_choice() com=get_computer_choice() result = who_wins(player, com) print(f"player:{player}, computer: {com}") if result == "player": print("이겼다") return "player" elif result == "computer": print("졌다") return "computer" else: print("비겼다") continue def check_final_winner(result): """ check_final_winner(result) --> string result : ex) ['player', 'player'] 반환값 : 만약 result 안에 'player' 가 두 개 이상이면 : 'player' 'computer' 가 두 개 이상이면 : 'computer' otherwise : none """ print(f"player: {result.count('player')}승, computer: {result.count('computer')}승") if result.count('player') >= 2: return "player" elif result.count('computer') >= 2: return "computer" else: None def play(): """ play() --> none 3판 2선승 가위바위보 게임 """ result_list=[] while True: result_list.append(play_one()) checked=check_final_winner(result_list) if checked=="player": print("당신이 이겼다") break elif checked=="computer": print("당신이 졌다") break else: continue if __name__ == "__main__": play()
# 절차지향적 프로그래밍 # 1. 상대방으로부터 문자열을 받기. import random def get_player_choice(): """ get_player_choice() --> string 반환 반환값 : "가위" or "바위" or "보" """ li=("가위","바위","보") mine=input("선택해라 휴먼 : ") while mine not in li: mine=input("똑바로 선택해라 휴먼 : ") return mine def get_computer_choice(): """ get_computer_choice() --> string 반환 반환값: "가위" | "바위" | "보" """ li=("가위","바위","보") computer=random.randint(0,2) computer=li[computer] return computer def who_wins(player, com): """ who_wins(player, com) --> string 반환값 : 플레이어가 이기면 문자로 "player" 컴퓨터가 이기면 문자로 "computer" 비기면 None """ if player == com: return None elif (player == "가위" and com == "보")or \ (player == "바위" and com == "가위")or \ (player == "보" and com == "바위"): return "player" elif (player == "가위" and com == "바위")or \ (player == "바위" and com == "보")or \ (player == "보" and com == "가위"): return "computer" def play_one(): """ who_wins(player, com) --> string 반환값 : 플레이어가 이기면 문자로 "player" 컴퓨터가 이기면 문자로 "computer" """ while True: player=get_player_choice() com=get_computer_choice() result = who_wins(player, com) print(f"player:{player}, computer: {com}") if result == "player": print("이겼다") return "player" elif result == "computer": print("졌다") return "computer" else: print("비겼다") continue def check_final_winner(result): """ check_final_winner(result) --> string result : ex) ['player', 'player'] 반환값 : 만약 result 안에 'player' 가 두 개 이상이면 : 'player' 'computer' 가 두 개 이상이면 : 'computer' otherwise : none """ print(f"player: {result.count('player')}승, computer: {result.count('computer')}승") if result.count('player') >= 2: return "player" elif result.count('computer') >= 2: return "computer" else: None def play(): """ play() --> none 3판 2선승 가위바위보 게임 """ result_list=[] while True: result_list.append(play_one()) checked=check_final_winner(result_list) if checked=="player": print("당신이 이겼다") break elif checked=="computer": print("당신이 졌다") break else: continue if __name__ == "__main__": play()
ko
0.92625
# 절차지향적 프로그래밍 # 1. 상대방으로부터 문자열을 받기. get_player_choice() --> string 반환 반환값 : "가위" or "바위" or "보" get_computer_choice() --> string 반환 반환값: "가위" | "바위" | "보" who_wins(player, com) --> string 반환값 : 플레이어가 이기면 문자로 "player" 컴퓨터가 이기면 문자로 "computer" 비기면 None who_wins(player, com) --> string 반환값 : 플레이어가 이기면 문자로 "player" 컴퓨터가 이기면 문자로 "computer" check_final_winner(result) --> string result : ex) ['player', 'player'] 반환값 : 만약 result 안에 'player' 가 두 개 이상이면 : 'player' 'computer' 가 두 개 이상이면 : 'computer' otherwise : none play() --> none 3판 2선승 가위바위보 게임
3.968307
4
backend/account_handlers/withdraw.py
rhedgeco/dank_bank
0
6623666
<reponame>rhedgeco/dank_bank<filename>backend/account_handlers/withdraw.py import falcon from ..authenticator import get_id_from_token from ..param_handler import validate_params from ..database_manager import withdraw_money, get_account_by_id class Withdraw: @staticmethod def on_post(req, resp): if not validate_params(req.params, 'authToken', 'account_id', 'amount'): resp.status = falcon.HTTP_BAD_REQUEST return user_id = get_id_from_token(req.params['authToken']) if not user_id: resp.status = falcon.HTTP_UNAUTHORIZED return amount = float(req.params['amount']) if amount < 0: resp.status = falcon.HTTP_UNAUTHORIZED return from_account = get_account_by_id(req.params['account_id']) # if account is not owned by current user, fail if from_account['user_id'] != user_id: resp.status = falcon.HTTP_UNAUTHORIZED return # if account balance is not sufficient, fail if float(from_account['balance']) < amount: resp.status = falcon.HTTP_UNAUTHORIZED resp.body = "Insufficient Funds" return withdraw_money(from_account['account_id'], amount)
import falcon from ..authenticator import get_id_from_token from ..param_handler import validate_params from ..database_manager import withdraw_money, get_account_by_id class Withdraw: @staticmethod def on_post(req, resp): if not validate_params(req.params, 'authToken', 'account_id', 'amount'): resp.status = falcon.HTTP_BAD_REQUEST return user_id = get_id_from_token(req.params['authToken']) if not user_id: resp.status = falcon.HTTP_UNAUTHORIZED return amount = float(req.params['amount']) if amount < 0: resp.status = falcon.HTTP_UNAUTHORIZED return from_account = get_account_by_id(req.params['account_id']) # if account is not owned by current user, fail if from_account['user_id'] != user_id: resp.status = falcon.HTTP_UNAUTHORIZED return # if account balance is not sufficient, fail if float(from_account['balance']) < amount: resp.status = falcon.HTTP_UNAUTHORIZED resp.body = "Insufficient Funds" return withdraw_money(from_account['account_id'], amount)
en
0.914786
# if account is not owned by current user, fail # if account balance is not sufficient, fail
2.515187
3
coordinate_tools.py
dmholtz/RoboticArm
1
6623667
<filename>coordinate_tools.py import numpy as np import math class Transformation(): """Handles cartesian coordinate transformations. """ def __init__(self, rotation_matrix, translation_vector, \ calc_inverse = True): """Initializes a coordinate transformation object. Accepts a rotation matrix and a translation vector, by which a linear coordinate transformation is defined. Calculates the the inverse transformation function and stores it as a CoordinateTransformation object. Args: * rotation_matrix (numpy.matrix): a real 3 by 3 orthogonal matrix * translation_vector (numpy.array): a real 3 by 1 column vector * calc_inverse (bool): (optional) automatically calculate an inverse transformation for this transformation Raises: * ValueError: If either translation_vector or rotation_matrix are not 3-dimensional * LinearAlgebraError: If rotation_matrix is not a orthogonal 3 by 3 matrix """ if not Coordinate.valid_vector(translation_vector): raise ValueError('Translation vector must be a 3x1 numpy \ array') if not Coordinate.valid_matrix(rotation_matrix): raise ValueError('Rotation matrix must be a 3x3 numpy matrix') if not Coordinate.orthogonal_matrix(rotation_matrix): raise LinearAlgebraError('Rotation matrix is not orthogonal \ and can thus not represent a cartesian coordinate system') self.__rotation_matrix = rotation_matrix self.__translation_vector = translation_vector if calc_inverse: self.__inverse_transformation = self._calc_inverse_transformation() else: self.__inverse_transformation = None @classmethod def from_translation(cls, translation_vector): """Returns a translation coordinate transformation. Args: * translation_vector (np.array): 3x1 column vector which represents the translation Raises: * ValueError: if translation_vector is not a valid 3x1 numpy vector """ if not Coordinate.valid_vector(translation_vector): raise ValueError('Translation vector must be a 3x1 numpy array') return cls(np.eye(3), translation_vector) @classmethod def from_identity(cls): """Returns the identity coordinate transformation. """ return cls(np.eye(3), np.zeros(3)) @classmethod def from_composition(cls, outer, inner): """Returns a transformation object, which represent the compostion g∘f, where f is the inner and g is the outer transformation function. Args: * outer (Transformation) * inner (Transformation) """ rotation_matrix = np.dot(outer.get_rotation(), \ inner.get_rotation()) translation_vector = np.dot(outer.get_rotation(), \ inner.get_translation()) + outer.get_translation() return cls(rotation_matrix, translation_vector) @classmethod def from_pipeline(cls, pipeline): """Returns a transformation object, which represent the outcome of n composed transformations, which are given in a pipeline. Args: * pipeline (list of Transformation objects): The list consists of zero to n transformations, which are sorted according to the composition. The first element represents the outermost function and the last element represents the innermost function. """ result = Transformation.from_identity() for next_transform in pipeline: assert isinstance(next_transform, Transformation) result = Transformation.from_composition(result, next_transform) return result def get_rotation(self): """Returns the rotation matrix. """ return self.__rotation_matrix def get_translation(self): """Returns the translation vector. """ return self.__translation_vector def get_inverse(self): """Returns the inverse transformation. Calculates this function if necessary. """ if self.__inverse_transformation is None: self.__inverse_transformation = self._calc_inverse_transformation() return self.__inverse_transformation def transform(self, affine_vector): """Transforms an affine vector to base coordinates. Args: * affine_vecotr (numpy.array): a real 3 by 1 column vector Raises: * ValueError: If affine_vector is not 3-dimensional """ if not Coordinate.valid_vector(affine_vector): raise ValueError('Affine vector must be a 3x1 dimensonal numpy \ array') return np.dot(self.__rotation_matrix, affine_vector) \ + self.__translation_vector def retransform(self, base_vector): """Transforms an base vector to affine coordinates. Args: * base_vector (numpy.array): a real 3 by 1 column vector Raises: * ValueError: If base_vector is not 3-dimensional """ if not Coordinate.valid_vector(base_vector): raise ValueError('Base vector must be a 3x1 dimensonal numpy \ array') return self.__inverse_transformation.transform(base_vector) def _calc_inverse_transformation(self): """Calculates the inverse transformation function of this object. """ inverse_matrix = np.linalg.inv(self.__rotation_matrix) inverse_vector = -np.dot(inverse_matrix, self.__translation_vector) return Transformation(inverse_matrix, inverse_vector, calc_inverse=False) class Coordinate(): """Provides useful tools to use numpy vectors as coordinate vectors. This class is considered to be a toolbox for handling numpy vectors. To ensure maximum compatibility accross standard python libraries, numpy arrays are preferred over proprietary Coordinate objects. """ @staticmethod def valid_vector(vector): """Returns true if vector is 3 by 1 dimensional and false otherwise. Args: * vector (numpy.array) """ return (vector.shape == (3,)) or (vector.shape == (3,1)) @staticmethod def valid_matrix(matrix): """Returns true if matrix is 3 by 3 dimensional and false otherwise. Args: * matrix (numpy.matrix) """ return matrix.shape == (3,3) @staticmethod def orthogonal_matrix(matrix): """Returns true if matrix orthogonal and false otherwise. A matrix A is orthogonal if and only if A multiplied by its transpose is an identity matrix. Args: * matrix (numpy.matrix) """ return np.allclose(np.dot(matrix, np.transpose(matrix)), np.eye(3)) class Trigonometry(): """Provides some useful trigonometric formulas. """ @staticmethod def cosine_sentence(a, b, c): """Returns gamma from a Triangle abc by applying the cosine sentence. Args: * a, b, c (double): lengths of the triangle: a, b, c > 0 Raises: * ValueError: If any of the parameters is less or equal than zero """ if a <= 0 or b <= 0 or c <= 0: raise ValueError('Every length in a triangle has to be greater than\ 0') return math.acos((a*a+b*b-c*c)/(2*a*b)) class RotationMatrix(): def __init__(self, rotation_vector): """Accepts the rotation vector and prepares future calculations. Args: * rotation_vector (np.array): must be a 3x1 numpy vector Raises_ * ValueError: if rotation_vector is not a valid vector """ if not Coordinate.valid_vector(rotation_vector): raise ValueError('Rotation vector must be a 3x1 numpy array') unit_vector = rotation_vector / np.linalg.norm(rotation_vector) unit_vector = np.reshape(unit_vector, (3,1)) self._rotation_vector = unit_vector # outer product of two vectors is a matrix self._outer_product = np.dot(unit_vector, np.transpose(unit_vector)) self._cosine_matrix = np.eye(3) - self._outer_product uv1 = np.ndarray.item(unit_vector[0]) uv2 = np.ndarray.item(unit_vector[1]) uv3 = np.ndarray.item(unit_vector[2]) self._cross_matrix = np.array([[0,-uv3, uv2],[uv3,0,-uv1], \ [-uv2, uv1,0]]) @classmethod def from_axis(cls, axis = 'z'): """Returns a rotation matrix object for a given coordinate axis. Args: * axis (str): textual axis description Raises: * ValueError: if textual description does not match any coordinate axis """ if axis == 'x' or axis == 'X': return cls(np.array([1,0,0])) if axis == 'y' or axis == 'Y': return cls(np.array([0,1,0])) if axis == 'z' or axis == 'Z': return cls(np.array([0,0,1])) else: raise ValueError('Axis is not a coordinate axis.') def matrix_at_angle(self, angle): """Returns a rotation matrix for this instances axis for a given angle. See: * Formula "Rotation matrix from axis and angle": https://w.wiki/Knf Args: * angle (double): angle of the affine COS's rotation with respect to the reference COS """ return np.cos(angle) * self._cosine_matrix + self._outer_product + \ np.sin(angle) * self._cross_matrix class LinearAlgebraError(Exception): """Exception raised for invalid linear algebra operations related to transformation process of cartesian cooridinate systems. Attributes: message -- explanation of the error """ def __init__(self, message): self.message = message
<filename>coordinate_tools.py import numpy as np import math class Transformation(): """Handles cartesian coordinate transformations. """ def __init__(self, rotation_matrix, translation_vector, \ calc_inverse = True): """Initializes a coordinate transformation object. Accepts a rotation matrix and a translation vector, by which a linear coordinate transformation is defined. Calculates the the inverse transformation function and stores it as a CoordinateTransformation object. Args: * rotation_matrix (numpy.matrix): a real 3 by 3 orthogonal matrix * translation_vector (numpy.array): a real 3 by 1 column vector * calc_inverse (bool): (optional) automatically calculate an inverse transformation for this transformation Raises: * ValueError: If either translation_vector or rotation_matrix are not 3-dimensional * LinearAlgebraError: If rotation_matrix is not a orthogonal 3 by 3 matrix """ if not Coordinate.valid_vector(translation_vector): raise ValueError('Translation vector must be a 3x1 numpy \ array') if not Coordinate.valid_matrix(rotation_matrix): raise ValueError('Rotation matrix must be a 3x3 numpy matrix') if not Coordinate.orthogonal_matrix(rotation_matrix): raise LinearAlgebraError('Rotation matrix is not orthogonal \ and can thus not represent a cartesian coordinate system') self.__rotation_matrix = rotation_matrix self.__translation_vector = translation_vector if calc_inverse: self.__inverse_transformation = self._calc_inverse_transformation() else: self.__inverse_transformation = None @classmethod def from_translation(cls, translation_vector): """Returns a translation coordinate transformation. Args: * translation_vector (np.array): 3x1 column vector which represents the translation Raises: * ValueError: if translation_vector is not a valid 3x1 numpy vector """ if not Coordinate.valid_vector(translation_vector): raise ValueError('Translation vector must be a 3x1 numpy array') return cls(np.eye(3), translation_vector) @classmethod def from_identity(cls): """Returns the identity coordinate transformation. """ return cls(np.eye(3), np.zeros(3)) @classmethod def from_composition(cls, outer, inner): """Returns a transformation object, which represent the compostion g∘f, where f is the inner and g is the outer transformation function. Args: * outer (Transformation) * inner (Transformation) """ rotation_matrix = np.dot(outer.get_rotation(), \ inner.get_rotation()) translation_vector = np.dot(outer.get_rotation(), \ inner.get_translation()) + outer.get_translation() return cls(rotation_matrix, translation_vector) @classmethod def from_pipeline(cls, pipeline): """Returns a transformation object, which represent the outcome of n composed transformations, which are given in a pipeline. Args: * pipeline (list of Transformation objects): The list consists of zero to n transformations, which are sorted according to the composition. The first element represents the outermost function and the last element represents the innermost function. """ result = Transformation.from_identity() for next_transform in pipeline: assert isinstance(next_transform, Transformation) result = Transformation.from_composition(result, next_transform) return result def get_rotation(self): """Returns the rotation matrix. """ return self.__rotation_matrix def get_translation(self): """Returns the translation vector. """ return self.__translation_vector def get_inverse(self): """Returns the inverse transformation. Calculates this function if necessary. """ if self.__inverse_transformation is None: self.__inverse_transformation = self._calc_inverse_transformation() return self.__inverse_transformation def transform(self, affine_vector): """Transforms an affine vector to base coordinates. Args: * affine_vecotr (numpy.array): a real 3 by 1 column vector Raises: * ValueError: If affine_vector is not 3-dimensional """ if not Coordinate.valid_vector(affine_vector): raise ValueError('Affine vector must be a 3x1 dimensonal numpy \ array') return np.dot(self.__rotation_matrix, affine_vector) \ + self.__translation_vector def retransform(self, base_vector): """Transforms an base vector to affine coordinates. Args: * base_vector (numpy.array): a real 3 by 1 column vector Raises: * ValueError: If base_vector is not 3-dimensional """ if not Coordinate.valid_vector(base_vector): raise ValueError('Base vector must be a 3x1 dimensonal numpy \ array') return self.__inverse_transformation.transform(base_vector) def _calc_inverse_transformation(self): """Calculates the inverse transformation function of this object. """ inverse_matrix = np.linalg.inv(self.__rotation_matrix) inverse_vector = -np.dot(inverse_matrix, self.__translation_vector) return Transformation(inverse_matrix, inverse_vector, calc_inverse=False) class Coordinate(): """Provides useful tools to use numpy vectors as coordinate vectors. This class is considered to be a toolbox for handling numpy vectors. To ensure maximum compatibility accross standard python libraries, numpy arrays are preferred over proprietary Coordinate objects. """ @staticmethod def valid_vector(vector): """Returns true if vector is 3 by 1 dimensional and false otherwise. Args: * vector (numpy.array) """ return (vector.shape == (3,)) or (vector.shape == (3,1)) @staticmethod def valid_matrix(matrix): """Returns true if matrix is 3 by 3 dimensional and false otherwise. Args: * matrix (numpy.matrix) """ return matrix.shape == (3,3) @staticmethod def orthogonal_matrix(matrix): """Returns true if matrix orthogonal and false otherwise. A matrix A is orthogonal if and only if A multiplied by its transpose is an identity matrix. Args: * matrix (numpy.matrix) """ return np.allclose(np.dot(matrix, np.transpose(matrix)), np.eye(3)) class Trigonometry(): """Provides some useful trigonometric formulas. """ @staticmethod def cosine_sentence(a, b, c): """Returns gamma from a Triangle abc by applying the cosine sentence. Args: * a, b, c (double): lengths of the triangle: a, b, c > 0 Raises: * ValueError: If any of the parameters is less or equal than zero """ if a <= 0 or b <= 0 or c <= 0: raise ValueError('Every length in a triangle has to be greater than\ 0') return math.acos((a*a+b*b-c*c)/(2*a*b)) class RotationMatrix(): def __init__(self, rotation_vector): """Accepts the rotation vector and prepares future calculations. Args: * rotation_vector (np.array): must be a 3x1 numpy vector Raises_ * ValueError: if rotation_vector is not a valid vector """ if not Coordinate.valid_vector(rotation_vector): raise ValueError('Rotation vector must be a 3x1 numpy array') unit_vector = rotation_vector / np.linalg.norm(rotation_vector) unit_vector = np.reshape(unit_vector, (3,1)) self._rotation_vector = unit_vector # outer product of two vectors is a matrix self._outer_product = np.dot(unit_vector, np.transpose(unit_vector)) self._cosine_matrix = np.eye(3) - self._outer_product uv1 = np.ndarray.item(unit_vector[0]) uv2 = np.ndarray.item(unit_vector[1]) uv3 = np.ndarray.item(unit_vector[2]) self._cross_matrix = np.array([[0,-uv3, uv2],[uv3,0,-uv1], \ [-uv2, uv1,0]]) @classmethod def from_axis(cls, axis = 'z'): """Returns a rotation matrix object for a given coordinate axis. Args: * axis (str): textual axis description Raises: * ValueError: if textual description does not match any coordinate axis """ if axis == 'x' or axis == 'X': return cls(np.array([1,0,0])) if axis == 'y' or axis == 'Y': return cls(np.array([0,1,0])) if axis == 'z' or axis == 'Z': return cls(np.array([0,0,1])) else: raise ValueError('Axis is not a coordinate axis.') def matrix_at_angle(self, angle): """Returns a rotation matrix for this instances axis for a given angle. See: * Formula "Rotation matrix from axis and angle": https://w.wiki/Knf Args: * angle (double): angle of the affine COS's rotation with respect to the reference COS """ return np.cos(angle) * self._cosine_matrix + self._outer_product + \ np.sin(angle) * self._cross_matrix class LinearAlgebraError(Exception): """Exception raised for invalid linear algebra operations related to transformation process of cartesian cooridinate systems. Attributes: message -- explanation of the error """ def __init__(self, message): self.message = message
en
0.71495
Handles cartesian coordinate transformations. Initializes a coordinate transformation object. Accepts a rotation matrix and a translation vector, by which a linear coordinate transformation is defined. Calculates the the inverse transformation function and stores it as a CoordinateTransformation object. Args: * rotation_matrix (numpy.matrix): a real 3 by 3 orthogonal matrix * translation_vector (numpy.array): a real 3 by 1 column vector * calc_inverse (bool): (optional) automatically calculate an inverse transformation for this transformation Raises: * ValueError: If either translation_vector or rotation_matrix are not 3-dimensional * LinearAlgebraError: If rotation_matrix is not a orthogonal 3 by 3 matrix Returns a translation coordinate transformation. Args: * translation_vector (np.array): 3x1 column vector which represents the translation Raises: * ValueError: if translation_vector is not a valid 3x1 numpy vector Returns the identity coordinate transformation. Returns a transformation object, which represent the compostion g∘f, where f is the inner and g is the outer transformation function. Args: * outer (Transformation) * inner (Transformation) Returns a transformation object, which represent the outcome of n composed transformations, which are given in a pipeline. Args: * pipeline (list of Transformation objects): The list consists of zero to n transformations, which are sorted according to the composition. The first element represents the outermost function and the last element represents the innermost function. Returns the rotation matrix. Returns the translation vector. Returns the inverse transformation. Calculates this function if necessary. Transforms an affine vector to base coordinates. Args: * affine_vecotr (numpy.array): a real 3 by 1 column vector Raises: * ValueError: If affine_vector is not 3-dimensional Transforms an base vector to affine coordinates. Args: * base_vector (numpy.array): a real 3 by 1 column vector Raises: * ValueError: If base_vector is not 3-dimensional Calculates the inverse transformation function of this object. Provides useful tools to use numpy vectors as coordinate vectors. This class is considered to be a toolbox for handling numpy vectors. To ensure maximum compatibility accross standard python libraries, numpy arrays are preferred over proprietary Coordinate objects. Returns true if vector is 3 by 1 dimensional and false otherwise. Args: * vector (numpy.array) Returns true if matrix is 3 by 3 dimensional and false otherwise. Args: * matrix (numpy.matrix) Returns true if matrix orthogonal and false otherwise. A matrix A is orthogonal if and only if A multiplied by its transpose is an identity matrix. Args: * matrix (numpy.matrix) Provides some useful trigonometric formulas. Returns gamma from a Triangle abc by applying the cosine sentence. Args: * a, b, c (double): lengths of the triangle: a, b, c > 0 Raises: * ValueError: If any of the parameters is less or equal than zero Accepts the rotation vector and prepares future calculations. Args: * rotation_vector (np.array): must be a 3x1 numpy vector Raises_ * ValueError: if rotation_vector is not a valid vector # outer product of two vectors is a matrix Returns a rotation matrix object for a given coordinate axis. Args: * axis (str): textual axis description Raises: * ValueError: if textual description does not match any coordinate axis Returns a rotation matrix for this instances axis for a given angle. See: * Formula "Rotation matrix from axis and angle": https://w.wiki/Knf Args: * angle (double): angle of the affine COS's rotation with respect to the reference COS Exception raised for invalid linear algebra operations related to transformation process of cartesian cooridinate systems. Attributes: message -- explanation of the error
3.645601
4
snowddl/resolver/tag.py
littleK0i/SnowDDL
21
6623668
<gh_stars>10-100 from snowddl.blueprint import TagBlueprint, ObjectType, SchemaObjectIdent from snowddl.resolver.abc_schema_object_resolver import AbstractSchemaObjectResolver, ResolveResult class TagResolver(AbstractSchemaObjectResolver): skip_on_empty_blueprints = True def get_object_type(self) -> ObjectType: return ObjectType.TAG def get_existing_objects_in_schema(self, schema: dict): existing_objects = {} cur = self.engine.execute_meta("SHOW TAGS IN SCHEMA {database:i}.{schema:i}", { "database": schema['database'], "schema": schema['schema'], }) for r in cur: full_name = f"{r['database_name']}.{r['schema_name']}.{r['name']}" existing_objects[full_name] = { "database": r['database_name'], "schema": r['schema_name'], "name": r['name'], "comment": r['comment'] if r['comment'] else None, } return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(TagBlueprint) def create_object(self, bp: TagBlueprint): self._create_tag(bp) self._apply_tag_refs(bp) return ResolveResult.CREATE def compare_object(self, bp: TagBlueprint, row: dict): result = ResolveResult.NOCHANGE if self._apply_tag_refs(bp): result = ResolveResult.ALTER if row['comment'] != bp.comment: self.engine.execute_unsafe_ddl("ALTER TAG {full_name:i} SET COMMENT = {comment}", { "full_name": bp.full_name, "comment": bp.comment, }) result = ResolveResult.ALTER return result def drop_object(self, row: dict): self._drop_tag_refs(SchemaObjectIdent('', row['database'], row['schema'], row['name'])) self._drop_tag(SchemaObjectIdent('', row['database'], row['schema'], row['name'])) return ResolveResult.DROP def _create_tag(self, bp: TagBlueprint): query = self.engine.query_builder() query.append("CREATE TAG {full_name:i}", { "full_name": bp.full_name, }) if bp.comment: query.append_nl("COMMENT = {comment}", { "comment": bp.comment, }) self.engine.execute_unsafe_ddl(query) def _drop_tag(self, tag_name: SchemaObjectIdent): self.engine.execute_unsafe_ddl("DROP TAG {full_name:i}", { "full_name": tag_name, }) def _apply_tag_refs(self, bp: TagBlueprint): existing_tag_refs = self._get_existing_tag_refs(bp.full_name) applied_change = False for ref in bp.references: if ref.column_name: ref_key = f"{ref.object_type.name}|{ref.object_name}|{ref.column_name}|{bp.full_name}" else: ref_key = f"{ref.object_type.name}|{ref.object_name}|{bp.full_name}" # Tag was applied before if ref_key in existing_tag_refs: existing_tag_value = existing_tag_refs[ref_key]['tag_value'] del(existing_tag_refs[ref_key]) # Tag was applied with the same value if ref.tag_value == existing_tag_value: continue # Apply tag if ref.column_name: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {object_name:i} MODIFY COLUMN {column_name:i} SET TAG {tag_name:i} = {tag_value}", { "object_type": ref.object_type.singular, "object_name": ref.object_name, "column_name": ref.column_name, "tag_name": bp.full_name, }) else: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {object_name:i} SET TAG {tag_name:i} = {tag_value}", { "object_type": ref.object_type.singular, "object_name": ref.object_name, "tag_name": bp.full_name, }) applied_change = True # Remove remaining tag references which no longer exist in blueprint for existing_ref in existing_tag_refs.values(): if existing_ref['column_name']: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {object_name:i} MODIFY COLUMN {column_name:i} UNSET TAG {tag_name:i}", { "object_type": existing_ref['object_type'], "database": existing_ref['database'], "schema": existing_ref['schema'], "name": existing_ref['name'], "column_name": existing_ref['column_name'], "tag_name": bp.full_name, }) else: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {object_name:i} UNSET TAG {tag_name:i}", { "object_type": existing_ref['object_type'], "database": existing_ref['database'], "schema": existing_ref['schema'], "tag_name": bp.full_name, }) applied_change = True return applied_change def _drop_tag_refs(self, tag_name: SchemaObjectIdent): existing_policy_refs = self._get_existing_tag_refs(tag_name) for existing_ref in existing_policy_refs.values(): if existing_ref['column_name']: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {database:i}.{schema:i}.{name:i} MODIFY COLUMN {column_name:i} UNSET TAG {tag_name:i}", { "object_type": existing_ref['object_type'], "database": existing_ref['database'], "schema": existing_ref['schema'], "name": existing_ref['name'], "column_name": existing_ref['column_name'], "tag_name": tag_name, }) else: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {database:i}.{schema:i}.{name:i} UNSET TAG {tag_name:i}", { "object_type": existing_ref['object_type'], "database": existing_ref['database'], "schema": existing_ref['schema'], "tag_name": tag_name, }) def _get_existing_tag_refs(self, tag_name: SchemaObjectIdent): existing_policy_refs = {} # TODO: discover a better way to get tag references in real time # Currently it is not clear how to get all tag references properly return existing_policy_refs
from snowddl.blueprint import TagBlueprint, ObjectType, SchemaObjectIdent from snowddl.resolver.abc_schema_object_resolver import AbstractSchemaObjectResolver, ResolveResult class TagResolver(AbstractSchemaObjectResolver): skip_on_empty_blueprints = True def get_object_type(self) -> ObjectType: return ObjectType.TAG def get_existing_objects_in_schema(self, schema: dict): existing_objects = {} cur = self.engine.execute_meta("SHOW TAGS IN SCHEMA {database:i}.{schema:i}", { "database": schema['database'], "schema": schema['schema'], }) for r in cur: full_name = f"{r['database_name']}.{r['schema_name']}.{r['name']}" existing_objects[full_name] = { "database": r['database_name'], "schema": r['schema_name'], "name": r['name'], "comment": r['comment'] if r['comment'] else None, } return existing_objects def get_blueprints(self): return self.config.get_blueprints_by_type(TagBlueprint) def create_object(self, bp: TagBlueprint): self._create_tag(bp) self._apply_tag_refs(bp) return ResolveResult.CREATE def compare_object(self, bp: TagBlueprint, row: dict): result = ResolveResult.NOCHANGE if self._apply_tag_refs(bp): result = ResolveResult.ALTER if row['comment'] != bp.comment: self.engine.execute_unsafe_ddl("ALTER TAG {full_name:i} SET COMMENT = {comment}", { "full_name": bp.full_name, "comment": bp.comment, }) result = ResolveResult.ALTER return result def drop_object(self, row: dict): self._drop_tag_refs(SchemaObjectIdent('', row['database'], row['schema'], row['name'])) self._drop_tag(SchemaObjectIdent('', row['database'], row['schema'], row['name'])) return ResolveResult.DROP def _create_tag(self, bp: TagBlueprint): query = self.engine.query_builder() query.append("CREATE TAG {full_name:i}", { "full_name": bp.full_name, }) if bp.comment: query.append_nl("COMMENT = {comment}", { "comment": bp.comment, }) self.engine.execute_unsafe_ddl(query) def _drop_tag(self, tag_name: SchemaObjectIdent): self.engine.execute_unsafe_ddl("DROP TAG {full_name:i}", { "full_name": tag_name, }) def _apply_tag_refs(self, bp: TagBlueprint): existing_tag_refs = self._get_existing_tag_refs(bp.full_name) applied_change = False for ref in bp.references: if ref.column_name: ref_key = f"{ref.object_type.name}|{ref.object_name}|{ref.column_name}|{bp.full_name}" else: ref_key = f"{ref.object_type.name}|{ref.object_name}|{bp.full_name}" # Tag was applied before if ref_key in existing_tag_refs: existing_tag_value = existing_tag_refs[ref_key]['tag_value'] del(existing_tag_refs[ref_key]) # Tag was applied with the same value if ref.tag_value == existing_tag_value: continue # Apply tag if ref.column_name: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {object_name:i} MODIFY COLUMN {column_name:i} SET TAG {tag_name:i} = {tag_value}", { "object_type": ref.object_type.singular, "object_name": ref.object_name, "column_name": ref.column_name, "tag_name": bp.full_name, }) else: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {object_name:i} SET TAG {tag_name:i} = {tag_value}", { "object_type": ref.object_type.singular, "object_name": ref.object_name, "tag_name": bp.full_name, }) applied_change = True # Remove remaining tag references which no longer exist in blueprint for existing_ref in existing_tag_refs.values(): if existing_ref['column_name']: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {object_name:i} MODIFY COLUMN {column_name:i} UNSET TAG {tag_name:i}", { "object_type": existing_ref['object_type'], "database": existing_ref['database'], "schema": existing_ref['schema'], "name": existing_ref['name'], "column_name": existing_ref['column_name'], "tag_name": bp.full_name, }) else: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {object_name:i} UNSET TAG {tag_name:i}", { "object_type": existing_ref['object_type'], "database": existing_ref['database'], "schema": existing_ref['schema'], "tag_name": bp.full_name, }) applied_change = True return applied_change def _drop_tag_refs(self, tag_name: SchemaObjectIdent): existing_policy_refs = self._get_existing_tag_refs(tag_name) for existing_ref in existing_policy_refs.values(): if existing_ref['column_name']: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {database:i}.{schema:i}.{name:i} MODIFY COLUMN {column_name:i} UNSET TAG {tag_name:i}", { "object_type": existing_ref['object_type'], "database": existing_ref['database'], "schema": existing_ref['schema'], "name": existing_ref['name'], "column_name": existing_ref['column_name'], "tag_name": tag_name, }) else: self.engine.execute_unsafe_ddl("ALTER {object_type:r} {database:i}.{schema:i}.{name:i} UNSET TAG {tag_name:i}", { "object_type": existing_ref['object_type'], "database": existing_ref['database'], "schema": existing_ref['schema'], "tag_name": tag_name, }) def _get_existing_tag_refs(self, tag_name: SchemaObjectIdent): existing_policy_refs = {} # TODO: discover a better way to get tag references in real time # Currently it is not clear how to get all tag references properly return existing_policy_refs
en
0.925693
# Tag was applied before # Tag was applied with the same value # Apply tag # Remove remaining tag references which no longer exist in blueprint # TODO: discover a better way to get tag references in real time # Currently it is not clear how to get all tag references properly
2.261566
2
exts/managing.py
erick-dsnk/uncle-dunks-discord-bot
0
6623669
import discord from discord.ext import commands from discord.ext.commands import Bot, Cog, Context class Manager(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot @commands.has_permissions(kick_members=True) @commands.command() async def announce(self, ctx: Context, channel: discord.TextChannel, *, message: str): ''' Make an announcement with a fancy embed containing your important message. ''' embed = discord.Embed( title=":loudspeaker: **Important announcement!**", description=f"{message}", color=discord.Color.green() ) embed.set_footer(text=f"Announcement made by {ctx.author.name}#{ctx.author.discriminator}.") await channel.send(embed=embed) @commands.has_permissions(kick_members=True) @commands.command() async def annoeveryone(self, ctx: Context, channel: discord.TextChannel, *, message: str): ''' Does the same thing as `announce` but also tags `@everyone`. ''' embed = discord.Embed( title=":loudspeaker: **Important announcement!**", description=f"{message}", color=discord.Color.green() ) embed.set_footer(text=f"Announcement made by {ctx.author.name}#{ctx.author.discriminator}.") await channel.send("@everyone", embed=embed) @commands.has_permissions(kick_members=True) @commands.command() async def annohere(self, ctx: Context, channel: discord.TextChannel, *, message: str): ''' Does the same thing as `announce` but also tags `@here` ''' embed = discord.Embed( title=":loudspeaker: **Important announcement!**", description=f"{message}", color=discord.Color.green() ) embed.set_footer(text=f"Announcement made by {ctx.author.name}#{ctx.author.discriminator}.") await channel.send("@here", embed=embed) def setup(bot: Bot): bot.add_cog(Manager(Bot))
import discord from discord.ext import commands from discord.ext.commands import Bot, Cog, Context class Manager(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot @commands.has_permissions(kick_members=True) @commands.command() async def announce(self, ctx: Context, channel: discord.TextChannel, *, message: str): ''' Make an announcement with a fancy embed containing your important message. ''' embed = discord.Embed( title=":loudspeaker: **Important announcement!**", description=f"{message}", color=discord.Color.green() ) embed.set_footer(text=f"Announcement made by {ctx.author.name}#{ctx.author.discriminator}.") await channel.send(embed=embed) @commands.has_permissions(kick_members=True) @commands.command() async def annoeveryone(self, ctx: Context, channel: discord.TextChannel, *, message: str): ''' Does the same thing as `announce` but also tags `@everyone`. ''' embed = discord.Embed( title=":loudspeaker: **Important announcement!**", description=f"{message}", color=discord.Color.green() ) embed.set_footer(text=f"Announcement made by {ctx.author.name}#{ctx.author.discriminator}.") await channel.send("@everyone", embed=embed) @commands.has_permissions(kick_members=True) @commands.command() async def annohere(self, ctx: Context, channel: discord.TextChannel, *, message: str): ''' Does the same thing as `announce` but also tags `@here` ''' embed = discord.Embed( title=":loudspeaker: **Important announcement!**", description=f"{message}", color=discord.Color.green() ) embed.set_footer(text=f"Announcement made by {ctx.author.name}#{ctx.author.discriminator}.") await channel.send("@here", embed=embed) def setup(bot: Bot): bot.add_cog(Manager(Bot))
en
0.858948
Make an announcement with a fancy embed containing your important message. #{ctx.author.discriminator}.") Does the same thing as `announce` but also tags `@everyone`. #{ctx.author.discriminator}.") Does the same thing as `announce` but also tags `@here` #{ctx.author.discriminator}.")
2.872819
3
torchaudio_augmentations/augmentations/reverb.py
wesbz/torchaudio-augmentations
112
6623670
import augment import torch class Reverb(torch.nn.Module): def __init__( self, sample_rate, reverberance_min=0, reverberance_max=100, dumping_factor_min=0, dumping_factor_max=100, room_size_min=0, room_size_max=100, ): super().__init__() self.sample_rate = sample_rate self.reverberance_min = reverberance_min self.reverberance_max = reverberance_max self.dumping_factor_min = dumping_factor_min self.dumping_factor_max = dumping_factor_max self.room_size_min = room_size_min self.room_size_max = room_size_max self.src_info = {"rate": self.sample_rate} self.target_info = { "channels": 1, "rate": self.sample_rate, } def forward(self, audio): reverberance = torch.randint( self.reverberance_min, self.reverberance_max, size=(1,) ).item() dumping_factor = torch.randint( self.dumping_factor_min, self.dumping_factor_max, size=(1,) ).item() room_size = torch.randint( self.room_size_min, self.room_size_max, size=(1,) ).item() num_channels = audio.shape[0] effect_chain = ( augment.EffectChain() .reverb(reverberance, dumping_factor, room_size) .channels(num_channels) ) audio = effect_chain.apply( audio, src_info=self.src_info, target_info=self.target_info ) return audio
import augment import torch class Reverb(torch.nn.Module): def __init__( self, sample_rate, reverberance_min=0, reverberance_max=100, dumping_factor_min=0, dumping_factor_max=100, room_size_min=0, room_size_max=100, ): super().__init__() self.sample_rate = sample_rate self.reverberance_min = reverberance_min self.reverberance_max = reverberance_max self.dumping_factor_min = dumping_factor_min self.dumping_factor_max = dumping_factor_max self.room_size_min = room_size_min self.room_size_max = room_size_max self.src_info = {"rate": self.sample_rate} self.target_info = { "channels": 1, "rate": self.sample_rate, } def forward(self, audio): reverberance = torch.randint( self.reverberance_min, self.reverberance_max, size=(1,) ).item() dumping_factor = torch.randint( self.dumping_factor_min, self.dumping_factor_max, size=(1,) ).item() room_size = torch.randint( self.room_size_min, self.room_size_max, size=(1,) ).item() num_channels = audio.shape[0] effect_chain = ( augment.EffectChain() .reverb(reverberance, dumping_factor, room_size) .channels(num_channels) ) audio = effect_chain.apply( audio, src_info=self.src_info, target_info=self.target_info ) return audio
none
1
2.657631
3
web/server.py
piyush82/icclab-rcb
2
6623671
############################################################ #@author: <NAME> (<EMAIL>) #@version: 0.1 #@summary: Module implementing RCB Restful Web Interface # #@requires: bottle ############################################################ from bottle import get, post, request, route, run, response import ConfigParser import sqlite3 as db import sys, getopt import web_ui import worker import config #list of database tables, this list is used to do DB sanity check whenever needed dbtables = ['user', 'project', 'session', 'projvariables'] def startServer(host, port): print 'Starting a simple REST server.' run(host=host, port=port) print 'Interrupt caught. Server stopped.' def checkdbconsistency(dbpath): print 'Starting the consistency check: ' + dbpath con = None try: con = db.connect(dbpath) cur = con.cursor() cur.execute('SELECT SQLITE_VERSION()') data = cur.fetchone() print "INFO: SQLite version: %s" % data cur.execute("SELECT name FROM sqlite_master WHERE type='table';") tlist = cur.fetchall() print "The count of tables found: %d" % len(tlist) if len(tlist) == len(dbtables): for tname in tlist: if tname[0] not in dbtables: print 'The table ' + tname + ' was not found in the control list!' return False else: print 'DB is inconsistent.' return False except db.Error, e: print 'Error %s:' % e.args[0] sys.exit(1) finally: if con: con.close() print 'DB is consistent!\n' return True def initializedb(dbpath): print 'Initializing the database: ' + dbpath con = None try: con = db.connect(dbpath) cur = con.cursor() cur.executescript(''' DROP TABLE IF EXISTS user; CREATE TABLE user(id INT, username VARCHAR(45), password VARCHAR(<PASSWORD>), cookiekey VARCHAR(128), email VARCHAR(128), isactive INT); DROP TABLE IF EXISTS project; CREATE TABLE project(id INT, name VARCHAR(45), userid INT, cfile TEXT); DROP TABLE IF EXISTS session; CREATE TABLE session(id INT, userid INT, taccess INT, projectid INT, isvalid INT); DROP TABLE IF EXISTS proj_variables; CREATE TABLE projvariables(id INT, projectid INT, cloudtype VARCHAR(45), cloudrelease VARCHAR(45), clouduser VARCHAR(45), cloudpassword VARCHAR(45), cloudtenant VARCHAR(45)); ''') con.commit() except db.Error, e: print 'Error %s:' % e.args[0] sys.exit(1) finally: if con: con.close() return True def main(argv): config.init() confFile = None try: opts, args = getopt.getopt(argv, "hc:i", "config=") except getopt.GetoptError: print 'server.py -c <configfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'server.py -c <configfile> [-i]' print 'To initialize a configuration file: use switch -i' sys.exit() elif opt in ("-c", "--config"): confFile = arg Config = ConfigParser.ConfigParser() for opt, arg in opts: if opt == '-i': if confFile != None: cfgfile = open(confFile,'w') Config.add_section('Server') Config.add_section('Database') Config.set('Server', 'Port', 8080) Config.set('Database', 'File', 'rcb.db') Config.set('Database', 'Driver', 'sqlite') Config.write(cfgfile) cfgfile.close() print 'New configuration file has been created. Change the parameters as needed and start the program with -c flag.' sys.exit() else: print 'Please specify the configuration file name. Use -c flag when using -i option.' sys.exit(2) if confFile == None: Config.read("/Users/harh/Codes/ZHAW/Eclipse/workspace/icclab-rcb/config.ini") else: Config.read(confFile) dbPath = Config.get("Database", "File") config.globals.append(dbPath) #Now performing sanitaion checks on the database dbtest = checkdbconsistency(dbPath) dbinitstatus = True if dbtest != True: dbinitstatus = initializedb(dbPath) serverPort = Config.get("Server", "Port") if dbinitstatus != False: print "Starting the ICCLab RCB Online Service\n" startServer('localhost', serverPort) else: print 'DB is not consistent, and it could not be initialized properly!' if __name__ == "__main__": main(sys.argv[1:])
############################################################ #@author: <NAME> (<EMAIL>) #@version: 0.1 #@summary: Module implementing RCB Restful Web Interface # #@requires: bottle ############################################################ from bottle import get, post, request, route, run, response import ConfigParser import sqlite3 as db import sys, getopt import web_ui import worker import config #list of database tables, this list is used to do DB sanity check whenever needed dbtables = ['user', 'project', 'session', 'projvariables'] def startServer(host, port): print 'Starting a simple REST server.' run(host=host, port=port) print 'Interrupt caught. Server stopped.' def checkdbconsistency(dbpath): print 'Starting the consistency check: ' + dbpath con = None try: con = db.connect(dbpath) cur = con.cursor() cur.execute('SELECT SQLITE_VERSION()') data = cur.fetchone() print "INFO: SQLite version: %s" % data cur.execute("SELECT name FROM sqlite_master WHERE type='table';") tlist = cur.fetchall() print "The count of tables found: %d" % len(tlist) if len(tlist) == len(dbtables): for tname in tlist: if tname[0] not in dbtables: print 'The table ' + tname + ' was not found in the control list!' return False else: print 'DB is inconsistent.' return False except db.Error, e: print 'Error %s:' % e.args[0] sys.exit(1) finally: if con: con.close() print 'DB is consistent!\n' return True def initializedb(dbpath): print 'Initializing the database: ' + dbpath con = None try: con = db.connect(dbpath) cur = con.cursor() cur.executescript(''' DROP TABLE IF EXISTS user; CREATE TABLE user(id INT, username VARCHAR(45), password VARCHAR(<PASSWORD>), cookiekey VARCHAR(128), email VARCHAR(128), isactive INT); DROP TABLE IF EXISTS project; CREATE TABLE project(id INT, name VARCHAR(45), userid INT, cfile TEXT); DROP TABLE IF EXISTS session; CREATE TABLE session(id INT, userid INT, taccess INT, projectid INT, isvalid INT); DROP TABLE IF EXISTS proj_variables; CREATE TABLE projvariables(id INT, projectid INT, cloudtype VARCHAR(45), cloudrelease VARCHAR(45), clouduser VARCHAR(45), cloudpassword VARCHAR(45), cloudtenant VARCHAR(45)); ''') con.commit() except db.Error, e: print 'Error %s:' % e.args[0] sys.exit(1) finally: if con: con.close() return True def main(argv): config.init() confFile = None try: opts, args = getopt.getopt(argv, "hc:i", "config=") except getopt.GetoptError: print 'server.py -c <configfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'server.py -c <configfile> [-i]' print 'To initialize a configuration file: use switch -i' sys.exit() elif opt in ("-c", "--config"): confFile = arg Config = ConfigParser.ConfigParser() for opt, arg in opts: if opt == '-i': if confFile != None: cfgfile = open(confFile,'w') Config.add_section('Server') Config.add_section('Database') Config.set('Server', 'Port', 8080) Config.set('Database', 'File', 'rcb.db') Config.set('Database', 'Driver', 'sqlite') Config.write(cfgfile) cfgfile.close() print 'New configuration file has been created. Change the parameters as needed and start the program with -c flag.' sys.exit() else: print 'Please specify the configuration file name. Use -c flag when using -i option.' sys.exit(2) if confFile == None: Config.read("/Users/harh/Codes/ZHAW/Eclipse/workspace/icclab-rcb/config.ini") else: Config.read(confFile) dbPath = Config.get("Database", "File") config.globals.append(dbPath) #Now performing sanitaion checks on the database dbtest = checkdbconsistency(dbPath) dbinitstatus = True if dbtest != True: dbinitstatus = initializedb(dbPath) serverPort = Config.get("Server", "Port") if dbinitstatus != False: print "Starting the ICCLab RCB Online Service\n" startServer('localhost', serverPort) else: print 'DB is not consistent, and it could not be initialized properly!' if __name__ == "__main__": main(sys.argv[1:])
en
0.334589
############################################################ #@author: <NAME> (<EMAIL>) #@version: 0.1 #@summary: Module implementing RCB Restful Web Interface # #@requires: bottle ############################################################ #list of database tables, this list is used to do DB sanity check whenever needed DROP TABLE IF EXISTS user; CREATE TABLE user(id INT, username VARCHAR(45), password VARCHAR(<PASSWORD>), cookiekey VARCHAR(128), email VARCHAR(128), isactive INT); DROP TABLE IF EXISTS project; CREATE TABLE project(id INT, name VARCHAR(45), userid INT, cfile TEXT); DROP TABLE IF EXISTS session; CREATE TABLE session(id INT, userid INT, taccess INT, projectid INT, isvalid INT); DROP TABLE IF EXISTS proj_variables; CREATE TABLE projvariables(id INT, projectid INT, cloudtype VARCHAR(45), cloudrelease VARCHAR(45), clouduser VARCHAR(45), cloudpassword VARCHAR(45), cloudtenant VARCHAR(45)); #Now performing sanitaion checks on the database
2.725199
3
AppDB/appscale/datastore/cassandra_env/entity_id_allocator.py
HafeezRai/appscale
1
6623672
import sys import uuid from appscale.common.unpackaged import APPSCALE_PYTHON_APPSERVER from cassandra.query import ( ConsistencyLevel, SimpleStatement ) from tornado import gen from appscale.datastore.cassandra_env.retry_policies import NO_RETRIES from appscale.datastore.cassandra_env.tornado_cassandra import TornadoCassandra from appscale.datastore.dbconstants import ( AppScaleBadArg, AppScaleDBConnectionError, TRANSIENT_CASSANDRA_ERRORS ) from appscale.datastore.utils import logger sys.path.append(APPSCALE_PYTHON_APPSERVER) from google.appengine.datastore.datastore_stub_util import ( _MAX_SCATTERED_COUNTER, _MAX_SEQUENTIAL_COUNTER, ToScatteredId ) # The number of scattered IDs the datastore should reserve at a time. DEFAULT_RESERVATION_SIZE = 10000 class ReservationFailed(Exception): """ Indicates that a block of IDs could not be reserved. """ pass class EntityIDAllocator(object): """ Keeps track of reserved entity IDs for a project. """ def __init__(self, session, project, scattered=False): """ Creates a new EntityIDAllocator object. Args: session: A cassandra-drivers session object. project: A string specifying a project ID. """ self.project = project self.session = session self.tornado_cassandra = TornadoCassandra(self.session) self.scattered = scattered if scattered: self.max_allowed = _MAX_SCATTERED_COUNTER else: self.max_allowed = _MAX_SEQUENTIAL_COUNTER # Allows the allocator to avoid making unnecessary Cassandra requests when # setting the minimum counter value. self._last_reserved_cache = None @gen.coroutine def _ensure_entry(self, retries=5): """ Ensures an entry exists for a reservation. Args: retries: The number of times to retry the insert. Raises: AppScaleDBConnectionError if the insert is tried too many times. """ if retries < 0: raise AppScaleDBConnectionError('Unable to create reserved_ids entry') logger.debug('Creating reserved_ids entry for {}'.format(self.project)) insert = SimpleStatement(""" INSERT INTO reserved_ids (project, scattered, last_reserved, op_id) VALUES (%(project)s, %(scattered)s, 0, uuid()) IF NOT EXISTS """, retry_policy=NO_RETRIES) parameters = {'project': self.project, 'scattered': self.scattered} try: yield self.tornado_cassandra.execute(insert, parameters) except TRANSIENT_CASSANDRA_ERRORS: yield self._ensure_entry(retries=retries-1) @gen.coroutine def _get_last_reserved(self): """ Retrieves the last entity ID that was reserved. Returns: An integer specifying an entity ID. """ get_reserved = SimpleStatement(""" SELECT last_reserved FROM reserved_ids WHERE project = %(project)s AND scattered = %(scattered)s """, consistency_level=ConsistencyLevel.SERIAL) parameters = {'project': self.project, 'scattered': self.scattered} try: results = yield self.tornado_cassandra.execute(get_reserved, parameters) result = results[0] except IndexError: yield self._ensure_entry() last_reserved = yield self._get_last_reserved() raise gen.Return(last_reserved) self._last_reserved_cache = result.last_reserved raise gen.Return(result.last_reserved) @gen.coroutine def _get_last_op_id(self): """ Retrieve the op_id that was last written during a reservation. Returns: A UUID4 containing the latest op_id. """ get_op_id = SimpleStatement(""" SELECT op_id FROM reserved_ids WHERE project = %(project)s AND scattered = %(scattered)s """, consistency_level=ConsistencyLevel.SERIAL) parameters = {'project': self.project, 'scattered': self.scattered} results = yield self.tornado_cassandra.execute(get_op_id, parameters) raise gen.Return(results[0].op_id) @gen.coroutine def _set_reserved(self, last_reserved, new_reserved): """ Update the last reserved value to allocate that block. Args: last_reserved: An integer specifying the last reserved value. new_reserved: An integer specifying the new reserved value. Raises: ReservationFailed if the update statement fails. """ op_id = uuid.uuid4() set_reserved = SimpleStatement(""" UPDATE reserved_ids SET last_reserved = %(new_reserved)s, op_id = %(op_id)s WHERE project = %(project)s AND scattered = %(scattered)s IF last_reserved = %(last_reserved)s """, retry_policy=NO_RETRIES) parameters = { 'last_reserved': last_reserved, 'new_reserved': new_reserved, 'project': self.project, 'scattered': self.scattered, 'op_id': op_id} try: result = yield self.tornado_cassandra.execute(set_reserved, parameters) except TRANSIENT_CASSANDRA_ERRORS as error: last_op_id = yield self._get_last_op_id() if last_op_id == op_id: return raise ReservationFailed(str(error)) if not result.was_applied: raise ReservationFailed('Last reserved value changed') self._last_reserved_cache = new_reserved @gen.coroutine def allocate_size(self, size, retries=5, min_counter=None): """ Reserve a block of IDs for this project. Args: size: The number of IDs to reserve. retries: The number of times to retry the reservation. min_counter: The minimum counter value that should be reserved. Returns: A tuple of integers specifying the start and end ID. Raises: AppScaleDBConnectionError if the reservation is tried too many times. AppScaleBadArg if the ID space has been exhausted. """ if retries < 0: raise AppScaleDBConnectionError('Unable to reserve new block') try: last_reserved = yield self._get_last_reserved() except TRANSIENT_CASSANDRA_ERRORS: raise AppScaleDBConnectionError('Unable to get last reserved ID') if min_counter is None: new_reserved = last_reserved + size else: new_reserved = max(last_reserved, min_counter) + size if new_reserved > self.max_allowed: raise AppScaleBadArg('Exceeded maximum allocated IDs') try: yield self._set_reserved(last_reserved, new_reserved) except ReservationFailed: start_id, end_id = yield self.allocate_size(size, retries=retries-1) raise gen.Return((start_id, end_id)) start_id = last_reserved + 1 end_id = new_reserved raise gen.Return((start_id, end_id)) @gen.coroutine def allocate_max(self, max_id, retries=5): """ Reserves all IDs up to the one given. Args: max_id: An integer specifying the maximum ID to allocated. retries: The number of times to retry the reservation. Returns: A tuple of integers specifying the start and end ID. Raises: AppScaleDBConnectionError if the reservation is tried too many times. AppScaleBadArg if the ID space has been exhausted. """ if retries < 0: raise AppScaleDBConnectionError('Unable to reserve new block') if max_id > self.max_allowed: raise AppScaleBadArg('Exceeded maximum allocated IDs') try: last_reserved = yield self._get_last_reserved() except TRANSIENT_CASSANDRA_ERRORS: raise AppScaleDBConnectionError('Unable to get last reserved ID') # Instead of returning an error, the API returns an invalid range. if last_reserved >= max_id: raise gen.Return((last_reserved + 1, last_reserved)) try: yield self._set_reserved(last_reserved, max_id) except ReservationFailed: start_id, end_id = yield self.allocate_max(max_id, retries=retries-1) raise gen.Return((start_id, end_id)) start_id = last_reserved + 1 end_id = max_id raise gen.Return((start_id, end_id)) @gen.coroutine def set_min_counter(self, counter): """ Ensures the counter is at least as large as the given value. Args: counter: An integer specifying the minimum counter value. """ if (self._last_reserved_cache is not None and self._last_reserved_cache >= counter): return yield self.allocate_max(counter) class ScatteredAllocator(EntityIDAllocator): """ An iterator that generates evenly-distributed entity IDs. """ def __init__(self, session, project): """ Creates a new ScatteredAllocator instance. Each project should just have one instance since it reserves a large block of IDs at a time. Args: session: A cassandra-driver session. project: A string specifying a project ID. """ super(ScatteredAllocator, self).__init__(session, project, scattered=True) # The range that this datastore has already reserved for scattered IDs. self.start_id = None self.end_id = None def __iter__(self): """ Returns a new iterator object. """ return self @gen.coroutine def next(self): """ Generates a new entity ID. Returns: An integer specifying an entity ID. """ # This function will require a tornado lock when made asynchronous. if self.start_id is None or self.start_id > self.end_id: size = DEFAULT_RESERVATION_SIZE self.start_id, self.end_id = yield self.allocate_size(size) next_id = ToScatteredId(self.start_id) self.start_id += 1 raise gen.Return(next_id) @gen.coroutine def set_min_counter(self, counter): """ Ensures the counter is at least as large as the given value. Args: counter: An integer specifying the minimum counter value. """ # If there's no chance the ID could be allocated, do nothing. if self.start_id is not None and self.start_id >= counter: return # If the ID is in the allocated block, adjust the block. if self.end_id is not None and self.end_id > counter: self.start_id = counter # If this server has never allocated a block, adjust the minimum for # future blocks. if self.start_id is None: if (self._last_reserved_cache is not None and self._last_reserved_cache >= counter): return yield self.allocate_max(counter) return # If this server has allocated a block, but the relevant ID is greater than # the end ID, get a new block that starts at least as high as the ID. self.start_id, self.end_id = yield self.allocate_size( DEFAULT_RESERVATION_SIZE, min_counter=counter )
import sys import uuid from appscale.common.unpackaged import APPSCALE_PYTHON_APPSERVER from cassandra.query import ( ConsistencyLevel, SimpleStatement ) from tornado import gen from appscale.datastore.cassandra_env.retry_policies import NO_RETRIES from appscale.datastore.cassandra_env.tornado_cassandra import TornadoCassandra from appscale.datastore.dbconstants import ( AppScaleBadArg, AppScaleDBConnectionError, TRANSIENT_CASSANDRA_ERRORS ) from appscale.datastore.utils import logger sys.path.append(APPSCALE_PYTHON_APPSERVER) from google.appengine.datastore.datastore_stub_util import ( _MAX_SCATTERED_COUNTER, _MAX_SEQUENTIAL_COUNTER, ToScatteredId ) # The number of scattered IDs the datastore should reserve at a time. DEFAULT_RESERVATION_SIZE = 10000 class ReservationFailed(Exception): """ Indicates that a block of IDs could not be reserved. """ pass class EntityIDAllocator(object): """ Keeps track of reserved entity IDs for a project. """ def __init__(self, session, project, scattered=False): """ Creates a new EntityIDAllocator object. Args: session: A cassandra-drivers session object. project: A string specifying a project ID. """ self.project = project self.session = session self.tornado_cassandra = TornadoCassandra(self.session) self.scattered = scattered if scattered: self.max_allowed = _MAX_SCATTERED_COUNTER else: self.max_allowed = _MAX_SEQUENTIAL_COUNTER # Allows the allocator to avoid making unnecessary Cassandra requests when # setting the minimum counter value. self._last_reserved_cache = None @gen.coroutine def _ensure_entry(self, retries=5): """ Ensures an entry exists for a reservation. Args: retries: The number of times to retry the insert. Raises: AppScaleDBConnectionError if the insert is tried too many times. """ if retries < 0: raise AppScaleDBConnectionError('Unable to create reserved_ids entry') logger.debug('Creating reserved_ids entry for {}'.format(self.project)) insert = SimpleStatement(""" INSERT INTO reserved_ids (project, scattered, last_reserved, op_id) VALUES (%(project)s, %(scattered)s, 0, uuid()) IF NOT EXISTS """, retry_policy=NO_RETRIES) parameters = {'project': self.project, 'scattered': self.scattered} try: yield self.tornado_cassandra.execute(insert, parameters) except TRANSIENT_CASSANDRA_ERRORS: yield self._ensure_entry(retries=retries-1) @gen.coroutine def _get_last_reserved(self): """ Retrieves the last entity ID that was reserved. Returns: An integer specifying an entity ID. """ get_reserved = SimpleStatement(""" SELECT last_reserved FROM reserved_ids WHERE project = %(project)s AND scattered = %(scattered)s """, consistency_level=ConsistencyLevel.SERIAL) parameters = {'project': self.project, 'scattered': self.scattered} try: results = yield self.tornado_cassandra.execute(get_reserved, parameters) result = results[0] except IndexError: yield self._ensure_entry() last_reserved = yield self._get_last_reserved() raise gen.Return(last_reserved) self._last_reserved_cache = result.last_reserved raise gen.Return(result.last_reserved) @gen.coroutine def _get_last_op_id(self): """ Retrieve the op_id that was last written during a reservation. Returns: A UUID4 containing the latest op_id. """ get_op_id = SimpleStatement(""" SELECT op_id FROM reserved_ids WHERE project = %(project)s AND scattered = %(scattered)s """, consistency_level=ConsistencyLevel.SERIAL) parameters = {'project': self.project, 'scattered': self.scattered} results = yield self.tornado_cassandra.execute(get_op_id, parameters) raise gen.Return(results[0].op_id) @gen.coroutine def _set_reserved(self, last_reserved, new_reserved): """ Update the last reserved value to allocate that block. Args: last_reserved: An integer specifying the last reserved value. new_reserved: An integer specifying the new reserved value. Raises: ReservationFailed if the update statement fails. """ op_id = uuid.uuid4() set_reserved = SimpleStatement(""" UPDATE reserved_ids SET last_reserved = %(new_reserved)s, op_id = %(op_id)s WHERE project = %(project)s AND scattered = %(scattered)s IF last_reserved = %(last_reserved)s """, retry_policy=NO_RETRIES) parameters = { 'last_reserved': last_reserved, 'new_reserved': new_reserved, 'project': self.project, 'scattered': self.scattered, 'op_id': op_id} try: result = yield self.tornado_cassandra.execute(set_reserved, parameters) except TRANSIENT_CASSANDRA_ERRORS as error: last_op_id = yield self._get_last_op_id() if last_op_id == op_id: return raise ReservationFailed(str(error)) if not result.was_applied: raise ReservationFailed('Last reserved value changed') self._last_reserved_cache = new_reserved @gen.coroutine def allocate_size(self, size, retries=5, min_counter=None): """ Reserve a block of IDs for this project. Args: size: The number of IDs to reserve. retries: The number of times to retry the reservation. min_counter: The minimum counter value that should be reserved. Returns: A tuple of integers specifying the start and end ID. Raises: AppScaleDBConnectionError if the reservation is tried too many times. AppScaleBadArg if the ID space has been exhausted. """ if retries < 0: raise AppScaleDBConnectionError('Unable to reserve new block') try: last_reserved = yield self._get_last_reserved() except TRANSIENT_CASSANDRA_ERRORS: raise AppScaleDBConnectionError('Unable to get last reserved ID') if min_counter is None: new_reserved = last_reserved + size else: new_reserved = max(last_reserved, min_counter) + size if new_reserved > self.max_allowed: raise AppScaleBadArg('Exceeded maximum allocated IDs') try: yield self._set_reserved(last_reserved, new_reserved) except ReservationFailed: start_id, end_id = yield self.allocate_size(size, retries=retries-1) raise gen.Return((start_id, end_id)) start_id = last_reserved + 1 end_id = new_reserved raise gen.Return((start_id, end_id)) @gen.coroutine def allocate_max(self, max_id, retries=5): """ Reserves all IDs up to the one given. Args: max_id: An integer specifying the maximum ID to allocated. retries: The number of times to retry the reservation. Returns: A tuple of integers specifying the start and end ID. Raises: AppScaleDBConnectionError if the reservation is tried too many times. AppScaleBadArg if the ID space has been exhausted. """ if retries < 0: raise AppScaleDBConnectionError('Unable to reserve new block') if max_id > self.max_allowed: raise AppScaleBadArg('Exceeded maximum allocated IDs') try: last_reserved = yield self._get_last_reserved() except TRANSIENT_CASSANDRA_ERRORS: raise AppScaleDBConnectionError('Unable to get last reserved ID') # Instead of returning an error, the API returns an invalid range. if last_reserved >= max_id: raise gen.Return((last_reserved + 1, last_reserved)) try: yield self._set_reserved(last_reserved, max_id) except ReservationFailed: start_id, end_id = yield self.allocate_max(max_id, retries=retries-1) raise gen.Return((start_id, end_id)) start_id = last_reserved + 1 end_id = max_id raise gen.Return((start_id, end_id)) @gen.coroutine def set_min_counter(self, counter): """ Ensures the counter is at least as large as the given value. Args: counter: An integer specifying the minimum counter value. """ if (self._last_reserved_cache is not None and self._last_reserved_cache >= counter): return yield self.allocate_max(counter) class ScatteredAllocator(EntityIDAllocator): """ An iterator that generates evenly-distributed entity IDs. """ def __init__(self, session, project): """ Creates a new ScatteredAllocator instance. Each project should just have one instance since it reserves a large block of IDs at a time. Args: session: A cassandra-driver session. project: A string specifying a project ID. """ super(ScatteredAllocator, self).__init__(session, project, scattered=True) # The range that this datastore has already reserved for scattered IDs. self.start_id = None self.end_id = None def __iter__(self): """ Returns a new iterator object. """ return self @gen.coroutine def next(self): """ Generates a new entity ID. Returns: An integer specifying an entity ID. """ # This function will require a tornado lock when made asynchronous. if self.start_id is None or self.start_id > self.end_id: size = DEFAULT_RESERVATION_SIZE self.start_id, self.end_id = yield self.allocate_size(size) next_id = ToScatteredId(self.start_id) self.start_id += 1 raise gen.Return(next_id) @gen.coroutine def set_min_counter(self, counter): """ Ensures the counter is at least as large as the given value. Args: counter: An integer specifying the minimum counter value. """ # If there's no chance the ID could be allocated, do nothing. if self.start_id is not None and self.start_id >= counter: return # If the ID is in the allocated block, adjust the block. if self.end_id is not None and self.end_id > counter: self.start_id = counter # If this server has never allocated a block, adjust the minimum for # future blocks. if self.start_id is None: if (self._last_reserved_cache is not None and self._last_reserved_cache >= counter): return yield self.allocate_max(counter) return # If this server has allocated a block, but the relevant ID is greater than # the end ID, get a new block that starts at least as high as the ID. self.start_id, self.end_id = yield self.allocate_size( DEFAULT_RESERVATION_SIZE, min_counter=counter )
en
0.844715
# The number of scattered IDs the datastore should reserve at a time. Indicates that a block of IDs could not be reserved. Keeps track of reserved entity IDs for a project. Creates a new EntityIDAllocator object. Args: session: A cassandra-drivers session object. project: A string specifying a project ID. # Allows the allocator to avoid making unnecessary Cassandra requests when # setting the minimum counter value. Ensures an entry exists for a reservation. Args: retries: The number of times to retry the insert. Raises: AppScaleDBConnectionError if the insert is tried too many times. INSERT INTO reserved_ids (project, scattered, last_reserved, op_id) VALUES (%(project)s, %(scattered)s, 0, uuid()) IF NOT EXISTS Retrieves the last entity ID that was reserved. Returns: An integer specifying an entity ID. SELECT last_reserved FROM reserved_ids WHERE project = %(project)s AND scattered = %(scattered)s Retrieve the op_id that was last written during a reservation. Returns: A UUID4 containing the latest op_id. SELECT op_id FROM reserved_ids WHERE project = %(project)s AND scattered = %(scattered)s Update the last reserved value to allocate that block. Args: last_reserved: An integer specifying the last reserved value. new_reserved: An integer specifying the new reserved value. Raises: ReservationFailed if the update statement fails. UPDATE reserved_ids SET last_reserved = %(new_reserved)s, op_id = %(op_id)s WHERE project = %(project)s AND scattered = %(scattered)s IF last_reserved = %(last_reserved)s Reserve a block of IDs for this project. Args: size: The number of IDs to reserve. retries: The number of times to retry the reservation. min_counter: The minimum counter value that should be reserved. Returns: A tuple of integers specifying the start and end ID. Raises: AppScaleDBConnectionError if the reservation is tried too many times. AppScaleBadArg if the ID space has been exhausted. Reserves all IDs up to the one given. Args: max_id: An integer specifying the maximum ID to allocated. retries: The number of times to retry the reservation. Returns: A tuple of integers specifying the start and end ID. Raises: AppScaleDBConnectionError if the reservation is tried too many times. AppScaleBadArg if the ID space has been exhausted. # Instead of returning an error, the API returns an invalid range. Ensures the counter is at least as large as the given value. Args: counter: An integer specifying the minimum counter value. An iterator that generates evenly-distributed entity IDs. Creates a new ScatteredAllocator instance. Each project should just have one instance since it reserves a large block of IDs at a time. Args: session: A cassandra-driver session. project: A string specifying a project ID. # The range that this datastore has already reserved for scattered IDs. Returns a new iterator object. Generates a new entity ID. Returns: An integer specifying an entity ID. # This function will require a tornado lock when made asynchronous. Ensures the counter is at least as large as the given value. Args: counter: An integer specifying the minimum counter value. # If there's no chance the ID could be allocated, do nothing. # If the ID is in the allocated block, adjust the block. # If this server has never allocated a block, adjust the minimum for # future blocks. # If this server has allocated a block, but the relevant ID is greater than # the end ID, get a new block that starts at least as high as the ID.
2.015592
2
version.py
Keneral/aeclang
0
6623673
<gh_stars>0 major = '3' minor = '8' patch = '256229'
major = '3' minor = '8' patch = '256229'
none
1
1.151842
1
config.py
ethanaggor/twitter-clone
0
6623674
<gh_stars>0 import os from pathlib import Path BASE_DIR = Path(__file__).parent class DevConfig(object): # It's very unfortunate that you can't enable development-mode without setting Env variables. SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format( BASE_DIR.joinpath('blah.sqlite3') ) SQLALCHEMY_TRACK_MODIFICATIONS = False STATIC_DIR = BASE_DIR.joinpath('static') TEMPLATE_DIR = BASE_DIR.joinpath('templates') SECRET_KEY = os.urandom(24) class TestConfig(DevConfig): TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format( BASE_DIR.joinpath('testing.sqlite3') ) WTF_CSRF_ENABLED = False SERVER_NAME = 'localhost.localdomain:5000'
import os from pathlib import Path BASE_DIR = Path(__file__).parent class DevConfig(object): # It's very unfortunate that you can't enable development-mode without setting Env variables. SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format( BASE_DIR.joinpath('blah.sqlite3') ) SQLALCHEMY_TRACK_MODIFICATIONS = False STATIC_DIR = BASE_DIR.joinpath('static') TEMPLATE_DIR = BASE_DIR.joinpath('templates') SECRET_KEY = os.urandom(24) class TestConfig(DevConfig): TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format( BASE_DIR.joinpath('testing.sqlite3') ) WTF_CSRF_ENABLED = False SERVER_NAME = 'localhost.localdomain:5000'
en
0.920643
# It's very unfortunate that you can't enable development-mode without setting Env variables.
1.949612
2
python/yacht/yacht.py
sci-c0/exercism-learning
0
6623675
<filename>python/yacht/yacht.py<gh_stars>0 from collections import Counter from typing import List, Callable _NUM_CATEGORIES = 12 # Score categories. (YACHT, ONES, TWOS, THREES, FOURS, FIVES, SIXES, FULL_HOUSE, FOUR_OF_A_KIND, LITTLE_STRAIGHT, BIG_STRAIGHT, CHOICE) = range(_NUM_CATEGORIES) def _yacht_score(dice: List[int]) -> int: return 50 if len(set(dice)) == 1 else 0 def _nums_score_gen(win_num: int) -> Callable: def num_score(dice: List[int]) -> int: return dice.count(win_num) * win_num return num_score def _full_house_score(dice: List[int]) -> int: counts = Counter(dice) if set(counts.values()) == {2, 3}: return sum(dice) return 0 def _four_of_a_kind_score(dice: List[int]) -> int: counts = Counter(dice) mc = counts.most_common(1)[0] return mc[0] * 4 if mc[1] >= 4 else 0 def _little_straight_score(dice: List[int]) -> int: return 30 * (set(dice) == set(range(1, 6))) def _big_straight_score(dice: List[int]) -> int: return 30 * (set(dice) == set(range(2, 7))) def _choice_score(dice: List[int]) -> int: return sum(dice) category_score_map = { YACHT: _yacht_score, ONES: _nums_score_gen(1), TWOS: _nums_score_gen(2), THREES: _nums_score_gen(3), FOURS: _nums_score_gen(4), FIVES: _nums_score_gen(5), SIXES: _nums_score_gen(6), FULL_HOUSE: _full_house_score, FOUR_OF_A_KIND: _four_of_a_kind_score, LITTLE_STRAIGHT: _little_straight_score, BIG_STRAIGHT: _big_straight_score, CHOICE: _choice_score } def score(dice, category): return category_score_map[category](dice)
<filename>python/yacht/yacht.py<gh_stars>0 from collections import Counter from typing import List, Callable _NUM_CATEGORIES = 12 # Score categories. (YACHT, ONES, TWOS, THREES, FOURS, FIVES, SIXES, FULL_HOUSE, FOUR_OF_A_KIND, LITTLE_STRAIGHT, BIG_STRAIGHT, CHOICE) = range(_NUM_CATEGORIES) def _yacht_score(dice: List[int]) -> int: return 50 if len(set(dice)) == 1 else 0 def _nums_score_gen(win_num: int) -> Callable: def num_score(dice: List[int]) -> int: return dice.count(win_num) * win_num return num_score def _full_house_score(dice: List[int]) -> int: counts = Counter(dice) if set(counts.values()) == {2, 3}: return sum(dice) return 0 def _four_of_a_kind_score(dice: List[int]) -> int: counts = Counter(dice) mc = counts.most_common(1)[0] return mc[0] * 4 if mc[1] >= 4 else 0 def _little_straight_score(dice: List[int]) -> int: return 30 * (set(dice) == set(range(1, 6))) def _big_straight_score(dice: List[int]) -> int: return 30 * (set(dice) == set(range(2, 7))) def _choice_score(dice: List[int]) -> int: return sum(dice) category_score_map = { YACHT: _yacht_score, ONES: _nums_score_gen(1), TWOS: _nums_score_gen(2), THREES: _nums_score_gen(3), FOURS: _nums_score_gen(4), FIVES: _nums_score_gen(5), SIXES: _nums_score_gen(6), FULL_HOUSE: _full_house_score, FOUR_OF_A_KIND: _four_of_a_kind_score, LITTLE_STRAIGHT: _little_straight_score, BIG_STRAIGHT: _big_straight_score, CHOICE: _choice_score } def score(dice, category): return category_score_map[category](dice)
en
0.348089
# Score categories.
3.05971
3
awx/main/models/ha.py
doziya/ansible
1
6623676
<gh_stars>1-10 # Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.timezone import now, timedelta from solo.models import SingletonModel from awx.api.versioning import reverse from awx.main.managers import InstanceManager, InstanceGroupManager from awx.main.models.inventory import InventoryUpdate from awx.main.models.jobs import Job from awx.main.models.projects import ProjectUpdate from awx.main.models.unified_jobs import UnifiedJob __all__ = ('Instance', 'InstanceGroup', 'JobOrigin', 'TowerScheduleState',) class Instance(models.Model): """A model representing an AWX instance running against this database.""" objects = InstanceManager() uuid = models.CharField(max_length=40) hostname = models.CharField(max_length=250, unique=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) last_isolated_check = models.DateTimeField( null=True, editable=False, auto_now_add=True ) version = models.CharField(max_length=24, blank=True) capacity = models.PositiveIntegerField( default=100, editable=False, ) class Meta: app_label = 'main' def get_absolute_url(self, request=None): return reverse('api:instance_detail', kwargs={'pk': self.pk}, request=request) @property def consumed_capacity(self): return sum(x.task_impact for x in UnifiedJob.objects.filter(execution_node=self.hostname, status__in=('running', 'waiting'))) @property def role(self): # NOTE: TODO: Likely to repurpose this once standalone ramparts are a thing return "awx" def is_lost(self, ref_time=None, isolated=False): if ref_time is None: ref_time = now() grace_period = 120 if isolated: grace_period = settings.AWX_ISOLATED_PERIODIC_CHECK * 2 return self.modified < ref_time - timedelta(seconds=grace_period) class InstanceGroup(models.Model): """A model representing a Queue/Group of AWX Instances.""" objects = InstanceGroupManager() name = models.CharField(max_length=250, unique=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) instances = models.ManyToManyField( 'Instance', related_name='rampart_groups', editable=False, help_text=_('Instances that are members of this InstanceGroup'), ) controller = models.ForeignKey( 'InstanceGroup', related_name='controlled_groups', help_text=_('Instance Group to remotely control this group.'), editable=False, default=None, null=True ) def get_absolute_url(self, request=None): return reverse('api:instance_group_detail', kwargs={'pk': self.pk}, request=request) @property def capacity(self): return sum([inst.capacity for inst in self.instances.all()]) class Meta: app_label = 'main' class TowerScheduleState(SingletonModel): schedule_last_run = models.DateTimeField(auto_now_add=True) class JobOrigin(models.Model): """A model representing the relationship between a unified job and the instance that was responsible for starting that job. It may be possible that a job has no origin (the common reason for this being that the job was started on Tower < 2.1 before origins were a thing). This is fine, and code should be able to handle it. A job with no origin is always assumed to *not* have the current instance as its origin. """ unified_job = models.OneToOneField(UnifiedJob, related_name='job_origin') instance = models.ForeignKey(Instance) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: app_label = 'main' # Unfortunately, the signal can't just be connected against UnifiedJob; it # turns out that creating a model's subclass doesn't fire the signal for the # superclass model. @receiver(post_save, sender=InventoryUpdate) @receiver(post_save, sender=Job) @receiver(post_save, sender=ProjectUpdate) def on_job_create(sender, instance, created=False, raw=False, **kwargs): """When a new job is created, save a record of its origin (the machine that started the job). """ # Sanity check: We only want to create a JobOrigin record in cases where # we are making a new record, and in normal situations. # # In other situations, we simply do nothing. if raw or not created: return # Create the JobOrigin record, which attaches to the current instance # (which started the job). job_origin, new = JobOrigin.objects.get_or_create( instance=Instance.objects.me(), unified_job=instance, )
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.timezone import now, timedelta from solo.models import SingletonModel from awx.api.versioning import reverse from awx.main.managers import InstanceManager, InstanceGroupManager from awx.main.models.inventory import InventoryUpdate from awx.main.models.jobs import Job from awx.main.models.projects import ProjectUpdate from awx.main.models.unified_jobs import UnifiedJob __all__ = ('Instance', 'InstanceGroup', 'JobOrigin', 'TowerScheduleState',) class Instance(models.Model): """A model representing an AWX instance running against this database.""" objects = InstanceManager() uuid = models.CharField(max_length=40) hostname = models.CharField(max_length=250, unique=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) last_isolated_check = models.DateTimeField( null=True, editable=False, auto_now_add=True ) version = models.CharField(max_length=24, blank=True) capacity = models.PositiveIntegerField( default=100, editable=False, ) class Meta: app_label = 'main' def get_absolute_url(self, request=None): return reverse('api:instance_detail', kwargs={'pk': self.pk}, request=request) @property def consumed_capacity(self): return sum(x.task_impact for x in UnifiedJob.objects.filter(execution_node=self.hostname, status__in=('running', 'waiting'))) @property def role(self): # NOTE: TODO: Likely to repurpose this once standalone ramparts are a thing return "awx" def is_lost(self, ref_time=None, isolated=False): if ref_time is None: ref_time = now() grace_period = 120 if isolated: grace_period = settings.AWX_ISOLATED_PERIODIC_CHECK * 2 return self.modified < ref_time - timedelta(seconds=grace_period) class InstanceGroup(models.Model): """A model representing a Queue/Group of AWX Instances.""" objects = InstanceGroupManager() name = models.CharField(max_length=250, unique=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) instances = models.ManyToManyField( 'Instance', related_name='rampart_groups', editable=False, help_text=_('Instances that are members of this InstanceGroup'), ) controller = models.ForeignKey( 'InstanceGroup', related_name='controlled_groups', help_text=_('Instance Group to remotely control this group.'), editable=False, default=None, null=True ) def get_absolute_url(self, request=None): return reverse('api:instance_group_detail', kwargs={'pk': self.pk}, request=request) @property def capacity(self): return sum([inst.capacity for inst in self.instances.all()]) class Meta: app_label = 'main' class TowerScheduleState(SingletonModel): schedule_last_run = models.DateTimeField(auto_now_add=True) class JobOrigin(models.Model): """A model representing the relationship between a unified job and the instance that was responsible for starting that job. It may be possible that a job has no origin (the common reason for this being that the job was started on Tower < 2.1 before origins were a thing). This is fine, and code should be able to handle it. A job with no origin is always assumed to *not* have the current instance as its origin. """ unified_job = models.OneToOneField(UnifiedJob, related_name='job_origin') instance = models.ForeignKey(Instance) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: app_label = 'main' # Unfortunately, the signal can't just be connected against UnifiedJob; it # turns out that creating a model's subclass doesn't fire the signal for the # superclass model. @receiver(post_save, sender=InventoryUpdate) @receiver(post_save, sender=Job) @receiver(post_save, sender=ProjectUpdate) def on_job_create(sender, instance, created=False, raw=False, **kwargs): """When a new job is created, save a record of its origin (the machine that started the job). """ # Sanity check: We only want to create a JobOrigin record in cases where # we are making a new record, and in normal situations. # # In other situations, we simply do nothing. if raw or not created: return # Create the JobOrigin record, which attaches to the current instance # (which started the job). job_origin, new = JobOrigin.objects.get_or_create( instance=Instance.objects.me(), unified_job=instance, )
en
0.969788
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. A model representing an AWX instance running against this database. # NOTE: TODO: Likely to repurpose this once standalone ramparts are a thing A model representing a Queue/Group of AWX Instances. A model representing the relationship between a unified job and the instance that was responsible for starting that job. It may be possible that a job has no origin (the common reason for this being that the job was started on Tower < 2.1 before origins were a thing). This is fine, and code should be able to handle it. A job with no origin is always assumed to *not* have the current instance as its origin. # Unfortunately, the signal can't just be connected against UnifiedJob; it # turns out that creating a model's subclass doesn't fire the signal for the # superclass model. When a new job is created, save a record of its origin (the machine that started the job). # Sanity check: We only want to create a JobOrigin record in cases where # we are making a new record, and in normal situations. # # In other situations, we simply do nothing. # Create the JobOrigin record, which attaches to the current instance # (which started the job).
1.871209
2
jsk_recognition/imagesift/sample/sift_keypoints.py
VT-ASIM-LAB/autoware.ai
0
6623677
#!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 from scipy.misc import lena import imagesift def main(): img = lena() frames, desc = imagesift.get_sift_keypoints(img) out = imagesift.draw_sift_frames(img, frames) cv2.imshow('sift image', out) cv2.waitKey(0) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 from scipy.misc import lena import imagesift def main(): img = lena() frames, desc = imagesift.get_sift_keypoints(img) out = imagesift.draw_sift_frames(img, frames) cv2.imshow('sift image', out) cv2.waitKey(0) if __name__ == '__main__': main()
en
0.352855
#!/usr/bin/env python # -*- coding: utf-8 -*-
2.961492
3
backend/Ehaat/details/migrations/0001_initial.py
shuttlesworthNEO/HackIIITD-fSociety
0
6623678
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-08-25 19:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Haat', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('address', models.TextField()), ('info', models.TextField()), ('theme', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('price', models.IntegerField()), ('promotions', models.TextField(blank=True, null=True)), ], ), migrations.CreateModel( name='Rating', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('userName', models.CharField(max_length=50)), ('value', models.IntegerField()), ('issueDate', models.DateTimeField(auto_now_add=True)), ('text', models.TextField(blank=True, null=True)), ], ), migrations.CreateModel( name='Stall', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('stallNumber', models.IntegerField()), ('story', models.TextField()), ('tags', models.TextField(blank=True, null=True)), ('haat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='details.Haat')), ], ), migrations.AddField( model_name='rating', name='stall', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='details.Stall'), ), migrations.AddField( model_name='product', name='stall', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='details.Stall'), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-08-25 19:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Haat', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('address', models.TextField()), ('info', models.TextField()), ('theme', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('price', models.IntegerField()), ('promotions', models.TextField(blank=True, null=True)), ], ), migrations.CreateModel( name='Rating', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('userName', models.CharField(max_length=50)), ('value', models.IntegerField()), ('issueDate', models.DateTimeField(auto_now_add=True)), ('text', models.TextField(blank=True, null=True)), ], ), migrations.CreateModel( name='Stall', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('stallNumber', models.IntegerField()), ('story', models.TextField()), ('tags', models.TextField(blank=True, null=True)), ('haat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='details.Haat')), ], ), migrations.AddField( model_name='rating', name='stall', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='details.Stall'), ), migrations.AddField( model_name='product', name='stall', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='details.Stall'), ), ]
en
0.769472
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-08-25 19:31
1.589288
2
08slice.py
Ulyssesss/Learn-Python
1
6623679
<reponame>Ulyssesss/Learn-Python l = [0, 1, 2, 3, 4, 5] print(l[0:3]) print(l[:3]) print(l[2:4]) print(l[-3:-1]) print(l[-3:]) ll = list(range(100)) print(ll[::5]) print((0, 1, 2, 3, 4, 5)[:3]) print('abc'[:2])
l = [0, 1, 2, 3, 4, 5] print(l[0:3]) print(l[:3]) print(l[2:4]) print(l[-3:-1]) print(l[-3:]) ll = list(range(100)) print(ll[::5]) print((0, 1, 2, 3, 4, 5)[:3]) print('abc'[:2])
none
1
3.681755
4
scripts/stt_wit.py
ray-hrst/stt
1
6623680
<reponame>ray-hrst/stt #!/usr/bin/env python # -*- coding: utf-8 -*- """Speech to text using wit.ai Speech-to-Text API. Example usage: python stt_wit.py /path/to/audio/sample.wav Notes: - Default sampling rate is 16 kHz - Language must be predefined in the user-interface - There isn't a lot of detail regarding the desired audio format, see: https://github.com/wit-ai/wit/issues/217 - No confidence level provided, default to 1.0 References: - https://wit.ai/ - https://github.com/wit-ai/pywit - https://www.liip.ch/en/blog/speech-recognition-with-wit-ai """ import os import time import argparse from wit import Wit def transcribe( filename, verbose=True): """Convert speech to text Args: filename (str): Path to audio file. Returns: transcript (unicode, utf-8): Transcription of audio file. proc_time (float): STT processing time. confidence (float): None provided, so default to 1.0. """ service = Wit(os.environ['SERVER_ACCESS_TOKEN']); # server access token response = None with open(filename, 'rb') as audio_file: start_time = time.time(); response = service.speech(audio_file, None, {'Content-Type': 'audio/wav'}) proc_time = time.time() - start_time transcript = response['_text'] if verbose: print("Filename: {}".format(filename)) print(transcript) print("Elapsed Time: {:.3f} seconds".format(proc_time)) print("Confidence: None Provided") return transcript, proc_time, 1.0 if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( 'path', help='File path for audio file to be transcribed') args = parser.parse_args() transcribe(args.path, verbose=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Speech to text using wit.ai Speech-to-Text API. Example usage: python stt_wit.py /path/to/audio/sample.wav Notes: - Default sampling rate is 16 kHz - Language must be predefined in the user-interface - There isn't a lot of detail regarding the desired audio format, see: https://github.com/wit-ai/wit/issues/217 - No confidence level provided, default to 1.0 References: - https://wit.ai/ - https://github.com/wit-ai/pywit - https://www.liip.ch/en/blog/speech-recognition-with-wit-ai """ import os import time import argparse from wit import Wit def transcribe( filename, verbose=True): """Convert speech to text Args: filename (str): Path to audio file. Returns: transcript (unicode, utf-8): Transcription of audio file. proc_time (float): STT processing time. confidence (float): None provided, so default to 1.0. """ service = Wit(os.environ['SERVER_ACCESS_TOKEN']); # server access token response = None with open(filename, 'rb') as audio_file: start_time = time.time(); response = service.speech(audio_file, None, {'Content-Type': 'audio/wav'}) proc_time = time.time() - start_time transcript = response['_text'] if verbose: print("Filename: {}".format(filename)) print(transcript) print("Elapsed Time: {:.3f} seconds".format(proc_time)) print("Confidence: None Provided") return transcript, proc_time, 1.0 if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( 'path', help='File path for audio file to be transcribed') args = parser.parse_args() transcribe(args.path, verbose=True)
en
0.618436
#!/usr/bin/env python # -*- coding: utf-8 -*- Speech to text using wit.ai Speech-to-Text API. Example usage: python stt_wit.py /path/to/audio/sample.wav Notes: - Default sampling rate is 16 kHz - Language must be predefined in the user-interface - There isn't a lot of detail regarding the desired audio format, see: https://github.com/wit-ai/wit/issues/217 - No confidence level provided, default to 1.0 References: - https://wit.ai/ - https://github.com/wit-ai/pywit - https://www.liip.ch/en/blog/speech-recognition-with-wit-ai Convert speech to text Args: filename (str): Path to audio file. Returns: transcript (unicode, utf-8): Transcription of audio file. proc_time (float): STT processing time. confidence (float): None provided, so default to 1.0. # server access token
3.451543
3
testcases/OpTestKdumpLparSmt.py
rashijhawar/op-test
23
6623681
<gh_stars>10-100 #!/usr/bin/env python2 # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: op-test-framework/testcases/OpTestKdumpLparSmt.py $ # # OpenPOWER Automated Test Project # # Contributors Listed Below - COPYRIGHT 2017 # [+] International Business Machines Corp. # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. # # IBM_PROLOG_END_TAG ''' OpTestKdump ------------ This module can contain testcases related to Kdump. Please install crash and kernel-default-debuginfo packages on the target machine where kdump is tested. 1. Configure kdump. 2. Run ffdc_validation script to check the configuration. 3. Trigger crash. 4. Check for vmcore and dmesg.txt. 5. Run crash tool on the vmcore captured. 6. Repeat Step3 to Step5 for different SMT levels. ''' import time import subprocess import commands import re import sys import pexpect import os import time from common.OpTestConstants import OpTestConstants as BMC_CONST from common.OpTestError import OpTestError from common import OpTestHMC import unittest import OpTestConfiguration from common.OpTestSystem import OpSystemState from common.OpTestSSH import ConsoleState as SSHConnectionState from common.Exceptions import KernelOOPS, KernelKdump class OpTestKernelBase(unittest.TestCase): def setUp(self): conf = OpTestConfiguration.conf self.cv_SYSTEM = conf.system() self.cv_HOST = conf.host() self.platform = conf.platform() self.bmc_type = conf.args.bmc_type self.util = self.cv_SYSTEM.util self.cv_HMC = self.cv_SYSTEM.hmc def kernel_crash(self): ''' This function will test the kdump followed by system reboot. it has below steps 1. Take backup of files under /var/crash. 2. Trigger kernel crash: ``echo c > /proc/sysrq-trigger`` ''' self.console = self.cv_HMC.get_console() self.cv_HMC.vterm_run_command(self.console, "mkdir -p /var/crash_bck/") self.cv_HMC.vterm_run_command(self.console, "mv /var/crash/* /var/crash_bck/") self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt") time.sleep(5) self.cv_HMC.vterm_run_command(self.console, "echo 1 > /proc/sys/kernel/sysrq") try: self.cv_HMC.vterm_run_command(self.console, "echo c > /proc/sysrq-trigger") except (KernelOOPS, KernelKdump): self.cv_HMC.wait_login_prompt(self.console, username="root", password="<PASSWORD>") def vmcore_check(self): ''' This function validates the vmcore captured. It has below steps. 1. Check for vmcore and dmesg.txt captured under /var/crash. 2. Run crash tool on captured vmcore. ''' self.console = self.cv_HMC.get_console() time.sleep(20) res = self.cv_HMC.vterm_run_command(self.console, 'ls -1 /var/crash') path_crash_dir = os.path.join("/var/crash", res[0]) if self.distro == 'SLES': file_list = ['vmcore','dmesg.txt'] crash_cmd = 'crash vmcore vmlinux* -i file' if self.distro == 'RHEL': file_list = ['vmcore','vmcore-dmesg.txt'] crash_cmd = 'crash /usr/lib/debug/lib/modules/`uname -r`/vmlinux vmcore -i file' res = self.cv_HMC.vterm_run_command(self.console, 'ls -1 %s' % path_crash_dir) for files in file_list: if files not in res: self.fail(" %s is not saved " % files) else: print(" %s is saved " % files) self.cv_HMC.vterm_run_command(self.console, "cd %s" % path_crash_dir) self.cv_HMC.vterm_run_command(self.console, 'echo -e "bt\\nbt -a\\nalias\\nascii\\nfiles\\nmount\\nps\\nq" > file') self.cv_HMC.vterm_run_command(self.console, crash_cmd, timeout=600) self.cv_HMC.vterm_run_command(self.console, "rm -rf /var/crash/*") print ("========== Please note that all the dumps under /var/crash are moved to /var/crash_bck ===========") class KernelCrash_Kdump(OpTestKernelBase): ''' This function will configure kdump. It has below steps. 1. Update crashkernel value, rebuild the grub and reboot the machine. 2. Run ffdc_validation script to check the configurations. ''' def setup_test(self): self.console = self.cv_HMC.get_console() self.cv_HMC.restart_lpar() self.cv_HMC.wait_login_prompt(self.console, username="root", password="<PASSWORD>") self.console = self.cv_HMC.get_console() self.cv_HMC.vterm_run_command(self.console, "uname -a") res = self.cv_HMC.vterm_run_command(self.console, "cat /etc/os-release | grep NAME | head -1") if 'SLES' in res[0].strip(): self.distro = 'SLES' self.cv_HMC.vterm_run_command(self.console, "sed -i 's/crashkernel=[0-9]\+M/crashkernel=2G-4G:512M,4G-64G:1024M,64G-128G:2048M,128G-:4096M/' /etc/default/grub;") self.cv_HMC.vterm_run_command(self.console, "grub2-mkconfig -o /boot/grub2/grub.cfg") self.cv_HMC.restart_lpar() self.cv_HMC.wait_login_prompt(self.console, username="root", password="<PASSWORD>") self.console = self.cv_HMC.get_console() elif 'Red Hat' in res[0].strip(): self.distro = 'RHEL' else: self.skipTest("Currently test is supported only on sles and rhel") res = self.cv_HMC.vterm_run_command(self.console, "service kdump status | grep active") if 'exited' not in res[0].strip(): print "Kdump service is not configured properly" def runTest(self): self.setup_test() self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt=off") self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt=2") self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt=4") self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --cores-on=1") self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --cores-on=1") self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt=off") self.kernel_crash() self.vmcore_check() def crash_suite(): s = unittest.TestSuite() s.addTest(KernelCrash_Kdump()) return s
#!/usr/bin/env python2 # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: op-test-framework/testcases/OpTestKdumpLparSmt.py $ # # OpenPOWER Automated Test Project # # Contributors Listed Below - COPYRIGHT 2017 # [+] International Business Machines Corp. # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. # # IBM_PROLOG_END_TAG ''' OpTestKdump ------------ This module can contain testcases related to Kdump. Please install crash and kernel-default-debuginfo packages on the target machine where kdump is tested. 1. Configure kdump. 2. Run ffdc_validation script to check the configuration. 3. Trigger crash. 4. Check for vmcore and dmesg.txt. 5. Run crash tool on the vmcore captured. 6. Repeat Step3 to Step5 for different SMT levels. ''' import time import subprocess import commands import re import sys import pexpect import os import time from common.OpTestConstants import OpTestConstants as BMC_CONST from common.OpTestError import OpTestError from common import OpTestHMC import unittest import OpTestConfiguration from common.OpTestSystem import OpSystemState from common.OpTestSSH import ConsoleState as SSHConnectionState from common.Exceptions import KernelOOPS, KernelKdump class OpTestKernelBase(unittest.TestCase): def setUp(self): conf = OpTestConfiguration.conf self.cv_SYSTEM = conf.system() self.cv_HOST = conf.host() self.platform = conf.platform() self.bmc_type = conf.args.bmc_type self.util = self.cv_SYSTEM.util self.cv_HMC = self.cv_SYSTEM.hmc def kernel_crash(self): ''' This function will test the kdump followed by system reboot. it has below steps 1. Take backup of files under /var/crash. 2. Trigger kernel crash: ``echo c > /proc/sysrq-trigger`` ''' self.console = self.cv_HMC.get_console() self.cv_HMC.vterm_run_command(self.console, "mkdir -p /var/crash_bck/") self.cv_HMC.vterm_run_command(self.console, "mv /var/crash/* /var/crash_bck/") self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt") time.sleep(5) self.cv_HMC.vterm_run_command(self.console, "echo 1 > /proc/sys/kernel/sysrq") try: self.cv_HMC.vterm_run_command(self.console, "echo c > /proc/sysrq-trigger") except (KernelOOPS, KernelKdump): self.cv_HMC.wait_login_prompt(self.console, username="root", password="<PASSWORD>") def vmcore_check(self): ''' This function validates the vmcore captured. It has below steps. 1. Check for vmcore and dmesg.txt captured under /var/crash. 2. Run crash tool on captured vmcore. ''' self.console = self.cv_HMC.get_console() time.sleep(20) res = self.cv_HMC.vterm_run_command(self.console, 'ls -1 /var/crash') path_crash_dir = os.path.join("/var/crash", res[0]) if self.distro == 'SLES': file_list = ['vmcore','dmesg.txt'] crash_cmd = 'crash vmcore vmlinux* -i file' if self.distro == 'RHEL': file_list = ['vmcore','vmcore-dmesg.txt'] crash_cmd = 'crash /usr/lib/debug/lib/modules/`uname -r`/vmlinux vmcore -i file' res = self.cv_HMC.vterm_run_command(self.console, 'ls -1 %s' % path_crash_dir) for files in file_list: if files not in res: self.fail(" %s is not saved " % files) else: print(" %s is saved " % files) self.cv_HMC.vterm_run_command(self.console, "cd %s" % path_crash_dir) self.cv_HMC.vterm_run_command(self.console, 'echo -e "bt\\nbt -a\\nalias\\nascii\\nfiles\\nmount\\nps\\nq" > file') self.cv_HMC.vterm_run_command(self.console, crash_cmd, timeout=600) self.cv_HMC.vterm_run_command(self.console, "rm -rf /var/crash/*") print ("========== Please note that all the dumps under /var/crash are moved to /var/crash_bck ===========") class KernelCrash_Kdump(OpTestKernelBase): ''' This function will configure kdump. It has below steps. 1. Update crashkernel value, rebuild the grub and reboot the machine. 2. Run ffdc_validation script to check the configurations. ''' def setup_test(self): self.console = self.cv_HMC.get_console() self.cv_HMC.restart_lpar() self.cv_HMC.wait_login_prompt(self.console, username="root", password="<PASSWORD>") self.console = self.cv_HMC.get_console() self.cv_HMC.vterm_run_command(self.console, "uname -a") res = self.cv_HMC.vterm_run_command(self.console, "cat /etc/os-release | grep NAME | head -1") if 'SLES' in res[0].strip(): self.distro = 'SLES' self.cv_HMC.vterm_run_command(self.console, "sed -i 's/crashkernel=[0-9]\+M/crashkernel=2G-4G:512M,4G-64G:1024M,64G-128G:2048M,128G-:4096M/' /etc/default/grub;") self.cv_HMC.vterm_run_command(self.console, "grub2-mkconfig -o /boot/grub2/grub.cfg") self.cv_HMC.restart_lpar() self.cv_HMC.wait_login_prompt(self.console, username="root", password="<PASSWORD>") self.console = self.cv_HMC.get_console() elif 'Red Hat' in res[0].strip(): self.distro = 'RHEL' else: self.skipTest("Currently test is supported only on sles and rhel") res = self.cv_HMC.vterm_run_command(self.console, "service kdump status | grep active") if 'exited' not in res[0].strip(): print "Kdump service is not configured properly" def runTest(self): self.setup_test() self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt=off") self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt=2") self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt=4") self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --cores-on=1") self.kernel_crash() self.vmcore_check() self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --cores-on=1") self.cv_HMC.vterm_run_command(self.console, "ppc64_cpu --smt=off") self.kernel_crash() self.vmcore_check() def crash_suite(): s = unittest.TestSuite() s.addTest(KernelCrash_Kdump()) return s
en
0.743033
#!/usr/bin/env python2 # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: op-test-framework/testcases/OpTestKdumpLparSmt.py $ # # OpenPOWER Automated Test Project # # Contributors Listed Below - COPYRIGHT 2017 # [+] International Business Machines Corp. # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. # # IBM_PROLOG_END_TAG OpTestKdump ------------ This module can contain testcases related to Kdump. Please install crash and kernel-default-debuginfo packages on the target machine where kdump is tested. 1. Configure kdump. 2. Run ffdc_validation script to check the configuration. 3. Trigger crash. 4. Check for vmcore and dmesg.txt. 5. Run crash tool on the vmcore captured. 6. Repeat Step3 to Step5 for different SMT levels. This function will test the kdump followed by system reboot. it has below steps 1. Take backup of files under /var/crash. 2. Trigger kernel crash: ``echo c > /proc/sysrq-trigger`` This function validates the vmcore captured. It has below steps. 1. Check for vmcore and dmesg.txt captured under /var/crash. 2. Run crash tool on captured vmcore. This function will configure kdump. It has below steps. 1. Update crashkernel value, rebuild the grub and reboot the machine. 2. Run ffdc_validation script to check the configurations.
1.914017
2
klab/cluster/python_script_template.py
Kortemme-Lab/klab
2
6623682
import sys from time import strftime import socket import os import platform import subprocess import tempfile import shutil import glob import re import shlex import traceback # Utility functions class ProcessOutput(object): def __init__(self, stdout, stderr, errorcode): self.stdout = stdout self.stderr = stderr self.errorcode = errorcode def getError(self): if self.errorcode != 0: return("Errorcode: %d\n%s" % (self.errorcode, self.stderr)) return None def Popen(outdir, args): subp = subprocess.Popen(shlex.split(" ".join([str(arg) for arg in args])), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=outdir, env={'SPARKSXDIR' : '/netapp/home/klabqb3backrub/tools/sparks-x'}) output = subp.communicate() return ProcessOutput(output[0], output[1], subp.returncode) # 0 is stdout, 1 is stderr def shell_execute(command_line): subp = subprocess.Popen(command_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output = subp.communicate() return ProcessOutput(output[0], output[1], subp.returncode) # 0 is stdout, 1 is stderr def create_scratch_path(): path = tempfile.mkdtemp(dir = '/scratch') if not os.path.isdir(path): raise os.error return path def print_tag(tag_name, content): print('<%s>%s</%s>' % (tag_name, content, tag_name)) def print_subprocess_output(subp): '''Prints the stdout and stderr output.''' if subp: if subp.errorcode != 0: print('<error errorcode="%s">' % str(subp.errorcode)) print(subp.stderr) print("</error>") print_tag('stdout', '\n%s\n' % subp.stdout) else: print_tag('success', '\n%s\n' % subp.stdout) print_tag('warnings', '\n%s\n' % subp.stderr) # Job/task parameters task_id = os.environ.get('SGE_TASK_ID') job_id = os.environ.get('JOB_ID') array_idx = int(task_id) - 1 # this can be used to index Python arrays (0-indexed) rather than task_id (based on 1-indexing) task_root_dir = None subp = None errorcode = 0 # failed jobs should set errorcode # Markup opener print('<task type="${JOB_NAME}" job_id="%s" task_id="%s">' % (job_id, task_id)) # Standard task properties - start time, host, architecture print_tag("start_time", strftime("%Y-%m-%d %H:%M:%S")) print_tag("host", socket.gethostname()) print_tag("architecture", platform.machine() + ', ' + platform.processor() + ', ' + platform.platform()) # Set up a scratch directory on the node scratch_path = create_scratch_path() print_tag("cwd", scratch_path) # Job data arrays. This section defines arrays that are used for tasks. ${JOB_DATA_ARRAYS} # Job setup. The job's root directory must be specified inside this block. ${JOB_SETUP_COMMANDS} if not os.path.exists(task_root_dir): raise Exception("You must set the task's root directory so that the script can clean up the job.") # Job execution block. Note: failed jobs should set errorcode. print("<output>") ${JOB_EXECUTION_COMMANDS} print("</output>") # Post-processing. Copy files from scratch back to /netapp. shutil.rmtree(task_root_dir, ignore_errors=True) shutil.copytree(scratch_path, task_root_dir) shutil.rmtree(scratch_path) ${JOB_POST_PROCESSING_COMMANDS} # Print task run details. The full path to qstat seems necessary on the QB3 cluster if you are not using a bash shell. task_usages = shell_execute('/usr/local/sge/bin/linux-x64/qstat -j %s' % job_id) if task_usages.errorcode == 0: try: print("<qstat>") print(task_usages.stdout) print("</qstat>") mtchs = re.match('.*?usage\s*(\d+):(.*?)\n.*', task_usages.stdout, re.DOTALL) print(mtchs) if mtchs and str(mtchs.group(1)) == str(task_id): task_properties = [s.strip() for s in mtchs.group(2).strip().split(",")] for tp in task_properties: if tp: prp=tp.split('=')[0] v=tp.split('=')[1] print('<task_%s>%s</task_%s>' % (prp, v, prp)) except Exception, e: print('<qstat_parse_error>') print(str(e)) print(traceback.format_exc()) print('</qstat_parse_error>') else: print_tag('qstat_error', task_usages.stderr) # Print the end walltime and close the outer tag print_tag("end_time", strftime("%Y-%m-%d %H:%M:%S")) print("</task>") # Exit the job with the errorcode set in the execution block if errorcode != 0: sys.exit(subp.errorcode)
import sys from time import strftime import socket import os import platform import subprocess import tempfile import shutil import glob import re import shlex import traceback # Utility functions class ProcessOutput(object): def __init__(self, stdout, stderr, errorcode): self.stdout = stdout self.stderr = stderr self.errorcode = errorcode def getError(self): if self.errorcode != 0: return("Errorcode: %d\n%s" % (self.errorcode, self.stderr)) return None def Popen(outdir, args): subp = subprocess.Popen(shlex.split(" ".join([str(arg) for arg in args])), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=outdir, env={'SPARKSXDIR' : '/netapp/home/klabqb3backrub/tools/sparks-x'}) output = subp.communicate() return ProcessOutput(output[0], output[1], subp.returncode) # 0 is stdout, 1 is stderr def shell_execute(command_line): subp = subprocess.Popen(command_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output = subp.communicate() return ProcessOutput(output[0], output[1], subp.returncode) # 0 is stdout, 1 is stderr def create_scratch_path(): path = tempfile.mkdtemp(dir = '/scratch') if not os.path.isdir(path): raise os.error return path def print_tag(tag_name, content): print('<%s>%s</%s>' % (tag_name, content, tag_name)) def print_subprocess_output(subp): '''Prints the stdout and stderr output.''' if subp: if subp.errorcode != 0: print('<error errorcode="%s">' % str(subp.errorcode)) print(subp.stderr) print("</error>") print_tag('stdout', '\n%s\n' % subp.stdout) else: print_tag('success', '\n%s\n' % subp.stdout) print_tag('warnings', '\n%s\n' % subp.stderr) # Job/task parameters task_id = os.environ.get('SGE_TASK_ID') job_id = os.environ.get('JOB_ID') array_idx = int(task_id) - 1 # this can be used to index Python arrays (0-indexed) rather than task_id (based on 1-indexing) task_root_dir = None subp = None errorcode = 0 # failed jobs should set errorcode # Markup opener print('<task type="${JOB_NAME}" job_id="%s" task_id="%s">' % (job_id, task_id)) # Standard task properties - start time, host, architecture print_tag("start_time", strftime("%Y-%m-%d %H:%M:%S")) print_tag("host", socket.gethostname()) print_tag("architecture", platform.machine() + ', ' + platform.processor() + ', ' + platform.platform()) # Set up a scratch directory on the node scratch_path = create_scratch_path() print_tag("cwd", scratch_path) # Job data arrays. This section defines arrays that are used for tasks. ${JOB_DATA_ARRAYS} # Job setup. The job's root directory must be specified inside this block. ${JOB_SETUP_COMMANDS} if not os.path.exists(task_root_dir): raise Exception("You must set the task's root directory so that the script can clean up the job.") # Job execution block. Note: failed jobs should set errorcode. print("<output>") ${JOB_EXECUTION_COMMANDS} print("</output>") # Post-processing. Copy files from scratch back to /netapp. shutil.rmtree(task_root_dir, ignore_errors=True) shutil.copytree(scratch_path, task_root_dir) shutil.rmtree(scratch_path) ${JOB_POST_PROCESSING_COMMANDS} # Print task run details. The full path to qstat seems necessary on the QB3 cluster if you are not using a bash shell. task_usages = shell_execute('/usr/local/sge/bin/linux-x64/qstat -j %s' % job_id) if task_usages.errorcode == 0: try: print("<qstat>") print(task_usages.stdout) print("</qstat>") mtchs = re.match('.*?usage\s*(\d+):(.*?)\n.*', task_usages.stdout, re.DOTALL) print(mtchs) if mtchs and str(mtchs.group(1)) == str(task_id): task_properties = [s.strip() for s in mtchs.group(2).strip().split(",")] for tp in task_properties: if tp: prp=tp.split('=')[0] v=tp.split('=')[1] print('<task_%s>%s</task_%s>' % (prp, v, prp)) except Exception, e: print('<qstat_parse_error>') print(str(e)) print(traceback.format_exc()) print('</qstat_parse_error>') else: print_tag('qstat_error', task_usages.stderr) # Print the end walltime and close the outer tag print_tag("end_time", strftime("%Y-%m-%d %H:%M:%S")) print("</task>") # Exit the job with the errorcode set in the execution block if errorcode != 0: sys.exit(subp.errorcode)
en
0.795586
# Utility functions # 0 is stdout, 1 is stderr # 0 is stdout, 1 is stderr Prints the stdout and stderr output. # Job/task parameters # this can be used to index Python arrays (0-indexed) rather than task_id (based on 1-indexing) # failed jobs should set errorcode # Markup opener # Standard task properties - start time, host, architecture # Set up a scratch directory on the node # Job data arrays. This section defines arrays that are used for tasks. # Job setup. The job's root directory must be specified inside this block. # Job execution block. Note: failed jobs should set errorcode. # Post-processing. Copy files from scratch back to /netapp. # Print task run details. The full path to qstat seems necessary on the QB3 cluster if you are not using a bash shell. # Print the end walltime and close the outer tag # Exit the job with the errorcode set in the execution block
2.248761
2
ElectionTwitterSentiment-IssueResolving.py
ridhitbhura/NLP-Twitter
0
6623683
#!/usr/bin/env python # coding: utf-8 # # NLP of Prime Minister Narendra Modi's Tweets during COVID-19 # #### By <NAME> # In this project, I gathered a dataset from https://www.kaggle.com/saurabhshahane/twitter-sentiment-dataset and use the pretrained data to train a set of ~3500 tweets from Prime Minister Narendra Modi's personal twitter account. The process includes 1) twitter data extraction which can be found in the git directory for this project, 2) preprocessing of the test data (Modi tweets), 3) visualisation techniques and 4) Standard Scale & Random Forest Classifier model training. # Due to migration to the M1 MacBook, the machine learning portion has bugs (specifically token labelling) which will be fixed shortly. # Nonetheless I was able to obtain >96% accuracy in model training for both the models. # ## Importing Packages # In[103]: #Importing All Necessary Packages and Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from wordcloud import WordCloud from PIL import Image import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.model_selection import train_test_split, StratifiedKFold from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import accuracy_score, f1_score, classification_report,confusion_matrix from sklearn.linear_model import LogisticRegression import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns import warnings import re re.compile('<title>(.*)</title>') # In[104]: #Importing the relevant test and train datesets from their respective csv filepaths. train = pd.read_csv('/Users/ridhitbhura/Downloads/Twitter_Data.csv') test = pd.read_csv('/Users/ridhitbhura/Downloads/twitterdatamodi.csv') print(test.shape) print(train.shape) # In[105]: test.head() # In[106]: train.head() # ## Cleaning The Datasets # In[107]: test.isna().sum() # In[108]: train.isna().sum() # In[109]: train[train['category'].isna()] # In[110]: train[train['clean_text'].isna()] # In[111]: train.drop(train[train['clean_text'].isna()].index, inplace=True) train.drop(train[train['category'].isna()].index, inplace=True) # ## Dataset Cleaning & Preprocessing # ### Deleting Non-English Words # In[112]: def delete_non_english(var): try: var = re.sub(r'\W+', ' ', var) var = var.lower() var = var.replace("[^a-zA-Z]", " ") word_tokens = word_tokenize(var) cleaned_word = [w for w in word_tokens if all(ord(c) < 128 for c in w)] cleaned_word = [w + " " for w in cleaned_word] return "".join(cleaned_word) except: return np.nan test["english_text"] = test.Tweet_Text.apply(delete_non_english) # In[113]: test.head() # ### Cleaning English Text # In[114]: def clean_text(english_txt): try: word_tokens = word_tokenize(english_txt) cleaned_word = [w for w in word_tokens if not w in stop_words] cleaned_word = [w + " " for w in cleaned_word] return "".join(cleaned_word) except: return np.nan test["cleaned_text"] = test.english_text.apply(clean_text) # In[115]: test.head() # In[116]: #Adopted code def remove_link_email(txt): txt = re.sub(r"https t co \S+", "", txt) txt = txt.replace('\S*@\S*\s?', "") txt = re.sub(r'[^\w\s]', '', txt) return txt test["final_text"] = test.english_text.apply(remove_link_email) # In[117]: test.head() # ## Visualisations # ### Word Frequency # In[118]: from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(stop_words = 'english') words = cv.fit_transform(test.final_text) sum_words = words.sum(axis=0) words_freq = [(word, sum_words[0, i]) for word, i in cv.vocabulary_.items()] words_freq = sorted(words_freq, key = lambda x: x[1], reverse = True) frequency = pd.DataFrame(words_freq, columns=['word', 'freq']) frequency.head(20).plot(x='word', y='freq', kind='bar', figsize=(15, 7), color = 'blue') plt.title("Word Occurunce Frequency - Top 20") # ### Word Cloud # In[130]: wordcloud = WordCloud(background_color = 'white', width = 1000, height = 1000, font_path = '/Users/ridhitbhura/Downloads/fainland/Fainland.ttf').generate_from_frequencies(dict(words_freq)) plt.figure(figsize=(12,9)) plt.imshow(wordcloud) plt.title("Most Common Words - Test Data", fontsize = 24) # In[131]: #Nuetral Words normal_words =' '.join([text for text in train['clean_text'][train['category'] == 0]]) wordcloud = WordCloud(background_color = 'white', width=800, height=500, random_state = 0, max_font_size = 110, font_path = '/Users/ridhitbhura/Downloads/fainland/Fainland.ttf').generate(normal_words) plt.figure(figsize=(12, 9)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis('off') plt.title('Neutral Words - Training Data') plt.show() # In[132]: #Negative Words normal_words =' '.join([text for text in train['clean_text'][train['category'] == -1]]) wordcloud = WordCloud(background_color = 'white', width=800, height=500, random_state = 0, max_font_size = 110, font_path = '/Users/ridhitbhura/Downloads/fainland/Fainland.ttf').generate(normal_words) plt.figure(figsize=(12, 9)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis('off') plt.title('Negative Words - Training Data') plt.show() # In[133]: #Positive Words normal_words =' '.join([text for text in train['clean_text'][train['category'] == 1]]) wordcloud = WordCloud(background_color = 'white', width=800, height=500, random_state = 0, max_font_size = 110,font_path = '/Users/ridhitbhura/Downloads/fainland/Fainland.ttf').generate(normal_words) plt.figure(figsize=(12, 9)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis('off') plt.title('Positive Words - Training Data') plt.show() # ### Hashtag Frequency Distribution # In[134]: #Hashtag Collection def hashtag_extract(x): hashtags = [] for i in x: ht = re.findall(r"#(\w+)", i) hashtags.append(ht) return hashtags # In[136]: # extracting hashtags from the test dataset HT_test = hashtag_extract(test['Tweet_Text']) # extracting hashtags from the training dataset by sentiment category HT_train_negative = hashtag_extract(train['clean_text'][train['category'] == -1]) HT_train_positive = hashtag_extract(train['clean_text'][train['category'] == 1]) HT_train_neutral = hashtag_extract(train['clean_text'][train['category'] == 0]) # removing nested attribute and simplifying the list HT_test = sum(HT_test, []) HT_train_negative = sum(HT_train_negative, []) HT_train_positive = sum(HT_train_positive, []) HT_train_neutral = sum(HT_train_neutral, []) # In[138]: a = nltk.FreqDist(HT_test) d = pd.DataFrame({'Hashtag': list(a.keys()), 'Count': list(a.values())}) # selecting top 10 most frequent hashtags d = d.nlargest(columns="Count", n = 10) plt.figure(figsize=(30, 5)) # width:30, height:3 plt.xticks(range(1, len(a.keys())+1), a.keys(), size='small') ax = sns.barplot(data=d, x= "Hashtag", y = "Count") ax.set(ylabel = 'Count') plt.title('Most Frequently Used Hasthags (Unhashed) - Test Data') plt.show() # ## Machine Learning Analysis # In[139]: #Tokenizing the training dataset tokenized_tweet = train['clean_text'].apply(lambda x: x.split()) # importing gensim import gensim # creating a word to vector model model_w2v = gensim.models.Word2Vec( tokenized_tweet, window=5, # context window size min_count=2, sg = 1, # 1 for skip-gram model hs = 0, negative = 10, # for negative sampling workers= 2, # no.of cores seed = 34) model_w2v.train(tokenized_tweet, total_examples= len(train['clean_text']), epochs=20) # ### Testing vectorisation of the model with test cases # In[140]: model_w2v.wv.most_similar(positive = "election") # In[141]: model_w2v.wv.most_similar(positive = "cancer") # In[142]: model_w2v.wv.most_similar(positive = "victory") # ### Labelling Tokenized Words # In[31]: from tqdm import tqdm tqdm.pandas(desc="progress-bar") from gensim.models.deprecated.doc2vec import LabeledSentence LabeledSentence = gensim.models.deprecated.doc2vec.LabeledSentence # In[32]: def add_label(twt): output = [] for i, s in zip(twt.index, twt): output.append(LabeledSentence(s, ["tweet_" + str(i)])) return output # label all the tweets labeled_tweets = add_label(tokenized_tweet) labeled_tweets[:6] # In[33]: print(train.shape) print(test.shape) # In[34]: train.shape # ### Assigning test-train splits in the data # In[49]: import re import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer # In[60]: get_ipython().run_cell_magic('time', '', "train_corpus = []\ntry:\n for i in range(0, 162969):\n review = re.sub('[^a-zA-Z]', ' ', train['clean_text'][i])\n review = review.lower()\n review = review.split()\n\n ps = PorterStemmer()\n # stemming\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\n # joining them back with space\n review = ' '.join(review)\n train_corpus.append(review)\nexcept KeyError:\n train_corpus.append(' ')") # In[61]: get_ipython().run_cell_magic('time', '', "test_corpus = []\n\nfor i in range(0, 3250):\n review = re.sub('[^a-zA-Z]', ' ', test['english_text'][i])\n review = review.lower()\n review = review.split()\n ps = PorterStemmer()\n # stemming\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\n # joining them back with space\n review = ' '.join(review)\n test_corpus.append(review)") # In[62]: from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features = 2500) x = cv.fit_transform(train_corpus).toarray() y = train.iloc[:, 1] print(x.shape) print(y.shape) # In[63]: # creating bag of words from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features = 2500) x_test = cv.fit_transform(test_corpus).toarray() print(x_test.shape) # In[64]: # splitting the training data into train and valid sets from sklearn.model_selection import train_test_split x_train, x_valid, y_train, y_valid = train_test_split(x, y, test_size = 0.25, random_state = 42) print(x_train.shape) print(x_valid.shape) print(y_train.shape) print(y_valid.shape) # In[65]: from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_train = sc.fit_transform(x_train) x_valid = sc.transform(x_valid) x_test = sc.transform(x_test) # In[66]: from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score model = RandomForestClassifier() model.fit(x_train, y_train) y_pred = model.predict(x_valid) print("Training Accuracy :", model.score(x_train, y_train)) print("Validation Accuracy :", model.score(x_valid, y_valid)) # calculating the f1 score for the validation set print("F1 score :", f1_score(y_valid, y_pred)) # confusion matrix cm = confusion_matrix(y_valid, y_pred) print(cm) # In[ ]:
#!/usr/bin/env python # coding: utf-8 # # NLP of Prime Minister Narendra Modi's Tweets during COVID-19 # #### By <NAME> # In this project, I gathered a dataset from https://www.kaggle.com/saurabhshahane/twitter-sentiment-dataset and use the pretrained data to train a set of ~3500 tweets from Prime Minister Narendra Modi's personal twitter account. The process includes 1) twitter data extraction which can be found in the git directory for this project, 2) preprocessing of the test data (Modi tweets), 3) visualisation techniques and 4) Standard Scale & Random Forest Classifier model training. # Due to migration to the M1 MacBook, the machine learning portion has bugs (specifically token labelling) which will be fixed shortly. # Nonetheless I was able to obtain >96% accuracy in model training for both the models. # ## Importing Packages # In[103]: #Importing All Necessary Packages and Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from wordcloud import WordCloud from PIL import Image import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.model_selection import train_test_split, StratifiedKFold from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import accuracy_score, f1_score, classification_report,confusion_matrix from sklearn.linear_model import LogisticRegression import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns import warnings import re re.compile('<title>(.*)</title>') # In[104]: #Importing the relevant test and train datesets from their respective csv filepaths. train = pd.read_csv('/Users/ridhitbhura/Downloads/Twitter_Data.csv') test = pd.read_csv('/Users/ridhitbhura/Downloads/twitterdatamodi.csv') print(test.shape) print(train.shape) # In[105]: test.head() # In[106]: train.head() # ## Cleaning The Datasets # In[107]: test.isna().sum() # In[108]: train.isna().sum() # In[109]: train[train['category'].isna()] # In[110]: train[train['clean_text'].isna()] # In[111]: train.drop(train[train['clean_text'].isna()].index, inplace=True) train.drop(train[train['category'].isna()].index, inplace=True) # ## Dataset Cleaning & Preprocessing # ### Deleting Non-English Words # In[112]: def delete_non_english(var): try: var = re.sub(r'\W+', ' ', var) var = var.lower() var = var.replace("[^a-zA-Z]", " ") word_tokens = word_tokenize(var) cleaned_word = [w for w in word_tokens if all(ord(c) < 128 for c in w)] cleaned_word = [w + " " for w in cleaned_word] return "".join(cleaned_word) except: return np.nan test["english_text"] = test.Tweet_Text.apply(delete_non_english) # In[113]: test.head() # ### Cleaning English Text # In[114]: def clean_text(english_txt): try: word_tokens = word_tokenize(english_txt) cleaned_word = [w for w in word_tokens if not w in stop_words] cleaned_word = [w + " " for w in cleaned_word] return "".join(cleaned_word) except: return np.nan test["cleaned_text"] = test.english_text.apply(clean_text) # In[115]: test.head() # In[116]: #Adopted code def remove_link_email(txt): txt = re.sub(r"https t co \S+", "", txt) txt = txt.replace('\S*@\S*\s?', "") txt = re.sub(r'[^\w\s]', '', txt) return txt test["final_text"] = test.english_text.apply(remove_link_email) # In[117]: test.head() # ## Visualisations # ### Word Frequency # In[118]: from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(stop_words = 'english') words = cv.fit_transform(test.final_text) sum_words = words.sum(axis=0) words_freq = [(word, sum_words[0, i]) for word, i in cv.vocabulary_.items()] words_freq = sorted(words_freq, key = lambda x: x[1], reverse = True) frequency = pd.DataFrame(words_freq, columns=['word', 'freq']) frequency.head(20).plot(x='word', y='freq', kind='bar', figsize=(15, 7), color = 'blue') plt.title("Word Occurunce Frequency - Top 20") # ### Word Cloud # In[130]: wordcloud = WordCloud(background_color = 'white', width = 1000, height = 1000, font_path = '/Users/ridhitbhura/Downloads/fainland/Fainland.ttf').generate_from_frequencies(dict(words_freq)) plt.figure(figsize=(12,9)) plt.imshow(wordcloud) plt.title("Most Common Words - Test Data", fontsize = 24) # In[131]: #Nuetral Words normal_words =' '.join([text for text in train['clean_text'][train['category'] == 0]]) wordcloud = WordCloud(background_color = 'white', width=800, height=500, random_state = 0, max_font_size = 110, font_path = '/Users/ridhitbhura/Downloads/fainland/Fainland.ttf').generate(normal_words) plt.figure(figsize=(12, 9)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis('off') plt.title('Neutral Words - Training Data') plt.show() # In[132]: #Negative Words normal_words =' '.join([text for text in train['clean_text'][train['category'] == -1]]) wordcloud = WordCloud(background_color = 'white', width=800, height=500, random_state = 0, max_font_size = 110, font_path = '/Users/ridhitbhura/Downloads/fainland/Fainland.ttf').generate(normal_words) plt.figure(figsize=(12, 9)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis('off') plt.title('Negative Words - Training Data') plt.show() # In[133]: #Positive Words normal_words =' '.join([text for text in train['clean_text'][train['category'] == 1]]) wordcloud = WordCloud(background_color = 'white', width=800, height=500, random_state = 0, max_font_size = 110,font_path = '/Users/ridhitbhura/Downloads/fainland/Fainland.ttf').generate(normal_words) plt.figure(figsize=(12, 9)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis('off') plt.title('Positive Words - Training Data') plt.show() # ### Hashtag Frequency Distribution # In[134]: #Hashtag Collection def hashtag_extract(x): hashtags = [] for i in x: ht = re.findall(r"#(\w+)", i) hashtags.append(ht) return hashtags # In[136]: # extracting hashtags from the test dataset HT_test = hashtag_extract(test['Tweet_Text']) # extracting hashtags from the training dataset by sentiment category HT_train_negative = hashtag_extract(train['clean_text'][train['category'] == -1]) HT_train_positive = hashtag_extract(train['clean_text'][train['category'] == 1]) HT_train_neutral = hashtag_extract(train['clean_text'][train['category'] == 0]) # removing nested attribute and simplifying the list HT_test = sum(HT_test, []) HT_train_negative = sum(HT_train_negative, []) HT_train_positive = sum(HT_train_positive, []) HT_train_neutral = sum(HT_train_neutral, []) # In[138]: a = nltk.FreqDist(HT_test) d = pd.DataFrame({'Hashtag': list(a.keys()), 'Count': list(a.values())}) # selecting top 10 most frequent hashtags d = d.nlargest(columns="Count", n = 10) plt.figure(figsize=(30, 5)) # width:30, height:3 plt.xticks(range(1, len(a.keys())+1), a.keys(), size='small') ax = sns.barplot(data=d, x= "Hashtag", y = "Count") ax.set(ylabel = 'Count') plt.title('Most Frequently Used Hasthags (Unhashed) - Test Data') plt.show() # ## Machine Learning Analysis # In[139]: #Tokenizing the training dataset tokenized_tweet = train['clean_text'].apply(lambda x: x.split()) # importing gensim import gensim # creating a word to vector model model_w2v = gensim.models.Word2Vec( tokenized_tweet, window=5, # context window size min_count=2, sg = 1, # 1 for skip-gram model hs = 0, negative = 10, # for negative sampling workers= 2, # no.of cores seed = 34) model_w2v.train(tokenized_tweet, total_examples= len(train['clean_text']), epochs=20) # ### Testing vectorisation of the model with test cases # In[140]: model_w2v.wv.most_similar(positive = "election") # In[141]: model_w2v.wv.most_similar(positive = "cancer") # In[142]: model_w2v.wv.most_similar(positive = "victory") # ### Labelling Tokenized Words # In[31]: from tqdm import tqdm tqdm.pandas(desc="progress-bar") from gensim.models.deprecated.doc2vec import LabeledSentence LabeledSentence = gensim.models.deprecated.doc2vec.LabeledSentence # In[32]: def add_label(twt): output = [] for i, s in zip(twt.index, twt): output.append(LabeledSentence(s, ["tweet_" + str(i)])) return output # label all the tweets labeled_tweets = add_label(tokenized_tweet) labeled_tweets[:6] # In[33]: print(train.shape) print(test.shape) # In[34]: train.shape # ### Assigning test-train splits in the data # In[49]: import re import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer # In[60]: get_ipython().run_cell_magic('time', '', "train_corpus = []\ntry:\n for i in range(0, 162969):\n review = re.sub('[^a-zA-Z]', ' ', train['clean_text'][i])\n review = review.lower()\n review = review.split()\n\n ps = PorterStemmer()\n # stemming\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\n # joining them back with space\n review = ' '.join(review)\n train_corpus.append(review)\nexcept KeyError:\n train_corpus.append(' ')") # In[61]: get_ipython().run_cell_magic('time', '', "test_corpus = []\n\nfor i in range(0, 3250):\n review = re.sub('[^a-zA-Z]', ' ', test['english_text'][i])\n review = review.lower()\n review = review.split()\n ps = PorterStemmer()\n # stemming\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\n # joining them back with space\n review = ' '.join(review)\n test_corpus.append(review)") # In[62]: from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features = 2500) x = cv.fit_transform(train_corpus).toarray() y = train.iloc[:, 1] print(x.shape) print(y.shape) # In[63]: # creating bag of words from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features = 2500) x_test = cv.fit_transform(test_corpus).toarray() print(x_test.shape) # In[64]: # splitting the training data into train and valid sets from sklearn.model_selection import train_test_split x_train, x_valid, y_train, y_valid = train_test_split(x, y, test_size = 0.25, random_state = 42) print(x_train.shape) print(x_valid.shape) print(y_train.shape) print(y_valid.shape) # In[65]: from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_train = sc.fit_transform(x_train) x_valid = sc.transform(x_valid) x_test = sc.transform(x_test) # In[66]: from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score model = RandomForestClassifier() model.fit(x_train, y_train) y_pred = model.predict(x_valid) print("Training Accuracy :", model.score(x_train, y_train)) print("Validation Accuracy :", model.score(x_valid, y_valid)) # calculating the f1 score for the validation set print("F1 score :", f1_score(y_valid, y_pred)) # confusion matrix cm = confusion_matrix(y_valid, y_pred) print(cm) # In[ ]:
en
0.684227
#!/usr/bin/env python # coding: utf-8 # # NLP of Prime Minister Narendra Modi's Tweets during COVID-19 # #### By <NAME> # In this project, I gathered a dataset from https://www.kaggle.com/saurabhshahane/twitter-sentiment-dataset and use the pretrained data to train a set of ~3500 tweets from Prime Minister Narendra Modi's personal twitter account. The process includes 1) twitter data extraction which can be found in the git directory for this project, 2) preprocessing of the test data (Modi tweets), 3) visualisation techniques and 4) Standard Scale & Random Forest Classifier model training. # Due to migration to the M1 MacBook, the machine learning portion has bugs (specifically token labelling) which will be fixed shortly. # Nonetheless I was able to obtain >96% accuracy in model training for both the models. # ## Importing Packages # In[103]: #Importing All Necessary Packages and Libraries # In[104]: #Importing the relevant test and train datesets from their respective csv filepaths. # In[105]: # In[106]: # ## Cleaning The Datasets # In[107]: # In[108]: # In[109]: # In[110]: # In[111]: # ## Dataset Cleaning & Preprocessing # ### Deleting Non-English Words # In[112]: # In[113]: # ### Cleaning English Text # In[114]: # In[115]: # In[116]: #Adopted code # In[117]: # ## Visualisations # ### Word Frequency # In[118]: # ### Word Cloud # In[130]: # In[131]: #Nuetral Words # In[132]: #Negative Words # In[133]: #Positive Words # ### Hashtag Frequency Distribution # In[134]: #Hashtag Collection # In[136]: # extracting hashtags from the test dataset # extracting hashtags from the training dataset by sentiment category # removing nested attribute and simplifying the list # In[138]: # selecting top 10 most frequent hashtags # width:30, height:3 # ## Machine Learning Analysis # In[139]: #Tokenizing the training dataset # importing gensim # creating a word to vector model # context window size # 1 for skip-gram model # for negative sampling # no.of cores # ### Testing vectorisation of the model with test cases # In[140]: # In[141]: # In[142]: # ### Labelling Tokenized Words # In[31]: # In[32]: # label all the tweets # In[33]: # In[34]: # ### Assigning test-train splits in the data # In[49]: # In[60]: # stemming\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\n # joining them back with space\n review = ' '.join(review)\n train_corpus.append(review)\nexcept KeyError:\n train_corpus.append(' ')") # In[61]: # stemming\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\n # joining them back with space\n review = ' '.join(review)\n test_corpus.append(review)") # In[62]: # In[63]: # creating bag of words # In[64]: # splitting the training data into train and valid sets # In[65]: # In[66]: # calculating the f1 score for the validation set # confusion matrix # In[ ]:
2.953359
3
recipe/middlewares.py
gotoeveryone/myrecipe
0
6623684
<gh_stars>0 """ カスタムミドルウェア """ import json from django.conf import settings from django.utils.deprecation import MiddlewareMixin from django.utils.functional import SimpleLazyObject from recipe.core.models import User class WebApiAuthenticationMiddleware(MiddlewareMixin): """ API認証ミドルウェア """ def process_request(self, request): """ リクエスト時の処理 @param request """ assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE%s setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'recipe.middlewares.WebApiAuthenticationMiddleware'." ) % ("_CLASSES" if settings.MIDDLEWARE is None else "") request.user = SimpleLazyObject(lambda: self.get_user(request)) @classmethod def get_user(cls, request): """ セッションからログインユーザを取得する @param request """ from django.contrib.auth.models import AnonymousUser user_data = request.session.get('user') if not user_data: return AnonymousUser() return User().from_json(json.loads(user_data))
""" カスタムミドルウェア """ import json from django.conf import settings from django.utils.deprecation import MiddlewareMixin from django.utils.functional import SimpleLazyObject from recipe.core.models import User class WebApiAuthenticationMiddleware(MiddlewareMixin): """ API認証ミドルウェア """ def process_request(self, request): """ リクエスト時の処理 @param request """ assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE%s setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'recipe.middlewares.WebApiAuthenticationMiddleware'." ) % ("_CLASSES" if settings.MIDDLEWARE is None else "") request.user = SimpleLazyObject(lambda: self.get_user(request)) @classmethod def get_user(cls, request): """ セッションからログインユーザを取得する @param request """ from django.contrib.auth.models import AnonymousUser user_data = request.session.get('user') if not user_data: return AnonymousUser() return User().from_json(json.loads(user_data))
ja
0.999416
カスタムミドルウェア API認証ミドルウェア リクエスト時の処理 @param request セッションからログインユーザを取得する @param request
2.363202
2
src/operators/test_identity.py
ClarkChiu/learn-python-tw
3
6623685
<reponame>ClarkChiu/learn-python-tw """恆等運算子 @詳見: https://www.w3schools.com/python/python_operators.asp 恆等運算子用途為比較物件,不僅是比較物件的內容,而是會更進一步比較到物件的記憶體位址 """ def test_identity_operators(): """恆等運算子""" # 讓我們使用以下的串列來說明恆等運算子 first_fruits_list = ["apple", "banana"] second_fruits_list = ["apple", "banana"] third_fruits_list = first_fruits_list # 是(is) # 比對兩個變數,若這兩個變數是相同的物件,則回傳真值 # 範例: # first_fruits_list 和 third_fruits_list 是相同的物件 assert first_fruits_list is third_fruits_list # 不是(is not) # 比對兩個變數,若這兩個變數不是相同的物件,則回傳真值 # 範例: # 雖然 first_fruits_list 和 second_fruits_list 有著相同的內容,但他們不是相同的物件 assert first_fruits_list is not second_fruits_list # 我們將用以下範例展示 "is" 和 "==" 的差異 # 因為 first_fruits_list 內容等於 second_fruits_list,故以下比較將回傳真值 assert first_fruits_list == second_fruits_list
"""恆等運算子 @詳見: https://www.w3schools.com/python/python_operators.asp 恆等運算子用途為比較物件,不僅是比較物件的內容,而是會更進一步比較到物件的記憶體位址 """ def test_identity_operators(): """恆等運算子""" # 讓我們使用以下的串列來說明恆等運算子 first_fruits_list = ["apple", "banana"] second_fruits_list = ["apple", "banana"] third_fruits_list = first_fruits_list # 是(is) # 比對兩個變數,若這兩個變數是相同的物件,則回傳真值 # 範例: # first_fruits_list 和 third_fruits_list 是相同的物件 assert first_fruits_list is third_fruits_list # 不是(is not) # 比對兩個變數,若這兩個變數不是相同的物件,則回傳真值 # 範例: # 雖然 first_fruits_list 和 second_fruits_list 有著相同的內容,但他們不是相同的物件 assert first_fruits_list is not second_fruits_list # 我們將用以下範例展示 "is" 和 "==" 的差異 # 因為 first_fruits_list 內容等於 second_fruits_list,故以下比較將回傳真值 assert first_fruits_list == second_fruits_list
zh
0.973701
恆等運算子 @詳見: https://www.w3schools.com/python/python_operators.asp 恆等運算子用途為比較物件,不僅是比較物件的內容,而是會更進一步比較到物件的記憶體位址 恆等運算子 # 讓我們使用以下的串列來說明恆等運算子 # 是(is) # 比對兩個變數,若這兩個變數是相同的物件,則回傳真值 # 範例: # first_fruits_list 和 third_fruits_list 是相同的物件 # 不是(is not) # 比對兩個變數,若這兩個變數不是相同的物件,則回傳真值 # 範例: # 雖然 first_fruits_list 和 second_fruits_list 有著相同的內容,但他們不是相同的物件 # 我們將用以下範例展示 "is" 和 "==" 的差異 # 因為 first_fruits_list 內容等於 second_fruits_list,故以下比較將回傳真值
4.453651
4
Create_PPI_preview.py
diogo1790team/inphinity_DM
1
6623686
<reponame>diogo1790team/inphinity_DM # -*- coding: utf-8 -*- """ Created on Fri May 4 08:27:54 2018 @author: Diogo """ from objects_new.Couples_new import * from objects_new.Proteins_new import * from objects_new.Protein_dom_new import * from objects_new.DDI_interactions_DB_new import * from objects_new.PPI_preview_new import * import time listasd = DDI_interaction_DB.get_DDI_interact_db_id_by_id_domains(10165, 10165) #qty_val = PPI_preview.get_number_ppi_score_by_bact_phage_prots(1977507, 27085575) def calcule_score_DDI(list_scores_ddi): #calcule the DDI score iPFAM, 3DID and ME have the maximum score ->9 score_ddi = 0 type_score = 0 if 1 in list_scores_ddi or 2 in list_scores_ddi: score_ddi = 9 type_score = 1 elif 3 in list_scores_ddi: score_ddi = 9 type_score = 2 else: score_ddi = len(list_scores_ddi) type_score = 3 return score_ddi, type_score def get_couples_NCBI_phagesDB(): #Get all couples from NCBI and Phages DB list_couples = Couple.get_all_couples_by_type_level_source(1, 4, 1) list_couples = list_couples + Couple.get_all_couples_by_type_level_source(1, 4, 2) list_couples = list_couples + Couple.get_all_couples_by_type_level_source(0, 4, 4) return list_couples def get_couples_Greg(): #Get all couples from Greg list_couples = Couple.get_all_couples_by_type_level_source(1, 4, 3) list_couples = list_couples + Couple.get_all_couples_by_type_level_source(0, 4, 3) return list_couples list_couples = get_couples_NCBI_phagesDB() print(len(list_couples)) print("qwqwqwqwqwqw") #id_couple = list_couples[0].id_couple auxaa = 0 for couple in list_couples: if couple.id_couple > 34943: print(couple) #for each couple list_prot_bact = Protein.get_all_Proteins_with_domains_by_organism_id(couple.fk_bacteria) list_prot_phage = Protein.get_all_Proteins_with_domains_by_organism_id(couple.fk_phage) print("It has {0:d} proteins for the bacterium".format(len(list_prot_bact))) print("It has {0:d} proteins for the Phages".format(len(list_prot_phage))) qty_ppi = PPI_preview.get_ppi_preview_scores_grouped_by_couple_id(couple.id_couple) aux_value = 0 print("Quantity of PPI {0}".format(len(qty_ppi))) if len(qty_ppi) == 0: #for all prots in bact combine with those of the phage for prot_bact in list_prot_bact: #get all domains by protein id list_domain_id_prot_Bact = ProteinDom.get_all_protein_domain_by_protein_id(prot_bact.id_protein) #for all proteins in phage for prot_phage in list_prot_phage: #get all domains by protein id list_domain_id_prot_phage = ProteinDom.get_all_protein_domain_by_protein_id(prot_phage.id_protein) #combiner tous les DDI et faire les insérer dans le tableau PPI preview for dom_bact in list_domain_id_prot_Bact: for dom_phage in list_domain_id_prot_phage: liste_scores_ddi = DDI_interaction_DB.get_DDI_interact_db_id_by_id_domains(dom_bact.Fk_id_domain, dom_phage.Fk_id_domain) if len(liste_scores_ddi) > 0: #print(couple) #print(aux_value) score_ddi, type_score = calcule_score_DDI(liste_scores_ddi) ppi_prev_obj = PPI_preview(score_ppi_prev = score_ddi, type_ppi_prev = type_score, fk_couple = couple.id_couple, fk_prot_bact = prot_bact.id_protein, fk_prot_phage = prot_phage.id_protein) ppi_prev_obj.create_ppi_preview() auxaa += 1 if auxaa %100 == 0: time.sleep(5) print(ppi_prev_obj) aux_value += 1 time.sleep(3) print(aux_value)
# -*- coding: utf-8 -*- """ Created on Fri May 4 08:27:54 2018 @author: Diogo """ from objects_new.Couples_new import * from objects_new.Proteins_new import * from objects_new.Protein_dom_new import * from objects_new.DDI_interactions_DB_new import * from objects_new.PPI_preview_new import * import time listasd = DDI_interaction_DB.get_DDI_interact_db_id_by_id_domains(10165, 10165) #qty_val = PPI_preview.get_number_ppi_score_by_bact_phage_prots(1977507, 27085575) def calcule_score_DDI(list_scores_ddi): #calcule the DDI score iPFAM, 3DID and ME have the maximum score ->9 score_ddi = 0 type_score = 0 if 1 in list_scores_ddi or 2 in list_scores_ddi: score_ddi = 9 type_score = 1 elif 3 in list_scores_ddi: score_ddi = 9 type_score = 2 else: score_ddi = len(list_scores_ddi) type_score = 3 return score_ddi, type_score def get_couples_NCBI_phagesDB(): #Get all couples from NCBI and Phages DB list_couples = Couple.get_all_couples_by_type_level_source(1, 4, 1) list_couples = list_couples + Couple.get_all_couples_by_type_level_source(1, 4, 2) list_couples = list_couples + Couple.get_all_couples_by_type_level_source(0, 4, 4) return list_couples def get_couples_Greg(): #Get all couples from Greg list_couples = Couple.get_all_couples_by_type_level_source(1, 4, 3) list_couples = list_couples + Couple.get_all_couples_by_type_level_source(0, 4, 3) return list_couples list_couples = get_couples_NCBI_phagesDB() print(len(list_couples)) print("qwqwqwqwqwqw") #id_couple = list_couples[0].id_couple auxaa = 0 for couple in list_couples: if couple.id_couple > 34943: print(couple) #for each couple list_prot_bact = Protein.get_all_Proteins_with_domains_by_organism_id(couple.fk_bacteria) list_prot_phage = Protein.get_all_Proteins_with_domains_by_organism_id(couple.fk_phage) print("It has {0:d} proteins for the bacterium".format(len(list_prot_bact))) print("It has {0:d} proteins for the Phages".format(len(list_prot_phage))) qty_ppi = PPI_preview.get_ppi_preview_scores_grouped_by_couple_id(couple.id_couple) aux_value = 0 print("Quantity of PPI {0}".format(len(qty_ppi))) if len(qty_ppi) == 0: #for all prots in bact combine with those of the phage for prot_bact in list_prot_bact: #get all domains by protein id list_domain_id_prot_Bact = ProteinDom.get_all_protein_domain_by_protein_id(prot_bact.id_protein) #for all proteins in phage for prot_phage in list_prot_phage: #get all domains by protein id list_domain_id_prot_phage = ProteinDom.get_all_protein_domain_by_protein_id(prot_phage.id_protein) #combiner tous les DDI et faire les insérer dans le tableau PPI preview for dom_bact in list_domain_id_prot_Bact: for dom_phage in list_domain_id_prot_phage: liste_scores_ddi = DDI_interaction_DB.get_DDI_interact_db_id_by_id_domains(dom_bact.Fk_id_domain, dom_phage.Fk_id_domain) if len(liste_scores_ddi) > 0: #print(couple) #print(aux_value) score_ddi, type_score = calcule_score_DDI(liste_scores_ddi) ppi_prev_obj = PPI_preview(score_ppi_prev = score_ddi, type_ppi_prev = type_score, fk_couple = couple.id_couple, fk_prot_bact = prot_bact.id_protein, fk_prot_phage = prot_phage.id_protein) ppi_prev_obj.create_ppi_preview() auxaa += 1 if auxaa %100 == 0: time.sleep(5) print(ppi_prev_obj) aux_value += 1 time.sleep(3) print(aux_value)
en
0.596666
# -*- coding: utf-8 -*- Created on Fri May 4 08:27:54 2018 @author: Diogo #qty_val = PPI_preview.get_number_ppi_score_by_bact_phage_prots(1977507, 27085575) #calcule the DDI score iPFAM, 3DID and ME have the maximum score ->9 #Get all couples from NCBI and Phages DB #Get all couples from Greg #id_couple = list_couples[0].id_couple #for each couple #for all prots in bact combine with those of the phage #get all domains by protein id #for all proteins in phage #get all domains by protein id #combiner tous les DDI et faire les insérer dans le tableau PPI preview #print(couple) #print(aux_value)
1.95412
2
chiki_jinja.py
endsh/chiki-jinja
0
6623687
# coding: utf-8 import re import json import traceback from datetime import datetime from flask import current_app, get_flashed_messages from jinja2 import Markup from xml.sax.saxutils import escape from chiki_base import time2best as _time2best, is_ajax, url_with_user, markup __all__ = [ 'markup', 'markupper', 'first_error', 'text2html', 'JinjaManager', 'init_jinja', ] regex = re.compile( r'((?:http|ftp)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+' r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' r'localhost|' r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' r'(?::\d+)?' r'(?:[a-zA-Z0-9\-\/._~%!$&()*+]+)?' r'(?:\?[a-zA-Z0-9&%=.\-!@^*+-_]+)?)', re.IGNORECASE) def markupper(func): def wrapper(*args, **kwargs): return markup(func(*args, **kwargs)) return wrapper def first_error(form): if form: for field in form: if field.errors: return field.errors[0] def replace_link(link): if link.startswith('http://') or link.startswith('https://'): return '<a class="link" href="%s">%s</a>' % ( escape(link), escape(link)) return escape(link) def text2html(text): try: out = [''] for line in text.splitlines(): if not line.strip(): out.append('') continue texts = [replace_link(x) for x in regex.split(line)] out[-1] += ''.join(texts) + '<br>' return ''.join(u'<p>%s</p>' % x for x in filter( lambda x: x.strip, out)) except: traceback.print_exc() return escape(text) class JinjaManager(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app): app.jinja_env.filters.update(self.filters) app.context_processor(self.context_processor) @property def filters(self): return dict( time2best=self.time2best, time2date=self.time2date, line2br=self.line2br_filter, text2html=self.text2html_filter, kform=self.kform_filter, kfield=self.kfield_filter, kform_inline=self.kform_inline_filter, kfield_inline=self.kfield_inline_filter, alert=self.alert_filter, rmb=self.rmb_filter, rmb2=self.rmb2_filter, rmb3=self.rmb3_filter, best_num=self.best_num_filter, json=json.dumps, cdn=self.cdn_filter, repr=self.repr, url_with_user=url_with_user, show_hex=self.show_hex, ) def context_processor(self): return dict( SITE_NAME=current_app.config.get('SITE_NAME'), VERSION=current_app.config.get('VERSION'), YEAR=datetime.now().year, alert=self.alert_filter, is_ajax=is_ajax, current_app=current_app, str=str, repr=self.repr, callable=callable, len=len, ) def line2br_filter(self, text): return markup(escape(text).replace('\n', '<br>')) def text2html_filter(self, text): return markup(text2html(text)) def kform_filter(self, form, **kwargs): out = [] for field in form: out.append(self.kfield_filter(field, **kwargs)) return markup(''.join(out)) def kfield_filter(self, field, **kwargs): label = kwargs.pop('label', 3) grid = kwargs.pop('grid', 'sm') _class = kwargs.pop('_class', 'form-group') error = kwargs.pop('error', True) label_class = 'control-label col-%s-%d' % (grid, label) out = [] if field.type == 'Label': out.append(field(class_='form-title')) elif field.type not in['CSRFTokenField', 'HiddenField']: out.append('<div class="%s">' % _class) out.append(field.label(class_=label_class)) if field.type == 'KRadioField': field_div = '<div class="col-%s-%d radio-line">' % ( grid, (12 - label)) out.append(field_div) out.append(field( sub_class='radio-inline', class_="radio-line")) elif field.type == 'KCheckboxField': field_div = '<div class="col-%s-%d checkbox-line">' % ( grid, (12 - label)) out.append(field_div) out.append(field( sub_class='checkbox-inline', class_="checkbox-line")) else: field_div = '<div class="col-%s-%d">' % (grid, (12 - label)) out.append(field_div) if hasattr(field, 'addon'): out.append('<div class="input-group">') out.append(field( class_='form-control', data_label=field.label.text, placeholder=field.description or '')) out.append('<span class="input-group-addon">%s</span>' % field.addon) out.append('</div>') else: out.append(field( class_='form-control', data_label=field.label.text, placeholder=field.description or '')) if error and field.errors: out.append('<div class="error-msg">%s</div>' % field.errors[0]) out.append('</div><div class="clearfix"></div></div>') else: out.append(field()) return markup(''.join(out)) def kform_inline_filter(self, form): out = [] for field in form: out.append(self.kfield_inline_filter(field)) return markup(''.join(out)) def kfield_inline_filter(self, field, **kwargs): out = [] if field.type in ['CSRFTokenField', 'HiddenField']: out.append(field(**kwargs)) else: out.append('<div class="form-group">') if field.type == 'BooleanField': out.append('<div class="checkbox"><label>%s %s</label></div>' % (field(**kwargs), field.label.text)) else: kwargs.setdefault('class_', 'form-control') kwargs.setdefault('data_label', field.label.text) kwargs.setdefault('placeholder', field.label.text) out.append(field(**kwargs)) out.append('</div>') return markup(''.join(out)) def alert_msg(self, msg, style='danger'): return markup( '<div class="alert alert-%s"><button class="close" ' 'type="button" data-dismiss="alert" aria-hidden="true">&times;' '</button><span>%s</span></div>' % (style, msg)) def alert_filter(self, form=None, style='danger'): error = first_error(form) if error: return self.alert_msg(error, style) messages = get_flashed_messages(with_categories=True) msg = 'Please log in to access this page.' if messages and messages[-1][1] != msg: return self.alert_msg(messages[-1][1], messages[-1][0] or 'danger') return '' def rmb_filter(self, money): return '%.2f' % money def rmb2_filter(self, money): return '%.2f' % (money / 100.0) def rmb3_filter(self, money): d = float('%.2f' % (money / 100.0)) return str([str(d), int(d)][int(d) == d]) def best_num_filter(self, num): if not num: return 0 if num < 1000: return num if num < 100000: return '%.1fk' % (num / 1000.0) if num < 1000000: return '%.1fw' % (num / 10000.0) return '%dw' % (num / 10000) def time2best(self, input): return _time2best(input) def time2date(self, input): return str(input)[:10] def cdn_filter(self, url, width, height): url = current_app.config.get('LAZY_IMAGE', '') return url + ('@%sw_%sh_1e_1c_95Q.png' % (width, height)) def show_hex(self, input): return ''.join(["\\x%s" % i.encode('hex') for i in input]) def repr(self, text): res = repr(unicode(text)) return unicode(res[2:-1]) def init_jinja(app): jinja = JinjaManager() jinja.init_app(app)
# coding: utf-8 import re import json import traceback from datetime import datetime from flask import current_app, get_flashed_messages from jinja2 import Markup from xml.sax.saxutils import escape from chiki_base import time2best as _time2best, is_ajax, url_with_user, markup __all__ = [ 'markup', 'markupper', 'first_error', 'text2html', 'JinjaManager', 'init_jinja', ] regex = re.compile( r'((?:http|ftp)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+' r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' r'localhost|' r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' r'(?::\d+)?' r'(?:[a-zA-Z0-9\-\/._~%!$&()*+]+)?' r'(?:\?[a-zA-Z0-9&%=.\-!@^*+-_]+)?)', re.IGNORECASE) def markupper(func): def wrapper(*args, **kwargs): return markup(func(*args, **kwargs)) return wrapper def first_error(form): if form: for field in form: if field.errors: return field.errors[0] def replace_link(link): if link.startswith('http://') or link.startswith('https://'): return '<a class="link" href="%s">%s</a>' % ( escape(link), escape(link)) return escape(link) def text2html(text): try: out = [''] for line in text.splitlines(): if not line.strip(): out.append('') continue texts = [replace_link(x) for x in regex.split(line)] out[-1] += ''.join(texts) + '<br>' return ''.join(u'<p>%s</p>' % x for x in filter( lambda x: x.strip, out)) except: traceback.print_exc() return escape(text) class JinjaManager(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app): app.jinja_env.filters.update(self.filters) app.context_processor(self.context_processor) @property def filters(self): return dict( time2best=self.time2best, time2date=self.time2date, line2br=self.line2br_filter, text2html=self.text2html_filter, kform=self.kform_filter, kfield=self.kfield_filter, kform_inline=self.kform_inline_filter, kfield_inline=self.kfield_inline_filter, alert=self.alert_filter, rmb=self.rmb_filter, rmb2=self.rmb2_filter, rmb3=self.rmb3_filter, best_num=self.best_num_filter, json=json.dumps, cdn=self.cdn_filter, repr=self.repr, url_with_user=url_with_user, show_hex=self.show_hex, ) def context_processor(self): return dict( SITE_NAME=current_app.config.get('SITE_NAME'), VERSION=current_app.config.get('VERSION'), YEAR=datetime.now().year, alert=self.alert_filter, is_ajax=is_ajax, current_app=current_app, str=str, repr=self.repr, callable=callable, len=len, ) def line2br_filter(self, text): return markup(escape(text).replace('\n', '<br>')) def text2html_filter(self, text): return markup(text2html(text)) def kform_filter(self, form, **kwargs): out = [] for field in form: out.append(self.kfield_filter(field, **kwargs)) return markup(''.join(out)) def kfield_filter(self, field, **kwargs): label = kwargs.pop('label', 3) grid = kwargs.pop('grid', 'sm') _class = kwargs.pop('_class', 'form-group') error = kwargs.pop('error', True) label_class = 'control-label col-%s-%d' % (grid, label) out = [] if field.type == 'Label': out.append(field(class_='form-title')) elif field.type not in['CSRFTokenField', 'HiddenField']: out.append('<div class="%s">' % _class) out.append(field.label(class_=label_class)) if field.type == 'KRadioField': field_div = '<div class="col-%s-%d radio-line">' % ( grid, (12 - label)) out.append(field_div) out.append(field( sub_class='radio-inline', class_="radio-line")) elif field.type == 'KCheckboxField': field_div = '<div class="col-%s-%d checkbox-line">' % ( grid, (12 - label)) out.append(field_div) out.append(field( sub_class='checkbox-inline', class_="checkbox-line")) else: field_div = '<div class="col-%s-%d">' % (grid, (12 - label)) out.append(field_div) if hasattr(field, 'addon'): out.append('<div class="input-group">') out.append(field( class_='form-control', data_label=field.label.text, placeholder=field.description or '')) out.append('<span class="input-group-addon">%s</span>' % field.addon) out.append('</div>') else: out.append(field( class_='form-control', data_label=field.label.text, placeholder=field.description or '')) if error and field.errors: out.append('<div class="error-msg">%s</div>' % field.errors[0]) out.append('</div><div class="clearfix"></div></div>') else: out.append(field()) return markup(''.join(out)) def kform_inline_filter(self, form): out = [] for field in form: out.append(self.kfield_inline_filter(field)) return markup(''.join(out)) def kfield_inline_filter(self, field, **kwargs): out = [] if field.type in ['CSRFTokenField', 'HiddenField']: out.append(field(**kwargs)) else: out.append('<div class="form-group">') if field.type == 'BooleanField': out.append('<div class="checkbox"><label>%s %s</label></div>' % (field(**kwargs), field.label.text)) else: kwargs.setdefault('class_', 'form-control') kwargs.setdefault('data_label', field.label.text) kwargs.setdefault('placeholder', field.label.text) out.append(field(**kwargs)) out.append('</div>') return markup(''.join(out)) def alert_msg(self, msg, style='danger'): return markup( '<div class="alert alert-%s"><button class="close" ' 'type="button" data-dismiss="alert" aria-hidden="true">&times;' '</button><span>%s</span></div>' % (style, msg)) def alert_filter(self, form=None, style='danger'): error = first_error(form) if error: return self.alert_msg(error, style) messages = get_flashed_messages(with_categories=True) msg = 'Please log in to access this page.' if messages and messages[-1][1] != msg: return self.alert_msg(messages[-1][1], messages[-1][0] or 'danger') return '' def rmb_filter(self, money): return '%.2f' % money def rmb2_filter(self, money): return '%.2f' % (money / 100.0) def rmb3_filter(self, money): d = float('%.2f' % (money / 100.0)) return str([str(d), int(d)][int(d) == d]) def best_num_filter(self, num): if not num: return 0 if num < 1000: return num if num < 100000: return '%.1fk' % (num / 1000.0) if num < 1000000: return '%.1fw' % (num / 10000.0) return '%dw' % (num / 10000) def time2best(self, input): return _time2best(input) def time2date(self, input): return str(input)[:10] def cdn_filter(self, url, width, height): url = current_app.config.get('LAZY_IMAGE', '') return url + ('@%sw_%sh_1e_1c_95Q.png' % (width, height)) def show_hex(self, input): return ''.join(["\\x%s" % i.encode('hex') for i in input]) def repr(self, text): res = repr(unicode(text)) return unicode(res[2:-1]) def init_jinja(app): jinja = JinjaManager() jinja.init_app(app)
en
0.833554
# coding: utf-8
2.234648
2
setup.py
MarkCiampa/HippocampusSegmentationMRI
16
6623688
<reponame>MarkCiampa/HippocampusSegmentationMRI<filename>setup.py import setuptools with open("README.md", "r") as fh: long_description = fh.read() with open('requirements.txt') as f: required = f.read().splitlines() setuptools.setup( name="hippo-vnet", version="0.0.1", author="<NAME>", author_email="<EMAIL>", description="Hippocampus Segmentation from MRI using 3D Convolutional Neural Networks in PyTorch", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Nicolik/HippocampusSegmentationMRI", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.7', test_suite='tests', install_requires=required, )
import setuptools with open("README.md", "r") as fh: long_description = fh.read() with open('requirements.txt') as f: required = f.read().splitlines() setuptools.setup( name="hippo-vnet", version="0.0.1", author="<NAME>", author_email="<EMAIL>", description="Hippocampus Segmentation from MRI using 3D Convolutional Neural Networks in PyTorch", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Nicolik/HippocampusSegmentationMRI", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.7', test_suite='tests', install_requires=required, )
none
1
1.547833
2
cs15211/ValidParenthesisString.py
JulyKikuAkita/PythonPrac
1
6623689
<reponame>JulyKikuAkita/PythonPrac __source__ = 'https://leetcode.com/problems/valid-parenthesis-string/description/' # Time: O() # Space: O() # # Description: Leetcode # 678. Valid Parenthesis String # # Given a string containing only three types of characters: '(', ')' and '*', # write a function to check whether this string is valid. # We define the validity of a string by these rules: # # Any left parenthesis '(' must have a corresponding right parenthesis ')'. # Any right parenthesis ')' must have a corresponding left parenthesis '('. # Left parenthesis '(' must go before the corresponding right parenthesis ')'. # '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. # An empty string is also valid. # Example 1: # Input: "()" # Output: True # Example 2: # Input: "(*)" # Output: True # Example 3: # Input: "(*))" # Output: True # Note: # The string size will be in the range [1, 100]. # # Companies # Alibaba # Related Topics # String # import unittest # Thought: # The number of open parenthesis is in a range [cmin, cmax] # cmax counts the maximum open parenthesis. # cmin counts the minimum open parenthesis. # The string is valid for 2 condition: # # cmax will never be negative. # cmin is 0 at the end. # #20ms 100% class Solution(object): def checkValidString(self, s): """ :type s: str :rtype: bool """ cmin = cmax = 0 for i in s: if i == '(': cmax += 1 cmin += 1 if i == ')': cmax -= 1 cmin = max(cmin - 1, 0) if i == '*': cmax += 1 cmin = max(cmin - 1, 0) if cmax < 0: return False return cmin == 0 class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' # Thought: https://leetcode.com/problems/valid-parenthesis-string/solution/ # 2ms 100% public class Solution { public boolean checkValidString(String s) { int low = 0; int high = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { low++; high++; } else if (s.charAt(i) == ')') { if (low > 0) { low--; } high--; } else { if (low > 0) { low--; } high++; } if (high < 0) { return false; } } return low == 0; } } # Greedy # 2ms 100% class Solution { public boolean checkValidString(String s) { int lo = 0, hi = 0; for (char c: s.toCharArray()) { lo += c == '(' ? 1 : -1; hi += c != ')' ? 1 : -1; if (hi < 0) break; lo = Math.max(lo, 0); } return lo == 0; } } '''
__source__ = 'https://leetcode.com/problems/valid-parenthesis-string/description/' # Time: O() # Space: O() # # Description: Leetcode # 678. Valid Parenthesis String # # Given a string containing only three types of characters: '(', ')' and '*', # write a function to check whether this string is valid. # We define the validity of a string by these rules: # # Any left parenthesis '(' must have a corresponding right parenthesis ')'. # Any right parenthesis ')' must have a corresponding left parenthesis '('. # Left parenthesis '(' must go before the corresponding right parenthesis ')'. # '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. # An empty string is also valid. # Example 1: # Input: "()" # Output: True # Example 2: # Input: "(*)" # Output: True # Example 3: # Input: "(*))" # Output: True # Note: # The string size will be in the range [1, 100]. # # Companies # Alibaba # Related Topics # String # import unittest # Thought: # The number of open parenthesis is in a range [cmin, cmax] # cmax counts the maximum open parenthesis. # cmin counts the minimum open parenthesis. # The string is valid for 2 condition: # # cmax will never be negative. # cmin is 0 at the end. # #20ms 100% class Solution(object): def checkValidString(self, s): """ :type s: str :rtype: bool """ cmin = cmax = 0 for i in s: if i == '(': cmax += 1 cmin += 1 if i == ')': cmax -= 1 cmin = max(cmin - 1, 0) if i == '*': cmax += 1 cmin = max(cmin - 1, 0) if cmax < 0: return False return cmin == 0 class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' # Thought: https://leetcode.com/problems/valid-parenthesis-string/solution/ # 2ms 100% public class Solution { public boolean checkValidString(String s) { int low = 0; int high = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { low++; high++; } else if (s.charAt(i) == ')') { if (low > 0) { low--; } high--; } else { if (low > 0) { low--; } high++; } if (high < 0) { return false; } } return low == 0; } } # Greedy # 2ms 100% class Solution { public boolean checkValidString(String s) { int lo = 0, hi = 0; for (char c: s.toCharArray()) { lo += c == '(' ? 1 : -1; hi += c != ')' ? 1 : -1; if (hi < 0) break; lo = Math.max(lo, 0); } return lo == 0; } } '''
en
0.516136
# Time: O() # Space: O() # # Description: Leetcode # 678. Valid Parenthesis String # # Given a string containing only three types of characters: '(', ')' and '*', # write a function to check whether this string is valid. # We define the validity of a string by these rules: # # Any left parenthesis '(' must have a corresponding right parenthesis ')'. # Any right parenthesis ')' must have a corresponding left parenthesis '('. # Left parenthesis '(' must go before the corresponding right parenthesis ')'. # '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. # An empty string is also valid. # Example 1: # Input: "()" # Output: True # Example 2: # Input: "(*)" # Output: True # Example 3: # Input: "(*))" # Output: True # Note: # The string size will be in the range [1, 100]. # # Companies # Alibaba # Related Topics # String # # Thought: # The number of open parenthesis is in a range [cmin, cmax] # cmax counts the maximum open parenthesis. # cmin counts the minimum open parenthesis. # The string is valid for 2 condition: # # cmax will never be negative. # cmin is 0 at the end. # #20ms 100% :type s: str :rtype: bool # Thought: https://leetcode.com/problems/valid-parenthesis-string/solution/ # 2ms 100% public class Solution { public boolean checkValidString(String s) { int low = 0; int high = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { low++; high++; } else if (s.charAt(i) == ')') { if (low > 0) { low--; } high--; } else { if (low > 0) { low--; } high++; } if (high < 0) { return false; } } return low == 0; } } # Greedy # 2ms 100% class Solution { public boolean checkValidString(String s) { int lo = 0, hi = 0; for (char c: s.toCharArray()) { lo += c == '(' ? 1 : -1; hi += c != ')' ? 1 : -1; if (hi < 0) break; lo = Math.max(lo, 0); } return lo == 0; } }
3.703618
4
tests/persistence/person_dao_spark_test.py
pydev-bootcamp/python-etl
0
6623690
""" Unit tests for PersonDao """ from datetime import datetime import os from os.path import dirname, abspath, join from pytest import raises from tempfile import mkstemp from typing import List, Optional, TextIO from textwrap import dedent from manage_accounts.model.person import Person from manage_accounts.persistence.person_dao_spark import PersonDaoSpark # from pprint import pprint # pretty-print Python data structures dao: PersonDaoSpark temp_file: Optional[TextIO] temp_file_handle: int temp_file_path: str data_file_path: str = join(dirname(abspath(__file__)), "person_dao_spark_test.jsonl") def setup_function() -> None: # create temp file global temp_file_handle, temp_file_path, temp_file temp_file_handle, temp_file_path = mkstemp(text=True) temp_file = open(temp_file_path, "w") def teardown_function() -> None: global dao, temp_file_handle, temp_file if dao: dao.close() if temp_file: # else file was closed in init_test_data() temp_file.close() if temp_file_handle: # remove temp file os.close(temp_file_handle) os.remove(temp_file_path) def init_test_data(test_data: str) -> None: global temp_file temp_file.write(dedent(test_data)) temp_file.close() temp_file = None def test_find_all_args_supplied() -> None: global dao dao = PersonDaoSpark(data_file_path) # dao.df.printSchema() results = [person for person in dao.find( "Vivien", "Theodore", "Thomas")] assert 1 == len(results) p = results[0] assert isinstance(p, Person) assert (1, "Vivien", "Theodore", "Thomas") == \ (p.id, p.given, p.middle, p.family) assert p.created_time < datetime.utcnow() def test_find_given_arg_only() -> None: global dao dao = PersonDaoSpark(data_file_path) results = [person for person in dao.find("Elizabeth")] assert 1 == len(results) p = results[0] assert isinstance(p, Person) assert (2, "Elizabeth", "", "Blackwell") == \ (p.id, p.given, p.middle, p.family) assert p.created_time < datetime.utcnow() def test_find_given_arg_only_two_results() -> None: global dao dao = PersonDaoSpark(data_file_path) results = [person for person in dao.find("Thomas")] assert 2 == len(results) sorted(results, key=lambda person: person.id) assert [(p.id, p.given, p.middle, p.family) for p in results] == \ [(4, "Thomas", "", "Addison"), (5, "Thomas", "", "Sydenham")] def test_find_several_queries() -> None: global dao dao = PersonDaoSpark(data_file_path) # next(iter(...)) performs one iteration of the Iterable argument p: Person = next(iter(dao.find("Vivien", "Theodore", "Thomas"))) assert ("Vivien", "Theodore", "Thomas") == (p.given, p.middle, p.family) p = next(iter(dao.find("Elizabeth", family="Blackwell"))) assert ("Elizabeth", "", "Blackwell") == (p.given, p.middle, p.family) p = next(iter(dao.find("Hippocrates"))) assert ("Hippocrates", "", "") == (p.given, p.middle, p.family) def test_find_person_not_present() -> None: global dao dao = PersonDaoSpark(data_file_path) results: List[Person] = [person for person in dao.find("NotThere")] assert 0 == len(results) def test_find_no_args_raises_exception() -> None: global dao dao = PersonDaoSpark(data_file_path) with raises(ValueError, match=r"arguments.*empty"): next(iter(dao.find())) # find() is s generator function, so it won't be executed unless # it's used for iteration def test_find_by_id_success() -> None: global dao dao = PersonDaoSpark(data_file_path) person: Person = dao.find_by_id(3) assert "Hippocrates" == person.given def test_find_by_id_not_present() -> None: global dao dao = PersonDaoSpark(data_file_path) assert dao.find_by_id(0) is None def test_find_by_id_json() -> None: global dao init_test_data(""" {"id": 1, "given": "Vivien", "middle": "Theodore", "family": "Thomas", "created_time": 1576109811} {"id": 2, "given": "Hippocrates", "created_time": 1576109813} {"id": 3, "given": "Thomas", "family": "Addison", "created_time": 1576109814} """) dao = PersonDaoSpark(temp_file_path) person: Person = dao.find_by_id(2) assert "Hippocrates" == person.given def test_find_by_id_csv() -> None: global dao init_test_data("""\ 1,Vivien,Theodore,Thomas,1576109811 2,Hippocrates,,1576109812 3,Thomas,,Addison,1576109813 """) dao = PersonDaoSpark(temp_file_path, "csv") person: Person = dao.find_by_id(2) assert "Hippocrates" == person.given def test_find_by_id_duplicate_id_raises_exception() -> None: global dao init_test_data("""\ {"id": 1, "given": "Vivien", "middle": "Theodore", "family": "Thomas", "created_time": 1576109811} {"id": 2, "given": "Hippocrates", "created_time": 1576109813} {"id": 2, "given": "Thomas", "family": "Addison", "created_time": 1576109814} """) dao = PersonDaoSpark(temp_file_path) with raises(ValueError, match=r"duplicate.*([Ii][Dd]|[Kk]ey)"): dao.find_by_id(2)
""" Unit tests for PersonDao """ from datetime import datetime import os from os.path import dirname, abspath, join from pytest import raises from tempfile import mkstemp from typing import List, Optional, TextIO from textwrap import dedent from manage_accounts.model.person import Person from manage_accounts.persistence.person_dao_spark import PersonDaoSpark # from pprint import pprint # pretty-print Python data structures dao: PersonDaoSpark temp_file: Optional[TextIO] temp_file_handle: int temp_file_path: str data_file_path: str = join(dirname(abspath(__file__)), "person_dao_spark_test.jsonl") def setup_function() -> None: # create temp file global temp_file_handle, temp_file_path, temp_file temp_file_handle, temp_file_path = mkstemp(text=True) temp_file = open(temp_file_path, "w") def teardown_function() -> None: global dao, temp_file_handle, temp_file if dao: dao.close() if temp_file: # else file was closed in init_test_data() temp_file.close() if temp_file_handle: # remove temp file os.close(temp_file_handle) os.remove(temp_file_path) def init_test_data(test_data: str) -> None: global temp_file temp_file.write(dedent(test_data)) temp_file.close() temp_file = None def test_find_all_args_supplied() -> None: global dao dao = PersonDaoSpark(data_file_path) # dao.df.printSchema() results = [person for person in dao.find( "Vivien", "Theodore", "Thomas")] assert 1 == len(results) p = results[0] assert isinstance(p, Person) assert (1, "Vivien", "Theodore", "Thomas") == \ (p.id, p.given, p.middle, p.family) assert p.created_time < datetime.utcnow() def test_find_given_arg_only() -> None: global dao dao = PersonDaoSpark(data_file_path) results = [person for person in dao.find("Elizabeth")] assert 1 == len(results) p = results[0] assert isinstance(p, Person) assert (2, "Elizabeth", "", "Blackwell") == \ (p.id, p.given, p.middle, p.family) assert p.created_time < datetime.utcnow() def test_find_given_arg_only_two_results() -> None: global dao dao = PersonDaoSpark(data_file_path) results = [person for person in dao.find("Thomas")] assert 2 == len(results) sorted(results, key=lambda person: person.id) assert [(p.id, p.given, p.middle, p.family) for p in results] == \ [(4, "Thomas", "", "Addison"), (5, "Thomas", "", "Sydenham")] def test_find_several_queries() -> None: global dao dao = PersonDaoSpark(data_file_path) # next(iter(...)) performs one iteration of the Iterable argument p: Person = next(iter(dao.find("Vivien", "Theodore", "Thomas"))) assert ("Vivien", "Theodore", "Thomas") == (p.given, p.middle, p.family) p = next(iter(dao.find("Elizabeth", family="Blackwell"))) assert ("Elizabeth", "", "Blackwell") == (p.given, p.middle, p.family) p = next(iter(dao.find("Hippocrates"))) assert ("Hippocrates", "", "") == (p.given, p.middle, p.family) def test_find_person_not_present() -> None: global dao dao = PersonDaoSpark(data_file_path) results: List[Person] = [person for person in dao.find("NotThere")] assert 0 == len(results) def test_find_no_args_raises_exception() -> None: global dao dao = PersonDaoSpark(data_file_path) with raises(ValueError, match=r"arguments.*empty"): next(iter(dao.find())) # find() is s generator function, so it won't be executed unless # it's used for iteration def test_find_by_id_success() -> None: global dao dao = PersonDaoSpark(data_file_path) person: Person = dao.find_by_id(3) assert "Hippocrates" == person.given def test_find_by_id_not_present() -> None: global dao dao = PersonDaoSpark(data_file_path) assert dao.find_by_id(0) is None def test_find_by_id_json() -> None: global dao init_test_data(""" {"id": 1, "given": "Vivien", "middle": "Theodore", "family": "Thomas", "created_time": 1576109811} {"id": 2, "given": "Hippocrates", "created_time": 1576109813} {"id": 3, "given": "Thomas", "family": "Addison", "created_time": 1576109814} """) dao = PersonDaoSpark(temp_file_path) person: Person = dao.find_by_id(2) assert "Hippocrates" == person.given def test_find_by_id_csv() -> None: global dao init_test_data("""\ 1,Vivien,Theodore,Thomas,1576109811 2,Hippocrates,,1576109812 3,Thomas,,Addison,1576109813 """) dao = PersonDaoSpark(temp_file_path, "csv") person: Person = dao.find_by_id(2) assert "Hippocrates" == person.given def test_find_by_id_duplicate_id_raises_exception() -> None: global dao init_test_data("""\ {"id": 1, "given": "Vivien", "middle": "Theodore", "family": "Thomas", "created_time": 1576109811} {"id": 2, "given": "Hippocrates", "created_time": 1576109813} {"id": 2, "given": "Thomas", "family": "Addison", "created_time": 1576109814} """) dao = PersonDaoSpark(temp_file_path) with raises(ValueError, match=r"duplicate.*([Ii][Dd]|[Kk]ey)"): dao.find_by_id(2)
en
0.653026
Unit tests for PersonDao # from pprint import pprint # pretty-print Python data structures # create temp file # else file was closed in init_test_data() # remove temp file # dao.df.printSchema() # next(iter(...)) performs one iteration of the Iterable argument # find() is s generator function, so it won't be executed unless # it's used for iteration {"id": 1, "given": "Vivien", "middle": "Theodore", "family": "Thomas", "created_time": 1576109811} {"id": 2, "given": "Hippocrates", "created_time": 1576109813} {"id": 3, "given": "Thomas", "family": "Addison", "created_time": 1576109814} \ 1,Vivien,Theodore,Thomas,1576109811 2,Hippocrates,,1576109812 3,Thomas,,Addison,1576109813 \ {"id": 1, "given": "Vivien", "middle": "Theodore", "family": "Thomas", "created_time": 1576109811} {"id": 2, "given": "Hippocrates", "created_time": 1576109813} {"id": 2, "given": "Thomas", "family": "Addison", "created_time": 1576109814}
2.384758
2
open_alchemy/schemas/validation/helpers/__init__.py
rgreinho/OpenAlchemy
0
6623691
<filename>open_alchemy/schemas/validation/helpers/__init__.py """Helpers for validation.""" from . import properties from . import value
<filename>open_alchemy/schemas/validation/helpers/__init__.py """Helpers for validation.""" from . import properties from . import value
en
0.603841
Helpers for validation.
1.280541
1
project/tests/test_news_filter.py
anton-svechnikau/feedya
0
6623692
import news_filter from tests.factories import NewsItemEntityFactory from exceptions import NewsAlreadyExists class TestNewsFilter: def test_mark_late_news__new_entity__fresh_news(self, mocker): entity = NewsItemEntityFactory() mock = mocker.patch('news_filter.db.create_news') mock.return_value = entity marked_entity = news_filter._mark_late_news(entity) assert not marked_entity.late def test_mark_late_news__new_entity__late_news(self, mocker): entity = NewsItemEntityFactory(title='qwe') mock = mocker.patch('news_filter.db.create_news') mock.side_effect = NewsAlreadyExists marked_entity = news_filter._mark_late_news(entity) assert marked_entity.late
import news_filter from tests.factories import NewsItemEntityFactory from exceptions import NewsAlreadyExists class TestNewsFilter: def test_mark_late_news__new_entity__fresh_news(self, mocker): entity = NewsItemEntityFactory() mock = mocker.patch('news_filter.db.create_news') mock.return_value = entity marked_entity = news_filter._mark_late_news(entity) assert not marked_entity.late def test_mark_late_news__new_entity__late_news(self, mocker): entity = NewsItemEntityFactory(title='qwe') mock = mocker.patch('news_filter.db.create_news') mock.side_effect = NewsAlreadyExists marked_entity = news_filter._mark_late_news(entity) assert marked_entity.late
none
1
2.381349
2
src/vlcars/vlcars_main.py
dcarrillox/VLCars
0
6623693
<reponame>dcarrillox/VLCars<gh_stars>0 import logging import sys, os, glob import argparse from platformdirs import * import pandas as pd #from vlcars import __version__ from vlcars.local_db import * from vlcars.query_online import * from vlcars.app import * __author__ = "dcarrillox" __copyright__ = "dcarrillox" __license__ = "MIT" _logger = logging.getLogger(__name__) def parse_args(sites): parser = argparse.ArgumentParser(description='') parser.add_argument('-s', '--site', default=sites[0], const=sites[0], choices=sites, nargs='?', dest='site', help='' ) parser.add_argument('-p', '--province', default='valencia', const='valencia', nargs='?', dest='province', help='' ) parser.add_argument('-l', '--local_server', dest="server", nargs="?", default=False, const=True, help="read info from tabular file under 'data/' and run the app") parser.add_argument('--heroku', nargs="?", default=False, const=True, help="read info from tabular file under 'data/' and run the app") parser.add_argument("--sql_to_tsv", nargs="?", default=False, const=True, help="parse SQL database and write to tabular file in 'data/yy-mm-dd.txt'") args = parser.parse_args() return args def main(): SITES = sorted( ["autocasion", ] ) args = parse_args(SITES) print(args) # init local_db appname = "vlcars" appauthor = "dcarrillox" db_path = user_data_dir(appname, appauthor) os.makedirs(db_path, exist_ok=True) db_file = db_path + "/cars.db" conn = create_connection(db_file) create_table(conn) # ----------------------------------- # Check arguments and run accordingly # --heroku # parse tabular database to DataFrame and run app. Used by branch "heroku" to run app on Heroku. #args.heroku = True if args.heroku: tab_database_file = glob.glob("src/vlcars/data/*.tsv")[0] tab_database_df = pd.read_csv(tsv_file, sep="\t", header=0) run_server_heroku(tab_database_df) # --sql_to_tab # parses current SQL database to tsv in "data/yy-mm-dd.tsv" elif args.sql_to_tsv: sql_database_df = sqldb_to_dataframe(conn) # write to file tsv_out = f"src/vlcars/data/{time.strftime('%Y-%m-%d')}.tsv" sql_database_df.to_csv(tsv_out, header=True, index=False, sep="\t") # create Dash app and render results locally elif args.server: df = sqldb_to_dataframe(conn) run_server(df) # query sites online else: parsed_pages = list() if args.site == "autocasion": parsed_pages += query_online_autocasion(args.province) # # create the mock file for testing # parsed_pages = sorted(parsed_pages) # for page in parsed_pages: # print(page) # # with open("/home/dani/effidotpy/github/VLCars/tests/files/autocasion_parsed.txt", "w") as fout: # for line in parsed_pages: # line[3], line[4], line[5], line[6] = str(line[3]), str(line[4]), str(line[5]), str(line[6]) # fout.write("\t".join(line) + "\n") #----------------------------- # insert in local SQL database insert_in_database(parsed_pages, conn) if __name__ == "__main__": main()
import logging import sys, os, glob import argparse from platformdirs import * import pandas as pd #from vlcars import __version__ from vlcars.local_db import * from vlcars.query_online import * from vlcars.app import * __author__ = "dcarrillox" __copyright__ = "dcarrillox" __license__ = "MIT" _logger = logging.getLogger(__name__) def parse_args(sites): parser = argparse.ArgumentParser(description='') parser.add_argument('-s', '--site', default=sites[0], const=sites[0], choices=sites, nargs='?', dest='site', help='' ) parser.add_argument('-p', '--province', default='valencia', const='valencia', nargs='?', dest='province', help='' ) parser.add_argument('-l', '--local_server', dest="server", nargs="?", default=False, const=True, help="read info from tabular file under 'data/' and run the app") parser.add_argument('--heroku', nargs="?", default=False, const=True, help="read info from tabular file under 'data/' and run the app") parser.add_argument("--sql_to_tsv", nargs="?", default=False, const=True, help="parse SQL database and write to tabular file in 'data/yy-mm-dd.txt'") args = parser.parse_args() return args def main(): SITES = sorted( ["autocasion", ] ) args = parse_args(SITES) print(args) # init local_db appname = "vlcars" appauthor = "dcarrillox" db_path = user_data_dir(appname, appauthor) os.makedirs(db_path, exist_ok=True) db_file = db_path + "/cars.db" conn = create_connection(db_file) create_table(conn) # ----------------------------------- # Check arguments and run accordingly # --heroku # parse tabular database to DataFrame and run app. Used by branch "heroku" to run app on Heroku. #args.heroku = True if args.heroku: tab_database_file = glob.glob("src/vlcars/data/*.tsv")[0] tab_database_df = pd.read_csv(tsv_file, sep="\t", header=0) run_server_heroku(tab_database_df) # --sql_to_tab # parses current SQL database to tsv in "data/yy-mm-dd.tsv" elif args.sql_to_tsv: sql_database_df = sqldb_to_dataframe(conn) # write to file tsv_out = f"src/vlcars/data/{time.strftime('%Y-%m-%d')}.tsv" sql_database_df.to_csv(tsv_out, header=True, index=False, sep="\t") # create Dash app and render results locally elif args.server: df = sqldb_to_dataframe(conn) run_server(df) # query sites online else: parsed_pages = list() if args.site == "autocasion": parsed_pages += query_online_autocasion(args.province) # # create the mock file for testing # parsed_pages = sorted(parsed_pages) # for page in parsed_pages: # print(page) # # with open("/home/dani/effidotpy/github/VLCars/tests/files/autocasion_parsed.txt", "w") as fout: # for line in parsed_pages: # line[3], line[4], line[5], line[6] = str(line[3]), str(line[4]), str(line[5]), str(line[6]) # fout.write("\t".join(line) + "\n") #----------------------------- # insert in local SQL database insert_in_database(parsed_pages, conn) if __name__ == "__main__": main()
en
0.414208
#from vlcars import __version__ # init local_db # ----------------------------------- # Check arguments and run accordingly # --heroku # parse tabular database to DataFrame and run app. Used by branch "heroku" to run app on Heroku. #args.heroku = True # --sql_to_tab # parses current SQL database to tsv in "data/yy-mm-dd.tsv" # write to file # create Dash app and render results locally # query sites online # # create the mock file for testing # parsed_pages = sorted(parsed_pages) # for page in parsed_pages: # print(page) # # with open("/home/dani/effidotpy/github/VLCars/tests/files/autocasion_parsed.txt", "w") as fout: # for line in parsed_pages: # line[3], line[4], line[5], line[6] = str(line[3]), str(line[4]), str(line[5]), str(line[6]) # fout.write("\t".join(line) + "\n") #----------------------------- # insert in local SQL database
2.756461
3
movefile_restart/__init__.py
hammy3502/python-movefile-restart
0
6623694
<reponame>hammy3502/python-movefile-restart from .main import DeleteFile, MoveFile, RenameFile, GetFileOperations, PrintFileOperations, RemoveFileOperation, CheckPermissions __version__ = "1.0.1"
from .main import DeleteFile, MoveFile, RenameFile, GetFileOperations, PrintFileOperations, RemoveFileOperation, CheckPermissions __version__ = "1.0.1"
none
1
1.170268
1
noobWS/_server.py
lancechua/noobWS
0
6623695
<filename>noobWS/_server.py """NoobServer Module""" import asyncio import logging from typing import Dict, List import websockets import zmq from zmq.asyncio import Context from .constants import Keyword class NoobServer: """ NoobServer class Has the following channels: * Websockets * Socket(s) connected to external URI(s) * If single socket, socket name = `self.name` * If multi socket, socket name = key in `uri` param * Command listener (zmq.PULL by default) * listens to incoming messages; passed to the appropriate websocket * messages must be multipart, i.e. `[uri_name, message]` * Publisher (zmq.PUB by default) * publishes formatted messages received from the external websocket(s) * messages will be multipart, i.e. `[topic, message]` It is recommended to override the `in_formatter` and `out_formatter` methods to match your desired input / output formats """ def __init__( self, uri: Dict[bytes, str] or str, cmd_addr: str, pub_addr: str, name: bytes = None, cmd_stype: int = None, pub_stype: int = None, ): """ Initialize a NoobServer with multiple websockets Parameters ---------- uri: dict[bytes, str] or str Socket URI dictionary * key = name for socket * value = socket URI If `uri` is type `str`, connects to a single socket. Single socket name will be based on the `name` parameter. cmd_addr: str command listener address pub_addr: str message publisher address name : bytes, optional default socket name for single socket, defaults to `b""` cmd_stype, pub_stype: int ZMQ socket types; defaults to `zmq.PULL` and `zmq.PUB` respectively These sockets will `bind` to their respective addresses """ self.name = name or b"" if isinstance(self.name, str): self._name_str = self.name self.name = self.name.encode() else: self._name_str = self.name.decode() if isinstance(uri, str): uri = {self.name: uri} assert all( isinstance(key, bytes) for key in uri ), "all `uri` keys must be type `bytes`" self.uri = uri self.cmd_addr = cmd_addr self.pub_addr = pub_addr self.cmd_stype = cmd_stype or zmq.PULL # pylint: disable=no-member self.pub_stype = pub_stype or zmq.PUB # pylint: disable=no-member self.ctx = Context.instance() self.loop = None self.msg_queue = None self.ws = None self.connected = False async def listener(self): """ Listener Coroutine Handles incoming messages from a NoobClient Notes --------- Messages should come in the following format: `[uri_name: bytes, message: bytes]` `uri_name` should be valid; i.e. in `uri` or `Keyword.command.value` """ receiver = self.ctx.socket(self.cmd_stype) # pylint: disable=no-member receiver.bind(self.cmd_addr) solo_ws = next(iter(self.ws.values())) if len(self.ws) == 1 else None logging.info( f"[NoobServer|{self._name_str}] Receiving NoobClient messages on: %s", self.cmd_addr, ) while True: try: uri_name, msg = await receiver.recv_multipart() except ValueError: logging.error( "Invalid value received. " "Please make sure format is `[uri_name, msg]`" ) continue logging.info( f"[NoobServer|{self._name_str}] LISTENER received %s|%s", uri_name, msg, ) if uri_name == Keyword.command.value: if msg == Keyword.shutdown.value: logging.info( f"[NoobServer|{self._name_str}] LISTENER received KILL signal" ) break elif msg == Keyword.ping.value: await self.msg_queue.put([uri_name, Keyword.pong.value]) else: # formatter here fmt_msg = self.in_formatter(msg, uri_name) try: await self.ws[uri_name].send(fmt_msg) except KeyError: logging.warning( f"[NoobServer|{self._name_str}] '%s' is not in provided uri(s): %s", uri_name, self.ws.keys(), ) if len(self.ws) == 1: logging.warning( ( f"[NoobServer|{self._name_str}] Ignoring uri_name '%s', " "sending message to ONLY socket" ), uri_name, ) await solo_ws.send(fmt_msg) receiver.close() logging.info(f"[NoobServer|{self._name_str}] LISTENER closed") await self.shutdown(False) async def data_feed( self, ws: websockets.WebSocketClientProtocol, uri_name: bytes = b"" ): """ Websocket Coroutine Handles the connection to external websockets Parameters ---------- ws: websockets.WebSocketClientProtocol uri_name: bytes, optional will be supplied to data sent to NoobServer publisher Notes ---------- Messages received are passed to the publisher with the following format: `[uri_name: bytes, message: bytes]` """ log_prefix = "{}| ".format(uri_name.decode()) if uri_name else "" error_caught = False try: async for msg in ws: logging.debug( f"[NoobServer|{self._name_str}] %sReceived %s", log_prefix, msg ) await self.msg_queue.put([uri_name, msg]) except websockets.ConnectionClosedError: logging.error("websocket closed unexpectedly %s", ws.remote_address) error_caught = True except Exception as err: logging.error("websocket error: %s", repr(err)) error_caught = True finally: if error_caught: await self.shutdown(True) async def publisher(self): """ Publisher Coroutine Processes messages from `data_feed` coroutine(s) and publishes for NoobClients """ broadcaster = self.ctx.socket(self.pub_stype) # pylint: disable=no-member broadcaster.setsockopt(zmq.LINGER, 3000) broadcaster.bind(self.pub_addr) logging.info( f"[NoobServer|{self._name_str}] Publishing messages on: %s", self.pub_addr, ) while True: uri_name, msg = await self.msg_queue.get() topic, fmt_msg = self.out_formatter(msg, uri_name) logging.debug( f"[NoobServer|{self._name_str}] PUBLISHER sending %s|%s", topic, fmt_msg, ) await broadcaster.send_multipart([topic, fmt_msg]) if (uri_name == Keyword.command.value) and (msg == Keyword.shutdown.value): break broadcaster.close() logging.info(f"[NoobServer|{self._name_str}] PUBLISHER closed") async def shutdown(self, internal: bool): """Shutdown Coroutine Parameters ---------- internal: bool flag if shutdown triggered internally; (e.g. due to internal error) """ logging.warning(f"[NoobServer|{self._name_str}] shutdown initiated") # close listener if internal: grim_reaper = self.ctx.socket(zmq.PUSH) # pylint: disable=no-member grim_reaper.connect(self.cmd_addr) await grim_reaper.send_multipart( [Keyword.command.value, Keyword.shutdown.value] ) grim_reaper.close() # close publisher await self.msg_queue.put([Keyword.command.value, Keyword.shutdown.value]) # close sockets logging.info("Closing socket(s). This might take ~10 seconds...") await asyncio.gather(*[ws.close() for ws in self.ws.values()]) self.connected = False def run(self, addl_coros: list = None): """Method to start Socket. Blocking Parameters ---------- addl_coros: list additional coroutines / tasks to run """ addl_coros = addl_coros or [] logging.info(f"[NoobServer|{self._name_str}] Starting") self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) self.msg_queue = asyncio.Queue() self.ws = { key: self.loop.run_until_complete(websockets.connect(uri)) for key, uri in self.uri.items() } coros = ( [self.listener(), self.publisher()] + [self.data_feed(ws, key) for key, ws in self.ws.items()] + addl_coros ) logging.info(f"[NoobServer|{self._name_str}] starting tasks") try: self.connected = True self.loop.run_until_complete(asyncio.gather(*coros)) except KeyboardInterrupt: logging.warning(f"[NoobServer|{self._name_str}] KeyboardInterrupt caught!") self.loop.run_until_complete(self.shutdown(True)) finally: self.ctx.term() self.loop.close() logging.info(f"[NoobServer|{self._name_str}] Closed.") def restart(self, addl_coros: list = None): """Restart NoobServer; calls `shutdown` first, then `run`""" self.loop.run_until_complete(self.shutdown(True)) self.run(addl_coros=addl_coros) def in_formatter(self, msg: bytes, uri_name: bytes = b""): """Formatter for incoming messages Parameters ---------- msg: bytes uri_name: bytes, optional defaults to `b""` Returns ---------- bytes or string Output will be sent to the corresponding websocket Notes ---------- Only formats the `msg` part of the multi-part message received by the listener. `uri_name` is always required since it identifies the destination URI. """ return msg.decode() def out_formatter(self, msg, uri_name: bytes = b""): """Formatter for outgoing multi-part messages Parameters ---------- msg: bytes uri_name: bytes, optional used as the topic; defaults to `b""` Returns ---------- tuple[bytes, bytes] `[topic, message]` to be broadcast """ try: fmsg = msg.encode() except AttributeError: fmsg = msg return [uri_name, fmsg]
<filename>noobWS/_server.py """NoobServer Module""" import asyncio import logging from typing import Dict, List import websockets import zmq from zmq.asyncio import Context from .constants import Keyword class NoobServer: """ NoobServer class Has the following channels: * Websockets * Socket(s) connected to external URI(s) * If single socket, socket name = `self.name` * If multi socket, socket name = key in `uri` param * Command listener (zmq.PULL by default) * listens to incoming messages; passed to the appropriate websocket * messages must be multipart, i.e. `[uri_name, message]` * Publisher (zmq.PUB by default) * publishes formatted messages received from the external websocket(s) * messages will be multipart, i.e. `[topic, message]` It is recommended to override the `in_formatter` and `out_formatter` methods to match your desired input / output formats """ def __init__( self, uri: Dict[bytes, str] or str, cmd_addr: str, pub_addr: str, name: bytes = None, cmd_stype: int = None, pub_stype: int = None, ): """ Initialize a NoobServer with multiple websockets Parameters ---------- uri: dict[bytes, str] or str Socket URI dictionary * key = name for socket * value = socket URI If `uri` is type `str`, connects to a single socket. Single socket name will be based on the `name` parameter. cmd_addr: str command listener address pub_addr: str message publisher address name : bytes, optional default socket name for single socket, defaults to `b""` cmd_stype, pub_stype: int ZMQ socket types; defaults to `zmq.PULL` and `zmq.PUB` respectively These sockets will `bind` to their respective addresses """ self.name = name or b"" if isinstance(self.name, str): self._name_str = self.name self.name = self.name.encode() else: self._name_str = self.name.decode() if isinstance(uri, str): uri = {self.name: uri} assert all( isinstance(key, bytes) for key in uri ), "all `uri` keys must be type `bytes`" self.uri = uri self.cmd_addr = cmd_addr self.pub_addr = pub_addr self.cmd_stype = cmd_stype or zmq.PULL # pylint: disable=no-member self.pub_stype = pub_stype or zmq.PUB # pylint: disable=no-member self.ctx = Context.instance() self.loop = None self.msg_queue = None self.ws = None self.connected = False async def listener(self): """ Listener Coroutine Handles incoming messages from a NoobClient Notes --------- Messages should come in the following format: `[uri_name: bytes, message: bytes]` `uri_name` should be valid; i.e. in `uri` or `Keyword.command.value` """ receiver = self.ctx.socket(self.cmd_stype) # pylint: disable=no-member receiver.bind(self.cmd_addr) solo_ws = next(iter(self.ws.values())) if len(self.ws) == 1 else None logging.info( f"[NoobServer|{self._name_str}] Receiving NoobClient messages on: %s", self.cmd_addr, ) while True: try: uri_name, msg = await receiver.recv_multipart() except ValueError: logging.error( "Invalid value received. " "Please make sure format is `[uri_name, msg]`" ) continue logging.info( f"[NoobServer|{self._name_str}] LISTENER received %s|%s", uri_name, msg, ) if uri_name == Keyword.command.value: if msg == Keyword.shutdown.value: logging.info( f"[NoobServer|{self._name_str}] LISTENER received KILL signal" ) break elif msg == Keyword.ping.value: await self.msg_queue.put([uri_name, Keyword.pong.value]) else: # formatter here fmt_msg = self.in_formatter(msg, uri_name) try: await self.ws[uri_name].send(fmt_msg) except KeyError: logging.warning( f"[NoobServer|{self._name_str}] '%s' is not in provided uri(s): %s", uri_name, self.ws.keys(), ) if len(self.ws) == 1: logging.warning( ( f"[NoobServer|{self._name_str}] Ignoring uri_name '%s', " "sending message to ONLY socket" ), uri_name, ) await solo_ws.send(fmt_msg) receiver.close() logging.info(f"[NoobServer|{self._name_str}] LISTENER closed") await self.shutdown(False) async def data_feed( self, ws: websockets.WebSocketClientProtocol, uri_name: bytes = b"" ): """ Websocket Coroutine Handles the connection to external websockets Parameters ---------- ws: websockets.WebSocketClientProtocol uri_name: bytes, optional will be supplied to data sent to NoobServer publisher Notes ---------- Messages received are passed to the publisher with the following format: `[uri_name: bytes, message: bytes]` """ log_prefix = "{}| ".format(uri_name.decode()) if uri_name else "" error_caught = False try: async for msg in ws: logging.debug( f"[NoobServer|{self._name_str}] %sReceived %s", log_prefix, msg ) await self.msg_queue.put([uri_name, msg]) except websockets.ConnectionClosedError: logging.error("websocket closed unexpectedly %s", ws.remote_address) error_caught = True except Exception as err: logging.error("websocket error: %s", repr(err)) error_caught = True finally: if error_caught: await self.shutdown(True) async def publisher(self): """ Publisher Coroutine Processes messages from `data_feed` coroutine(s) and publishes for NoobClients """ broadcaster = self.ctx.socket(self.pub_stype) # pylint: disable=no-member broadcaster.setsockopt(zmq.LINGER, 3000) broadcaster.bind(self.pub_addr) logging.info( f"[NoobServer|{self._name_str}] Publishing messages on: %s", self.pub_addr, ) while True: uri_name, msg = await self.msg_queue.get() topic, fmt_msg = self.out_formatter(msg, uri_name) logging.debug( f"[NoobServer|{self._name_str}] PUBLISHER sending %s|%s", topic, fmt_msg, ) await broadcaster.send_multipart([topic, fmt_msg]) if (uri_name == Keyword.command.value) and (msg == Keyword.shutdown.value): break broadcaster.close() logging.info(f"[NoobServer|{self._name_str}] PUBLISHER closed") async def shutdown(self, internal: bool): """Shutdown Coroutine Parameters ---------- internal: bool flag if shutdown triggered internally; (e.g. due to internal error) """ logging.warning(f"[NoobServer|{self._name_str}] shutdown initiated") # close listener if internal: grim_reaper = self.ctx.socket(zmq.PUSH) # pylint: disable=no-member grim_reaper.connect(self.cmd_addr) await grim_reaper.send_multipart( [Keyword.command.value, Keyword.shutdown.value] ) grim_reaper.close() # close publisher await self.msg_queue.put([Keyword.command.value, Keyword.shutdown.value]) # close sockets logging.info("Closing socket(s). This might take ~10 seconds...") await asyncio.gather(*[ws.close() for ws in self.ws.values()]) self.connected = False def run(self, addl_coros: list = None): """Method to start Socket. Blocking Parameters ---------- addl_coros: list additional coroutines / tasks to run """ addl_coros = addl_coros or [] logging.info(f"[NoobServer|{self._name_str}] Starting") self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) self.msg_queue = asyncio.Queue() self.ws = { key: self.loop.run_until_complete(websockets.connect(uri)) for key, uri in self.uri.items() } coros = ( [self.listener(), self.publisher()] + [self.data_feed(ws, key) for key, ws in self.ws.items()] + addl_coros ) logging.info(f"[NoobServer|{self._name_str}] starting tasks") try: self.connected = True self.loop.run_until_complete(asyncio.gather(*coros)) except KeyboardInterrupt: logging.warning(f"[NoobServer|{self._name_str}] KeyboardInterrupt caught!") self.loop.run_until_complete(self.shutdown(True)) finally: self.ctx.term() self.loop.close() logging.info(f"[NoobServer|{self._name_str}] Closed.") def restart(self, addl_coros: list = None): """Restart NoobServer; calls `shutdown` first, then `run`""" self.loop.run_until_complete(self.shutdown(True)) self.run(addl_coros=addl_coros) def in_formatter(self, msg: bytes, uri_name: bytes = b""): """Formatter for incoming messages Parameters ---------- msg: bytes uri_name: bytes, optional defaults to `b""` Returns ---------- bytes or string Output will be sent to the corresponding websocket Notes ---------- Only formats the `msg` part of the multi-part message received by the listener. `uri_name` is always required since it identifies the destination URI. """ return msg.decode() def out_formatter(self, msg, uri_name: bytes = b""): """Formatter for outgoing multi-part messages Parameters ---------- msg: bytes uri_name: bytes, optional used as the topic; defaults to `b""` Returns ---------- tuple[bytes, bytes] `[topic, message]` to be broadcast """ try: fmsg = msg.encode() except AttributeError: fmsg = msg return [uri_name, fmsg]
en
0.583214
NoobServer Module NoobServer class Has the following channels: * Websockets * Socket(s) connected to external URI(s) * If single socket, socket name = `self.name` * If multi socket, socket name = key in `uri` param * Command listener (zmq.PULL by default) * listens to incoming messages; passed to the appropriate websocket * messages must be multipart, i.e. `[uri_name, message]` * Publisher (zmq.PUB by default) * publishes formatted messages received from the external websocket(s) * messages will be multipart, i.e. `[topic, message]` It is recommended to override the `in_formatter` and `out_formatter` methods to match your desired input / output formats Initialize a NoobServer with multiple websockets Parameters ---------- uri: dict[bytes, str] or str Socket URI dictionary * key = name for socket * value = socket URI If `uri` is type `str`, connects to a single socket. Single socket name will be based on the `name` parameter. cmd_addr: str command listener address pub_addr: str message publisher address name : bytes, optional default socket name for single socket, defaults to `b""` cmd_stype, pub_stype: int ZMQ socket types; defaults to `zmq.PULL` and `zmq.PUB` respectively These sockets will `bind` to their respective addresses # pylint: disable=no-member # pylint: disable=no-member Listener Coroutine Handles incoming messages from a NoobClient Notes --------- Messages should come in the following format: `[uri_name: bytes, message: bytes]` `uri_name` should be valid; i.e. in `uri` or `Keyword.command.value` # pylint: disable=no-member # formatter here Websocket Coroutine Handles the connection to external websockets Parameters ---------- ws: websockets.WebSocketClientProtocol uri_name: bytes, optional will be supplied to data sent to NoobServer publisher Notes ---------- Messages received are passed to the publisher with the following format: `[uri_name: bytes, message: bytes]` Publisher Coroutine Processes messages from `data_feed` coroutine(s) and publishes for NoobClients # pylint: disable=no-member Shutdown Coroutine Parameters ---------- internal: bool flag if shutdown triggered internally; (e.g. due to internal error) # close listener # pylint: disable=no-member # close publisher # close sockets Method to start Socket. Blocking Parameters ---------- addl_coros: list additional coroutines / tasks to run Restart NoobServer; calls `shutdown` first, then `run` Formatter for incoming messages Parameters ---------- msg: bytes uri_name: bytes, optional defaults to `b""` Returns ---------- bytes or string Output will be sent to the corresponding websocket Notes ---------- Only formats the `msg` part of the multi-part message received by the listener. `uri_name` is always required since it identifies the destination URI. Formatter for outgoing multi-part messages Parameters ---------- msg: bytes uri_name: bytes, optional used as the topic; defaults to `b""` Returns ---------- tuple[bytes, bytes] `[topic, message]` to be broadcast
2.734912
3
test/logger.py
mokbat/callerid_test
0
6623696
""" ########################################################## # logger - A class module to assist you in your logging. # # # # This is a stand alone logging function file. # # It gives you an ease creating logging functionality # # for your test cases. This only depends upon the # # modules we import # ########################################################## """ # Standard Python Libraries import os import logging from datetime import datetime class Logger(): """ Custom logger""" def __init__(self, propagate=True, loglevel=20): """ Descriptions - Constructor for Logger which initializes all variables. Mandatory Args - None Optional Args - propagate (bool) : True (default) - Propagate log level across False - Don't propagate log level loglevel (int) : 20 (default) - INFO 10 - DEBUG 30 - WARNING 40 - ERROR 50 - CRITICAL Usage - >>> from logger import Logger ; log = Logger(__file__) """ # Default log msg format self.msg_format = '%(asctime)s | %(levelname).4s | %(lineno)-4d | %(module)-20s | %(message)s' # Default log date format self.date_format = '%m/%d/%y %H:%M:%S' # Default log directory self.log_dir = "logs" # Create the log directory if it does not exists if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) # Log level self.loglevel = loglevel # File Handle self.file_handle = None # Enable / Disable Propagation self.propagate = propagate # Enable formatter self.formatter = logging.Formatter(fmt=self.msg_format, datefmt=self.date_format) # Define log instance self.log = logging.getLogger('root') # Assume we have no stream handlers found = False # Find if we have any instance of stream handler for each in list(logging.root.handlers): each = str(each) if each.split(" ")[0].split(".")[1] == "StreamHandler": found = True break # If not found create one if not found: console_handler = logging.StreamHandler() console_handler.setFormatter(self.formatter) self.log.root.addHandler(console_handler) def file_logger(self, name, propagate=True): """ Descriptions - Create a testcase logger which enables file logging Mandatory Args - name (str) : File name Optional Args - propagate (bool) : True (default) - Propagate log level across False - Don't propagate log level Usage - >>> from logger import Logger ; log = Logger(__file__).testcase() """ # Fetch the name of logger name = os.path.basename(name).split('.')[0] # Get a child logger from root for testcase self.log = logging.getLogger(name).getChild("root.testcase") # Set the logging to required level self.log.setLevel(self.loglevel) # Enable or Disable Propagation self.propagate = propagate # Assume we have no file handlers found = False # Find if there is already a file logger for each in list(logging.root.handlers): each = str(each) if each.split(" ")[0] == "FileHandler": found = True break # If not found create one if not found: file_suffix = datetime.now().strftime('%b_%d_%y_%H_%M_%S') file_handle = logging.FileHandler(self.log_dir + '/' + name + '_' + file_suffix + '.log') file_handle.setFormatter(self.formatter) self.log.root.addHandler(file_handle) self.file_handle = file_handle return self.log
""" ########################################################## # logger - A class module to assist you in your logging. # # # # This is a stand alone logging function file. # # It gives you an ease creating logging functionality # # for your test cases. This only depends upon the # # modules we import # ########################################################## """ # Standard Python Libraries import os import logging from datetime import datetime class Logger(): """ Custom logger""" def __init__(self, propagate=True, loglevel=20): """ Descriptions - Constructor for Logger which initializes all variables. Mandatory Args - None Optional Args - propagate (bool) : True (default) - Propagate log level across False - Don't propagate log level loglevel (int) : 20 (default) - INFO 10 - DEBUG 30 - WARNING 40 - ERROR 50 - CRITICAL Usage - >>> from logger import Logger ; log = Logger(__file__) """ # Default log msg format self.msg_format = '%(asctime)s | %(levelname).4s | %(lineno)-4d | %(module)-20s | %(message)s' # Default log date format self.date_format = '%m/%d/%y %H:%M:%S' # Default log directory self.log_dir = "logs" # Create the log directory if it does not exists if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) # Log level self.loglevel = loglevel # File Handle self.file_handle = None # Enable / Disable Propagation self.propagate = propagate # Enable formatter self.formatter = logging.Formatter(fmt=self.msg_format, datefmt=self.date_format) # Define log instance self.log = logging.getLogger('root') # Assume we have no stream handlers found = False # Find if we have any instance of stream handler for each in list(logging.root.handlers): each = str(each) if each.split(" ")[0].split(".")[1] == "StreamHandler": found = True break # If not found create one if not found: console_handler = logging.StreamHandler() console_handler.setFormatter(self.formatter) self.log.root.addHandler(console_handler) def file_logger(self, name, propagate=True): """ Descriptions - Create a testcase logger which enables file logging Mandatory Args - name (str) : File name Optional Args - propagate (bool) : True (default) - Propagate log level across False - Don't propagate log level Usage - >>> from logger import Logger ; log = Logger(__file__).testcase() """ # Fetch the name of logger name = os.path.basename(name).split('.')[0] # Get a child logger from root for testcase self.log = logging.getLogger(name).getChild("root.testcase") # Set the logging to required level self.log.setLevel(self.loglevel) # Enable or Disable Propagation self.propagate = propagate # Assume we have no file handlers found = False # Find if there is already a file logger for each in list(logging.root.handlers): each = str(each) if each.split(" ")[0] == "FileHandler": found = True break # If not found create one if not found: file_suffix = datetime.now().strftime('%b_%d_%y_%H_%M_%S') file_handle = logging.FileHandler(self.log_dir + '/' + name + '_' + file_suffix + '.log') file_handle.setFormatter(self.formatter) self.log.root.addHandler(file_handle) self.file_handle = file_handle return self.log
en
0.540115
########################################################## # logger - A class module to assist you in your logging. # # # # This is a stand alone logging function file. # # It gives you an ease creating logging functionality # # for your test cases. This only depends upon the # # modules we import # ########################################################## # Standard Python Libraries Custom logger Descriptions - Constructor for Logger which initializes all variables. Mandatory Args - None Optional Args - propagate (bool) : True (default) - Propagate log level across False - Don't propagate log level loglevel (int) : 20 (default) - INFO 10 - DEBUG 30 - WARNING 40 - ERROR 50 - CRITICAL Usage - >>> from logger import Logger ; log = Logger(__file__) # Default log msg format # Default log date format # Default log directory # Create the log directory if it does not exists # Log level # File Handle # Enable / Disable Propagation # Enable formatter # Define log instance # Assume we have no stream handlers # Find if we have any instance of stream handler # If not found create one Descriptions - Create a testcase logger which enables file logging Mandatory Args - name (str) : File name Optional Args - propagate (bool) : True (default) - Propagate log level across False - Don't propagate log level Usage - >>> from logger import Logger ; log = Logger(__file__).testcase() # Fetch the name of logger # Get a child logger from root for testcase # Set the logging to required level # Enable or Disable Propagation # Assume we have no file handlers # Find if there is already a file logger # If not found create one
3.389378
3
converter_gui.py
ShuksanGeomatics/Salish_Sea_Coordinate_Converter
0
6623697
<reponame>ShuksanGeomatics/Salish_Sea_Coordinate_Converter #!/usr/bin/python3 '''This script is a graphic user interface using for generating KML files and CSV files.''' import sys import traceback try: import convert import tkinter as tk from tkinter import ttk def ssconvert(): in_crs = incrs.get() out_crs = outcrs.get() in_x = x_var.get() in_y = y_var.get() conversion = convert.SalishSeaCoordConverter(incrs.get(), outcrs.get(), x_var.get() , y_var.get()) #out_label = Label(root, text= str(conversion.out_x) +', ' +str( conversion.out_y)) #out_latel.pack() return print (conversion.out_x, conversion.out_y) # Creating tkinter window window = tk.Tk() window.title('Salish Sea Coordinate Converter') window.geometry('400x200') # label ttk.Label(window, text = "Select input CRS :").grid(column = 0, row = 5, padx = 5, pady = 10) # label ttk.Label(window, text = "Select output CRS :").grid(column = 0, row = 6, padx = 5, pady = 10) # label ttk.Label(window, text = "x :").grid(column = 0, row = 7, padx = 5, pady = 10) # label ttk.Label(window, text = "y :").grid(column = 0, row = 8, padx = 5, pady = 10) # Combobox creation incrs = tk.StringVar() crschoosen = ttk.Combobox(window, width = 15, textvariable = incrs) # Combobox creation outcrs = tk.StringVar() crschoosen2 = ttk.Combobox(window, width = 15, textvariable = outcrs) x_var = tk.DoubleVar() x_entry = tk.Entry(window, textvariable = x_var) y_var = tk.DoubleVar() y_entry = tk.Entry(window, textvariable = y_var) # Adding combobox drop down list crschoosen['values'] = ('WN_HARN','WN_NAD83','WN_NAD27','WS_HARN','WS_NAD83','WS_NAD27','UTM10N_WGS84','UTM10N_NAD83','UTM10N_NAD27','UTM10N_WGS72','UTM10N_HARN','WGS84','WGS72') crschoosen2['values'] = ('WN_HARN','WN_NAD83','WN_NAD27','WS_HARN','WS_NAD83','WS_NAD27','UTM10N_WGS84','UTM10N_NAD83','UTM10N_NAD27','UTM10N_WGS72','UTM10N_HARN','WGS84','WGS72') crschoosen.grid(column = 1, row = 5) crschoosen2.grid(column = 1, row = 6) crschoosen.current() crschoosen2.current() x_entry.grid(row=7,column=1) y_entry.grid(row=8,column=1) sub_btn=tk.Button(window,text = 'Convert', command = ssconvert) sub_btn.grid(row=9,column=1) window.mainloop() except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] print ("PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]))
#!/usr/bin/python3 '''This script is a graphic user interface using for generating KML files and CSV files.''' import sys import traceback try: import convert import tkinter as tk from tkinter import ttk def ssconvert(): in_crs = incrs.get() out_crs = outcrs.get() in_x = x_var.get() in_y = y_var.get() conversion = convert.SalishSeaCoordConverter(incrs.get(), outcrs.get(), x_var.get() , y_var.get()) #out_label = Label(root, text= str(conversion.out_x) +', ' +str( conversion.out_y)) #out_latel.pack() return print (conversion.out_x, conversion.out_y) # Creating tkinter window window = tk.Tk() window.title('Salish Sea Coordinate Converter') window.geometry('400x200') # label ttk.Label(window, text = "Select input CRS :").grid(column = 0, row = 5, padx = 5, pady = 10) # label ttk.Label(window, text = "Select output CRS :").grid(column = 0, row = 6, padx = 5, pady = 10) # label ttk.Label(window, text = "x :").grid(column = 0, row = 7, padx = 5, pady = 10) # label ttk.Label(window, text = "y :").grid(column = 0, row = 8, padx = 5, pady = 10) # Combobox creation incrs = tk.StringVar() crschoosen = ttk.Combobox(window, width = 15, textvariable = incrs) # Combobox creation outcrs = tk.StringVar() crschoosen2 = ttk.Combobox(window, width = 15, textvariable = outcrs) x_var = tk.DoubleVar() x_entry = tk.Entry(window, textvariable = x_var) y_var = tk.DoubleVar() y_entry = tk.Entry(window, textvariable = y_var) # Adding combobox drop down list crschoosen['values'] = ('WN_HARN','WN_NAD83','WN_NAD27','WS_HARN','WS_NAD83','WS_NAD27','UTM10N_WGS84','UTM10N_NAD83','UTM10N_NAD27','UTM10N_WGS72','UTM10N_HARN','WGS84','WGS72') crschoosen2['values'] = ('WN_HARN','WN_NAD83','WN_NAD27','WS_HARN','WS_NAD83','WS_NAD27','UTM10N_WGS84','UTM10N_NAD83','UTM10N_NAD27','UTM10N_WGS72','UTM10N_HARN','WGS84','WGS72') crschoosen.grid(column = 1, row = 5) crschoosen2.grid(column = 1, row = 6) crschoosen.current() crschoosen2.current() x_entry.grid(row=7,column=1) y_entry.grid(row=8,column=1) sub_btn=tk.Button(window,text = 'Convert', command = ssconvert) sub_btn.grid(row=9,column=1) window.mainloop() except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] print ("PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]))
en
0.340044
#!/usr/bin/python3 This script is a graphic user interface using for generating KML files and CSV files. #out_label = Label(root, text= str(conversion.out_x) +', ' +str( conversion.out_y)) #out_latel.pack() # Creating tkinter window # label # label # label # label # Combobox creation # Combobox creation # Adding combobox drop down list
3.027438
3
burgeon-server/burgeon/api/tracks/delete_track_api.py
danielvinson/Burgeon
1
6623698
import logging import json from flask import request, make_response, jsonify from flask.views import MethodView from flask_login import current_user from burgeon import db from burgeon.models import Track log = logging.getLogger('burgeon.track.delete_track_api') class DeleteTrackAPI(MethodView): """ Delete Track """ def delete(self, track_id): post_data = request.get_json() track = Track.query.get(track_id) if track: try: db.session.delete(track) db.session.commit() responseObject = { 'status': 'success', 'message': 'Track successfully deleted.' } return make_response(jsonify(responseObject), 202) except Exception as e: log.error('Delete Track failed. Error: {}. Params: {}'.format(e, post_data)) responseObject = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } return make_response(jsonify(responseObject), 401) else: responseObject = { 'status': 'fail', 'message': 'Track not found.', } return make_response(jsonify(responseObject), 404)
import logging import json from flask import request, make_response, jsonify from flask.views import MethodView from flask_login import current_user from burgeon import db from burgeon.models import Track log = logging.getLogger('burgeon.track.delete_track_api') class DeleteTrackAPI(MethodView): """ Delete Track """ def delete(self, track_id): post_data = request.get_json() track = Track.query.get(track_id) if track: try: db.session.delete(track) db.session.commit() responseObject = { 'status': 'success', 'message': 'Track successfully deleted.' } return make_response(jsonify(responseObject), 202) except Exception as e: log.error('Delete Track failed. Error: {}. Params: {}'.format(e, post_data)) responseObject = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } return make_response(jsonify(responseObject), 401) else: responseObject = { 'status': 'fail', 'message': 'Track not found.', } return make_response(jsonify(responseObject), 404)
en
0.989964
Delete Track
2.264223
2
scripts/tSNEW2V_Sum.py
nik-sm/neural-topic-models-music
0
6623699
<reponame>nik-sm/neural-topic-models-music import matplotlib.pyplot as plt from sklearn.manifold import TSNE import numpy as np sumFeatures = np.load("../data/nik/word2VecSumFeatures.npy") X_embedded = TSNE(n_components=2).fit_transform(sumFeatures) np.save("../results/tSNE_w2v_sum.npy")
import matplotlib.pyplot as plt from sklearn.manifold import TSNE import numpy as np sumFeatures = np.load("../data/nik/word2VecSumFeatures.npy") X_embedded = TSNE(n_components=2).fit_transform(sumFeatures) np.save("../results/tSNE_w2v_sum.npy")
none
1
2.551311
3
python/302.smallest-rectangle-enclosing-black-pixels.py
Zhenye-Na/leetcode
10
6623700
<reponame>Zhenye-Na/leetcode<gh_stars>1-10 # [302] Smallest Rectangle Enclosing Black Pixels # Description # An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. # The black pixels are connected, i.e., there is only one black region. # Pixels are connected horizontally and vertically. # Given the location (x, y) of one of the black pixels, return the area of the smallest # (axis-aligned) rectangle that encloses all black pixels. # Example # Example 1: # Input: # [ # "0010", # "0110", # "0100" # ], # x=0,y=2 # Output:6 # Explanation: # The upper left coordinate of the matrix is (0,1), and the lower right coordinate is (2,2). # Example 2: # Input:["1110","1100","0000","0000"], x = 0, y = 1 # Output:6 # Explanation: # The upper left coordinate of the matrix is (0, 0), and the lower right coordinate is (1,2). # Tag Google class Solution: """ @param image: a binary matrix with '0' and '1' @param x: the location of one of the black pixels @param y: the location of one of the black pixels @return: an integer """ def __init__(self): self.WHITE = '0' self.BLACK = '1' def minArea(self, image, x, y): # write your code here # O(n^2) if not image or len(image) == 0 or len(image[0]) == 0: return 0 m, n = len(image), len(image[0]) x_min, x_max = n - 1, 0 y_min, y_max = m - 1, 0 for i in range(m): for j in range(n): if image[i][j] == self.BLACK: x_min = min(x_min, j) x_max = max(x_max, j) y_min = min(y_min, i) y_max = max(y_max, i) return (x_max - x_min + 1) * (y_max - y_min + 1)
# [302] Smallest Rectangle Enclosing Black Pixels # Description # An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. # The black pixels are connected, i.e., there is only one black region. # Pixels are connected horizontally and vertically. # Given the location (x, y) of one of the black pixels, return the area of the smallest # (axis-aligned) rectangle that encloses all black pixels. # Example # Example 1: # Input: # [ # "0010", # "0110", # "0100" # ], # x=0,y=2 # Output:6 # Explanation: # The upper left coordinate of the matrix is (0,1), and the lower right coordinate is (2,2). # Example 2: # Input:["1110","1100","0000","0000"], x = 0, y = 1 # Output:6 # Explanation: # The upper left coordinate of the matrix is (0, 0), and the lower right coordinate is (1,2). # Tag Google class Solution: """ @param image: a binary matrix with '0' and '1' @param x: the location of one of the black pixels @param y: the location of one of the black pixels @return: an integer """ def __init__(self): self.WHITE = '0' self.BLACK = '1' def minArea(self, image, x, y): # write your code here # O(n^2) if not image or len(image) == 0 or len(image[0]) == 0: return 0 m, n = len(image), len(image[0]) x_min, x_max = n - 1, 0 y_min, y_max = m - 1, 0 for i in range(m): for j in range(n): if image[i][j] == self.BLACK: x_min = min(x_min, j) x_max = max(x_max, j) y_min = min(y_min, i) y_max = max(y_max, i) return (x_max - x_min + 1) * (y_max - y_min + 1)
en
0.776718
# [302] Smallest Rectangle Enclosing Black Pixels # Description # An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. # The black pixels are connected, i.e., there is only one black region. # Pixels are connected horizontally and vertically. # Given the location (x, y) of one of the black pixels, return the area of the smallest # (axis-aligned) rectangle that encloses all black pixels. # Example # Example 1: # Input: # [ # "0010", # "0110", # "0100" # ], # x=0,y=2 # Output:6 # Explanation: # The upper left coordinate of the matrix is (0,1), and the lower right coordinate is (2,2). # Example 2: # Input:["1110","1100","0000","0000"], x = 0, y = 1 # Output:6 # Explanation: # The upper left coordinate of the matrix is (0, 0), and the lower right coordinate is (1,2). # Tag Google @param image: a binary matrix with '0' and '1' @param x: the location of one of the black pixels @param y: the location of one of the black pixels @return: an integer # write your code here # O(n^2)
3.896281
4
app.py
Yuchees/esf_maps_template
0
6623701
<reponame>Yuchees/esf_maps_template #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Template of the interactive ESF map within 3D molecular viewer Author: <NAME> """ import pandas as pd import dash import dash_html_components as html import dash_core_components as dcc from utils import th4_plot, structure_viewer from config import CONFIG # Set up web server app = dash.Dash(__name__) server = app.server # Load dataframe df = pd.read_csv('./data/th4.csv') columns_dict = [{'label': i, 'value': i} for i in df.columns[1:-1]] # Application object and HTML components app.layout = html.Div( id='main', className='app_main', children=[ # Dash title and icon html.Div( id='mol3d-title', children=[ html.Img( id='dash-logo', src="https://s3-us-west-1.amazonaws.com/plotly-tutorials/" "logo/new-branding/dash-logo-by-plotly-stripe.png" ), html.H1(id='chart-title', children='ESF maps') ] ), # Dash graph and 3D molecule viewer dcc.Graph(id='indicator-graphic', config=CONFIG), # Dash axis, colour bar and range selection controller html.Div( id='plot-controller', children=[ html.H3('Chart types:'), dcc.RadioItems( id='chart-type', options=[ {'label': 'ESF Map: TH4', 'value': 'th4'} ], value='th4' ), html.Div( id='color-bar-control', className='dropdown-control', children=[ html.H3('Colour bar:'), dcc.Dropdown( id='colour_column', options=columns_dict, value='No. of hydrogen bonds' ) ] ), html.Div( id='x-axis', className='dropdown-control', children=[ html.H3('X-axis:'), dcc.Dropdown( id='x_axis_column', className='axis_controller', options=columns_dict, value='Density (g/cm^3)' ) ] ), html.Div( id='y-axis', className='dropdown-control', children=[ html.H3('Y-axis:'), dcc.Dropdown( id='y_axis_column', className='axis_controller', options=columns_dict, value='Relative lattice energy (kJ/mol)' ) ] ), html.P('The X and Y axis dropdown are disabled ' 'when choose landmarks chart.'), html.Div( id='range-slider-control', className='dropdown-control', children=[ html.H3('Range slider:'), dcc.Dropdown( id='range_column', options=columns_dict, value='Relative lattice energy (kJ/mol)' ) ] ), # Dash range slider and texts dcc.RangeSlider(id='range-slider'), html.P(id='selected_data'), # User instructions ] ), html.Div( id='selected_structure', children=[ html.H3(className='viewer-title', children='Selected structure:'), dcc.Loading(id='loading_selected', className='loading') ] ) ] ) # Setting range slider properties @app.callback( dash.dependencies.Output('range-slider', 'min'), [dash.dependencies.Input('range_column', 'value')]) def select_bar1(range_column_value): return df[range_column_value].min() @app.callback( dash.dependencies.Output('range-slider', 'max'), [dash.dependencies.Input('range_column', 'value')]) def select_bar2(range_column_value): return df[range_column_value].max() @app.callback( dash.dependencies.Output('range-slider', 'value'), [dash.dependencies.Input('range_column', 'value')]) def select_bar3(range_column_value): return [df[range_column_value].min(), df[range_column_value].max()] @app.callback( dash.dependencies.Output('range-slider', 'step'), [dash.dependencies.Input('range_column', 'value')] ) def range_step(range_column_value): step = (df[range_column_value].max() - df[range_column_value].min())/100 return step # Print the selected range @app.callback( dash.dependencies.Output('selected_data', 'children'), [dash.dependencies.Input('range-slider', 'value'), dash.dependencies.Input('range_column', 'value')]) def callback(range_slider_value, range_column_value): return 'Structure {} between {:>.1f} and {:>.1f} are selected.'.format( range_column_value, range_slider_value[0], range_slider_value[1] ) # Chemical structure 3D viewer @app.callback( dash.dependencies.Output('loading_selected', 'children'), [dash.dependencies.Input('indicator-graphic', 'selectedData')]) def display_selected_structure(selectedData): return structure_viewer(df, selectedData) # Figure updated by different dash components @app.callback( dash.dependencies.Output('indicator-graphic', 'figure'), [dash.dependencies.Input('x_axis_column', 'value'), dash.dependencies.Input('y_axis_column', 'value'), dash.dependencies.Input('colour_column', 'value'), dash.dependencies.Input('range_column', 'value'), dash.dependencies.Input('range-slider', 'value')]) def update_graph(x_axis_column_name, y_axis_column_name, colour_column_value, range_column_value, range_slider_value): filtered_df = pd.DataFrame( data=df[ (df[range_column_value] >= range_slider_value[0]) & (df[range_column_value] <= range_slider_value[1])] ) # General ESF map fig = th4_plot(filtered_df, x_axis_column_name, y_axis_column_name, colour_column_value) return fig if __name__ == '__main__': app.run_server(debug=False)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Template of the interactive ESF map within 3D molecular viewer Author: <NAME> """ import pandas as pd import dash import dash_html_components as html import dash_core_components as dcc from utils import th4_plot, structure_viewer from config import CONFIG # Set up web server app = dash.Dash(__name__) server = app.server # Load dataframe df = pd.read_csv('./data/th4.csv') columns_dict = [{'label': i, 'value': i} for i in df.columns[1:-1]] # Application object and HTML components app.layout = html.Div( id='main', className='app_main', children=[ # Dash title and icon html.Div( id='mol3d-title', children=[ html.Img( id='dash-logo', src="https://s3-us-west-1.amazonaws.com/plotly-tutorials/" "logo/new-branding/dash-logo-by-plotly-stripe.png" ), html.H1(id='chart-title', children='ESF maps') ] ), # Dash graph and 3D molecule viewer dcc.Graph(id='indicator-graphic', config=CONFIG), # Dash axis, colour bar and range selection controller html.Div( id='plot-controller', children=[ html.H3('Chart types:'), dcc.RadioItems( id='chart-type', options=[ {'label': 'ESF Map: TH4', 'value': 'th4'} ], value='th4' ), html.Div( id='color-bar-control', className='dropdown-control', children=[ html.H3('Colour bar:'), dcc.Dropdown( id='colour_column', options=columns_dict, value='No. of hydrogen bonds' ) ] ), html.Div( id='x-axis', className='dropdown-control', children=[ html.H3('X-axis:'), dcc.Dropdown( id='x_axis_column', className='axis_controller', options=columns_dict, value='Density (g/cm^3)' ) ] ), html.Div( id='y-axis', className='dropdown-control', children=[ html.H3('Y-axis:'), dcc.Dropdown( id='y_axis_column', className='axis_controller', options=columns_dict, value='Relative lattice energy (kJ/mol)' ) ] ), html.P('The X and Y axis dropdown are disabled ' 'when choose landmarks chart.'), html.Div( id='range-slider-control', className='dropdown-control', children=[ html.H3('Range slider:'), dcc.Dropdown( id='range_column', options=columns_dict, value='Relative lattice energy (kJ/mol)' ) ] ), # Dash range slider and texts dcc.RangeSlider(id='range-slider'), html.P(id='selected_data'), # User instructions ] ), html.Div( id='selected_structure', children=[ html.H3(className='viewer-title', children='Selected structure:'), dcc.Loading(id='loading_selected', className='loading') ] ) ] ) # Setting range slider properties @app.callback( dash.dependencies.Output('range-slider', 'min'), [dash.dependencies.Input('range_column', 'value')]) def select_bar1(range_column_value): return df[range_column_value].min() @app.callback( dash.dependencies.Output('range-slider', 'max'), [dash.dependencies.Input('range_column', 'value')]) def select_bar2(range_column_value): return df[range_column_value].max() @app.callback( dash.dependencies.Output('range-slider', 'value'), [dash.dependencies.Input('range_column', 'value')]) def select_bar3(range_column_value): return [df[range_column_value].min(), df[range_column_value].max()] @app.callback( dash.dependencies.Output('range-slider', 'step'), [dash.dependencies.Input('range_column', 'value')] ) def range_step(range_column_value): step = (df[range_column_value].max() - df[range_column_value].min())/100 return step # Print the selected range @app.callback( dash.dependencies.Output('selected_data', 'children'), [dash.dependencies.Input('range-slider', 'value'), dash.dependencies.Input('range_column', 'value')]) def callback(range_slider_value, range_column_value): return 'Structure {} between {:>.1f} and {:>.1f} are selected.'.format( range_column_value, range_slider_value[0], range_slider_value[1] ) # Chemical structure 3D viewer @app.callback( dash.dependencies.Output('loading_selected', 'children'), [dash.dependencies.Input('indicator-graphic', 'selectedData')]) def display_selected_structure(selectedData): return structure_viewer(df, selectedData) # Figure updated by different dash components @app.callback( dash.dependencies.Output('indicator-graphic', 'figure'), [dash.dependencies.Input('x_axis_column', 'value'), dash.dependencies.Input('y_axis_column', 'value'), dash.dependencies.Input('colour_column', 'value'), dash.dependencies.Input('range_column', 'value'), dash.dependencies.Input('range-slider', 'value')]) def update_graph(x_axis_column_name, y_axis_column_name, colour_column_value, range_column_value, range_slider_value): filtered_df = pd.DataFrame( data=df[ (df[range_column_value] >= range_slider_value[0]) & (df[range_column_value] <= range_slider_value[1])] ) # General ESF map fig = th4_plot(filtered_df, x_axis_column_name, y_axis_column_name, colour_column_value) return fig if __name__ == '__main__': app.run_server(debug=False)
en
0.640658
#!/usr/bin/env python3 # -*- coding: utf-8 -*- Template of the interactive ESF map within 3D molecular viewer Author: <NAME> # Set up web server # Load dataframe # Application object and HTML components # Dash title and icon # Dash graph and 3D molecule viewer # Dash axis, colour bar and range selection controller # Dash range slider and texts # User instructions # Setting range slider properties # Print the selected range # Chemical structure 3D viewer # Figure updated by different dash components # General ESF map
2.231457
2
第11章/program/baidu/spiders/example.py
kingname/SourceCodeOfBook
274
6623702
# -*- coding: utf-8 -*- import scrapy class ExampleSpider(scrapy.Spider): name = "example" allowed_domains = ["baidu.com"] start_urls = ['http://baidu.com/'] def parse(self, response): # title = response.xpath('//title/text()').extract() # search_button_text = response.xpath('//input[@class="bg s_btn"]/@value').extract() # print(title) # print(search_button_text) title_example = response.xpath('//title/text()') title_example_1 = title_example.extract()[0] title_example_2 = title_example[0].extract() print('先读取下标为0的元素,再extract: {}'.format(title_example_1)) print('先extract,再读取下标为0的元素: {}'.format(title_example_2))
# -*- coding: utf-8 -*- import scrapy class ExampleSpider(scrapy.Spider): name = "example" allowed_domains = ["baidu.com"] start_urls = ['http://baidu.com/'] def parse(self, response): # title = response.xpath('//title/text()').extract() # search_button_text = response.xpath('//input[@class="bg s_btn"]/@value').extract() # print(title) # print(search_button_text) title_example = response.xpath('//title/text()') title_example_1 = title_example.extract()[0] title_example_2 = title_example[0].extract() print('先读取下标为0的元素,再extract: {}'.format(title_example_1)) print('先extract,再读取下标为0的元素: {}'.format(title_example_2))
en
0.352694
# -*- coding: utf-8 -*- # title = response.xpath('//title/text()').extract() # search_button_text = response.xpath('//input[@class="bg s_btn"]/@value').extract() # print(title) # print(search_button_text)
3.07067
3
src/resdk/tables/methylation.py
robertcv/resolwe-bio-py
4
6623703
""".. Ignore pydocstyle D400. ================= MethylationTables ================= .. autoclass:: MethylationTables :members: .. automethod:: __init__ """ import os from functools import lru_cache from typing import Callable, List, Optional import pandas as pd from resdk.resources import Collection from .base import BaseTables CHUNK_SIZE = 1000 class MethylationTables(BaseTables): """A helper class to fetch collection's methylation and meta data. This class enables fetching given collection's data and returning it as tables which have samples in rows and methylation/metadata in columns. A simple example: .. code-block:: python # Get Collection object collection = res.collection.get("collection-slug") # Fetch collection methylation and metadata tables = MethylationTables(collection) meta = tables.meta beta = tables.beta m_values = tables.mval """ process_type = "data:methylation:" BETA = "betas" MVAL = "mvals" data_type_to_field_name = { BETA: "methylation_data", MVAL: "methylation_data", } def __init__( self, collection: Collection, cache_dir: Optional[str] = None, progress_callable: Optional[Callable] = None, ): """Initialize class. :param collection: collection to use :param cache_dir: cache directory location, if not specified system specific cache directory is used :param progress_callable: custom callable that can be used to report progress. By default, progress is written to stderr with tqdm """ super().__init__(collection, cache_dir, progress_callable) self.probe_ids = [] # type: List[str] @property @lru_cache() def beta(self) -> pd.DataFrame: """Return beta values table as a pandas DataFrame object.""" beta = self._load_fetch(self.BETA) self.probe_ids = beta.columns.tolist() return beta @property @lru_cache() def mval(self) -> pd.DataFrame: """Return m-values as a pandas DataFrame object.""" mval = self._load_fetch(self.MVAL) self.probe_ids = mval.columns.tolist() return mval def _cache_file(self, data_type: str) -> str: """Return full cache file path.""" if data_type == self.META: version = self._metadata_version elif data_type == self.QC: version = self._qc_version else: version = self._data_version cache_file = f"{self.collection.slug}_{data_type}_{version}.pickle" return os.path.join(self.cache_dir, cache_file) def _download_qc(self) -> pd.DataFrame: """Download sample QC data and transform into table.""" return pd.DataFrame() def _parse_file(self, file_obj, sample_id, data_type): """Parse file object and return one DataFrame line.""" sample_data = pd.read_csv( file_obj, sep="\t", compression="gzip", usecols=["probe_ids", data_type], index_col="probe_ids", )[data_type] sample_data.name = sample_id return sample_data
""".. Ignore pydocstyle D400. ================= MethylationTables ================= .. autoclass:: MethylationTables :members: .. automethod:: __init__ """ import os from functools import lru_cache from typing import Callable, List, Optional import pandas as pd from resdk.resources import Collection from .base import BaseTables CHUNK_SIZE = 1000 class MethylationTables(BaseTables): """A helper class to fetch collection's methylation and meta data. This class enables fetching given collection's data and returning it as tables which have samples in rows and methylation/metadata in columns. A simple example: .. code-block:: python # Get Collection object collection = res.collection.get("collection-slug") # Fetch collection methylation and metadata tables = MethylationTables(collection) meta = tables.meta beta = tables.beta m_values = tables.mval """ process_type = "data:methylation:" BETA = "betas" MVAL = "mvals" data_type_to_field_name = { BETA: "methylation_data", MVAL: "methylation_data", } def __init__( self, collection: Collection, cache_dir: Optional[str] = None, progress_callable: Optional[Callable] = None, ): """Initialize class. :param collection: collection to use :param cache_dir: cache directory location, if not specified system specific cache directory is used :param progress_callable: custom callable that can be used to report progress. By default, progress is written to stderr with tqdm """ super().__init__(collection, cache_dir, progress_callable) self.probe_ids = [] # type: List[str] @property @lru_cache() def beta(self) -> pd.DataFrame: """Return beta values table as a pandas DataFrame object.""" beta = self._load_fetch(self.BETA) self.probe_ids = beta.columns.tolist() return beta @property @lru_cache() def mval(self) -> pd.DataFrame: """Return m-values as a pandas DataFrame object.""" mval = self._load_fetch(self.MVAL) self.probe_ids = mval.columns.tolist() return mval def _cache_file(self, data_type: str) -> str: """Return full cache file path.""" if data_type == self.META: version = self._metadata_version elif data_type == self.QC: version = self._qc_version else: version = self._data_version cache_file = f"{self.collection.slug}_{data_type}_{version}.pickle" return os.path.join(self.cache_dir, cache_file) def _download_qc(self) -> pd.DataFrame: """Download sample QC data and transform into table.""" return pd.DataFrame() def _parse_file(self, file_obj, sample_id, data_type): """Parse file object and return one DataFrame line.""" sample_data = pd.read_csv( file_obj, sep="\t", compression="gzip", usecols=["probe_ids", data_type], index_col="probe_ids", )[data_type] sample_data.name = sample_id return sample_data
en
0.64638
.. Ignore pydocstyle D400. ================= MethylationTables ================= .. autoclass:: MethylationTables :members: .. automethod:: __init__ A helper class to fetch collection's methylation and meta data. This class enables fetching given collection's data and returning it as tables which have samples in rows and methylation/metadata in columns. A simple example: .. code-block:: python # Get Collection object collection = res.collection.get("collection-slug") # Fetch collection methylation and metadata tables = MethylationTables(collection) meta = tables.meta beta = tables.beta m_values = tables.mval Initialize class. :param collection: collection to use :param cache_dir: cache directory location, if not specified system specific cache directory is used :param progress_callable: custom callable that can be used to report progress. By default, progress is written to stderr with tqdm # type: List[str] Return beta values table as a pandas DataFrame object. Return m-values as a pandas DataFrame object. Return full cache file path. Download sample QC data and transform into table. Parse file object and return one DataFrame line.
2.430606
2
tests/test_utils/test_memory.py
Youth-Got/mmdetection
1
6623704
import numpy as np import pytest import torch from mmdet.utils import AvoidOOM from mmdet.utils.memory import cast_tensor_type def test_avoidoom(): tensor = torch.from_numpy(np.random.random((20, 20))) if torch.cuda.is_available(): tensor = tensor.cuda() # get default result default_result = torch.mm(tensor, tensor.transpose(1, 0)) # when not occurred OOM error AvoidCudaOOM = AvoidOOM() result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.equal(default_result, result) # calculate with fp16 and convert back to source type AvoidCudaOOM = AvoidOOM(test=True) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.allclose(default_result, result, 1e-3) # calculate on cpu and convert back to source device AvoidCudaOOM = AvoidOOM(test=True) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert result.dtype == default_result.dtype and \ result.device == default_result.device and \ torch.allclose(default_result, result) # do not calculate on cpu and the outputs will be same as input AvoidCudaOOM = AvoidOOM(test=True, to_cpu=False) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert result.dtype == default_result.dtype and \ result.device == default_result.device else: default_result = torch.mm(tensor, tensor.transpose(1, 0)) AvoidCudaOOM = AvoidOOM() result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.equal(default_result, result) def test_cast_tensor_type(): inputs = torch.rand(10) if torch.cuda.is_available(): inputs = inputs.cuda() with pytest.raises(AssertionError): cast_tensor_type(inputs, src_type=None, dst_type=None) # input is a float out = cast_tensor_type(10., dst_type=torch.half) assert out == 10. and isinstance(out, float) # convert Tensor to fp16 and re-convert to fp32 fp16_out = cast_tensor_type(inputs, dst_type=torch.half) assert fp16_out.dtype == torch.half fp32_out = cast_tensor_type(fp16_out, dst_type=torch.float32) assert fp32_out.dtype == torch.float32 # input is a list list_input = [inputs, inputs] list_outs = cast_tensor_type(list_input, dst_type=torch.half) assert len(list_outs) == len(list_input) and \ isinstance(list_outs, list) for out in list_outs: assert out.dtype == torch.half # input is a dict dict_input = {'test1': inputs, 'test2': inputs} dict_outs = cast_tensor_type(dict_input, dst_type=torch.half) assert len(dict_outs) == len(dict_input) and \ isinstance(dict_outs, dict) # convert the input tensor to CPU and re-convert to GPU if torch.cuda.is_available(): cpu_device = torch.empty(0).device gpu_device = inputs.device cpu_out = cast_tensor_type(inputs, dst_type=cpu_device) assert cpu_out.device == cpu_device gpu_out = cast_tensor_type(inputs, dst_type=gpu_device) assert gpu_out.device == gpu_device
import numpy as np import pytest import torch from mmdet.utils import AvoidOOM from mmdet.utils.memory import cast_tensor_type def test_avoidoom(): tensor = torch.from_numpy(np.random.random((20, 20))) if torch.cuda.is_available(): tensor = tensor.cuda() # get default result default_result = torch.mm(tensor, tensor.transpose(1, 0)) # when not occurred OOM error AvoidCudaOOM = AvoidOOM() result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.equal(default_result, result) # calculate with fp16 and convert back to source type AvoidCudaOOM = AvoidOOM(test=True) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.allclose(default_result, result, 1e-3) # calculate on cpu and convert back to source device AvoidCudaOOM = AvoidOOM(test=True) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert result.dtype == default_result.dtype and \ result.device == default_result.device and \ torch.allclose(default_result, result) # do not calculate on cpu and the outputs will be same as input AvoidCudaOOM = AvoidOOM(test=True, to_cpu=False) result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert result.dtype == default_result.dtype and \ result.device == default_result.device else: default_result = torch.mm(tensor, tensor.transpose(1, 0)) AvoidCudaOOM = AvoidOOM() result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, tensor.transpose( 1, 0)) assert default_result.device == result.device and \ default_result.dtype == result.dtype and \ torch.equal(default_result, result) def test_cast_tensor_type(): inputs = torch.rand(10) if torch.cuda.is_available(): inputs = inputs.cuda() with pytest.raises(AssertionError): cast_tensor_type(inputs, src_type=None, dst_type=None) # input is a float out = cast_tensor_type(10., dst_type=torch.half) assert out == 10. and isinstance(out, float) # convert Tensor to fp16 and re-convert to fp32 fp16_out = cast_tensor_type(inputs, dst_type=torch.half) assert fp16_out.dtype == torch.half fp32_out = cast_tensor_type(fp16_out, dst_type=torch.float32) assert fp32_out.dtype == torch.float32 # input is a list list_input = [inputs, inputs] list_outs = cast_tensor_type(list_input, dst_type=torch.half) assert len(list_outs) == len(list_input) and \ isinstance(list_outs, list) for out in list_outs: assert out.dtype == torch.half # input is a dict dict_input = {'test1': inputs, 'test2': inputs} dict_outs = cast_tensor_type(dict_input, dst_type=torch.half) assert len(dict_outs) == len(dict_input) and \ isinstance(dict_outs, dict) # convert the input tensor to CPU and re-convert to GPU if torch.cuda.is_available(): cpu_device = torch.empty(0).device gpu_device = inputs.device cpu_out = cast_tensor_type(inputs, dst_type=cpu_device) assert cpu_out.device == cpu_device gpu_out = cast_tensor_type(inputs, dst_type=gpu_device) assert gpu_out.device == gpu_device
en
0.794108
# get default result # when not occurred OOM error # calculate with fp16 and convert back to source type # calculate on cpu and convert back to source device # do not calculate on cpu and the outputs will be same as input # input is a float # convert Tensor to fp16 and re-convert to fp32 # input is a list # input is a dict # convert the input tensor to CPU and re-convert to GPU
1.950594
2
obo/exceptions.py
biosustain/obo
1
6623705
<gh_stars>1-10 class OBOException(object): pass class OBOTagCardinalityException(OBOException): def __init__(self, stanza, tag, cardinality=(0, 1)): pass class UnknownTermSubset(OBOException): """ https://oboformat.googlecode.com/svn/trunk/doc/GO.format.obo-1_2.html#S.2.2 The value of this tag must be a subset name as defined in a subsetdef tag in the file header. If the value of this tag is not mentioned in a subsetdef tag, a parse error will be generated. A term may belong to any number of subsets. """ def __init__(self): pass class MissingRequiredTag(OBOException): pass
class OBOException(object): pass class OBOTagCardinalityException(OBOException): def __init__(self, stanza, tag, cardinality=(0, 1)): pass class UnknownTermSubset(OBOException): """ https://oboformat.googlecode.com/svn/trunk/doc/GO.format.obo-1_2.html#S.2.2 The value of this tag must be a subset name as defined in a subsetdef tag in the file header. If the value of this tag is not mentioned in a subsetdef tag, a parse error will be generated. A term may belong to any number of subsets. """ def __init__(self): pass class MissingRequiredTag(OBOException): pass
en
0.671261
https://oboformat.googlecode.com/svn/trunk/doc/GO.format.obo-1_2.html#S.2.2 The value of this tag must be a subset name as defined in a subsetdef tag in the file header. If the value of this tag is not mentioned in a subsetdef tag, a parse error will be generated. A term may belong to any number of subsets.
2.570663
3
brain_brew/configuration/build_config/parts_builder.py
aplaice/brain-brew
0
6623706
from dataclasses import dataclass from typing import Dict, Type, List, Set from brain_brew.build_tasks.crowd_anki.headers_from_crowdanki import HeadersFromCrowdAnki from brain_brew.build_tasks.crowd_anki.media_group_from_crowd_anki import MediaGroupFromCrowdAnki from brain_brew.build_tasks.crowd_anki.note_models_from_crowd_anki import NoteModelsFromCrowdAnki from brain_brew.build_tasks.crowd_anki.notes_from_crowd_anki import NotesFromCrowdAnki from brain_brew.build_tasks.csvs.notes_from_csvs import NotesFromCsvs from brain_brew.build_tasks.deck_parts.from_yaml_part import NotesFromYamlPart, NoteModelsFromYamlPart, \ MediaGroupFromYamlPart from brain_brew.build_tasks.deck_parts.headers_from_yaml_part import HeadersFromYamlPart from brain_brew.build_tasks.deck_parts.media_group_from_folder import MediaGroupFromFolder from brain_brew.build_tasks.deck_parts.media_group_to_folder import MediaGroupsToFolder from brain_brew.build_tasks.deck_parts.note_model_from_html_parts import NoteModelFromHTMLParts from brain_brew.build_tasks.deck_parts.note_model_template_from_html_files import TemplateFromHTML from brain_brew.configuration.build_config.build_task import BuildTask, BuildPartTask, TopLevelBuildTask from brain_brew.configuration.build_config.recipe_builder import RecipeBuilder @dataclass class PartsBuilder(RecipeBuilder, TopLevelBuildTask): accepts_list_of_self: bool = False @classmethod def task_name(cls) -> str: return r'build_parts' @classmethod def task_regex(cls) -> str: return r'build_part[s]?' @classmethod def known_task_dict(cls) -> Dict[str, Type[BuildTask]]: return BuildPartTask.get_all_task_regex(cls.yamale_dependencies()) @classmethod def from_repr(cls, data: List[dict]): if not isinstance(data, list): raise TypeError(f"PartsBuilder needs a list") return cls.from_list(data) def encode(self) -> dict: pass @classmethod def from_yaml_file(cls, filename: str): pass @classmethod def yamale_schema(cls) -> str: return cls.build_yamale_root_node(cls.yamale_dependencies()) @classmethod def yamale_dependencies(cls) -> Set[Type[BuildPartTask]]: return { NotesFromCsvs, NotesFromYamlPart, HeadersFromYamlPart, NoteModelsFromYamlPart, MediaGroupFromYamlPart, MediaGroupFromFolder, MediaGroupsToFolder, NoteModelFromHTMLParts, TemplateFromHTML, HeadersFromCrowdAnki, MediaGroupFromCrowdAnki, NoteModelsFromCrowdAnki, NotesFromCrowdAnki }
from dataclasses import dataclass from typing import Dict, Type, List, Set from brain_brew.build_tasks.crowd_anki.headers_from_crowdanki import HeadersFromCrowdAnki from brain_brew.build_tasks.crowd_anki.media_group_from_crowd_anki import MediaGroupFromCrowdAnki from brain_brew.build_tasks.crowd_anki.note_models_from_crowd_anki import NoteModelsFromCrowdAnki from brain_brew.build_tasks.crowd_anki.notes_from_crowd_anki import NotesFromCrowdAnki from brain_brew.build_tasks.csvs.notes_from_csvs import NotesFromCsvs from brain_brew.build_tasks.deck_parts.from_yaml_part import NotesFromYamlPart, NoteModelsFromYamlPart, \ MediaGroupFromYamlPart from brain_brew.build_tasks.deck_parts.headers_from_yaml_part import HeadersFromYamlPart from brain_brew.build_tasks.deck_parts.media_group_from_folder import MediaGroupFromFolder from brain_brew.build_tasks.deck_parts.media_group_to_folder import MediaGroupsToFolder from brain_brew.build_tasks.deck_parts.note_model_from_html_parts import NoteModelFromHTMLParts from brain_brew.build_tasks.deck_parts.note_model_template_from_html_files import TemplateFromHTML from brain_brew.configuration.build_config.build_task import BuildTask, BuildPartTask, TopLevelBuildTask from brain_brew.configuration.build_config.recipe_builder import RecipeBuilder @dataclass class PartsBuilder(RecipeBuilder, TopLevelBuildTask): accepts_list_of_self: bool = False @classmethod def task_name(cls) -> str: return r'build_parts' @classmethod def task_regex(cls) -> str: return r'build_part[s]?' @classmethod def known_task_dict(cls) -> Dict[str, Type[BuildTask]]: return BuildPartTask.get_all_task_regex(cls.yamale_dependencies()) @classmethod def from_repr(cls, data: List[dict]): if not isinstance(data, list): raise TypeError(f"PartsBuilder needs a list") return cls.from_list(data) def encode(self) -> dict: pass @classmethod def from_yaml_file(cls, filename: str): pass @classmethod def yamale_schema(cls) -> str: return cls.build_yamale_root_node(cls.yamale_dependencies()) @classmethod def yamale_dependencies(cls) -> Set[Type[BuildPartTask]]: return { NotesFromCsvs, NotesFromYamlPart, HeadersFromYamlPart, NoteModelsFromYamlPart, MediaGroupFromYamlPart, MediaGroupFromFolder, MediaGroupsToFolder, NoteModelFromHTMLParts, TemplateFromHTML, HeadersFromCrowdAnki, MediaGroupFromCrowdAnki, NoteModelsFromCrowdAnki, NotesFromCrowdAnki }
none
1
1.957746
2
chapter04/base_orm_operate/book/models.py
Tomtao626/django
0
6623707
from django.db import models # Create your models here. class Book(models.Model): """ 图书 """ name = models.CharField(max_length=100, null=False) author = models.CharField(max_length=100, null=False) price = models.FloatField(default=0) def __str__(self): # <Book:(name,author,price)> return f"<Book:({self.name},{self.author},{self.price})>"
from django.db import models # Create your models here. class Book(models.Model): """ 图书 """ name = models.CharField(max_length=100, null=False) author = models.CharField(max_length=100, null=False) price = models.FloatField(default=0) def __str__(self): # <Book:(name,author,price)> return f"<Book:({self.name},{self.author},{self.price})>"
en
0.75541
# Create your models here. 图书 # <Book:(name,author,price)>
2.992257
3
domains.py
Yepoleb/gv.at
1
6623708
import csv import jinja2 with open("gv.at.csv") as csvfile: reader = csv.reader(csvfile) next(reader) rows = list(reader) domains = set(r[2] for r in rows) filtdomains = set() for dom in domains: if '@' in dom: continue if dom.startswith("*") and dom[2:] in domains: continue elif "www." + dom in domains: continue filtdomains.add(dom) sortdomains = list(filtdomains) sortdomains.sort(key=lambda d: tuple(reversed(d.split(".")))) template = jinja2.Template(open("domainlist_tmpl.html").read()) site = template.render(domains=sortdomains) with open("domainlist.html", "w") as domainlist: domainlist.write(site)
import csv import jinja2 with open("gv.at.csv") as csvfile: reader = csv.reader(csvfile) next(reader) rows = list(reader) domains = set(r[2] for r in rows) filtdomains = set() for dom in domains: if '@' in dom: continue if dom.startswith("*") and dom[2:] in domains: continue elif "www." + dom in domains: continue filtdomains.add(dom) sortdomains = list(filtdomains) sortdomains.sort(key=lambda d: tuple(reversed(d.split(".")))) template = jinja2.Template(open("domainlist_tmpl.html").read()) site = template.render(domains=sortdomains) with open("domainlist.html", "w") as domainlist: domainlist.write(site)
none
1
3.107192
3
bin/params/con.py
chapochn/ORN-LN_circuit
1
6623709
<filename>bin/params/con.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 30 14:24:44 2017 @author: <NAME> """ file_L = 'data/Berck_2016/elife-14859-supp1-v2_no_blanks.xlsx' file_R = 'data/Berck_2016/elife-14859-supp2-v2_no_blanks.xlsx' # this is some information from the excel sheet # not sure if it is meaningful to put it here, or somewhere else # or to read out from some parameter file. Let's leave it here for the moment ORN_begin = 2 ORN_end = 22 ORN_n = ORN_end - ORN_begin + 1 uPN_begin = 23 uPN_end = 44 uPN_n = uPN_end - uPN_begin + 1 Broad_begin = 45 Broad_end = 49 Broad_n = Broad_end - Broad_begin + 1 Picky_begin = 52 Picky_end = 61 Picky_n = Picky_end - Picky_begin + 1 Choosy_begin = 62 Choosy_end = 65 Choosy_n = Choosy_end - Choosy_begin + 1 mPN_begin = 67 mPN_end = 84 mPN_n = mPN_end - mPN_begin + 1 all_begin = 2 all_end = 97 all_n = all_end - all_begin + 1 ORN = ['1a', '13a', '22c', '24a', '30a', '33a', '35a', '42a', '42b', '45a', '45b', '33b/47a', '49a', '59a', '63a', '67b', '74a', '82a', '83a', '85c', '94a/94b'] ORN = ['ORN ' + name for name in ORN] ORN_L = [name + ' L' for name in ORN] ORN_R = [name + ' R' for name in ORN] ORN_A = [name + ' L&R' for name in ORN] # A being all uPN = ['1a', '13a', '22c', '24a', '30a', '33a', '35a bil. L', '35a bil. R', '42a', '42b', '45a', '45b', '33b/47a', '49a', '59a', '63a', '67b', '74a', '82a', '83a', '85c', '94a/94b'] uPN_merg = ['1a', '13a', '22c', '24a', '30a', '33a', '35a bil. L', '42a', '42b', '45a', '45b', '33b/47a', '49a', '59a', '63a', '67b', '74a', '82a', '83a', '85c', '94a/94b'] uPN = ['PN ' + name for name in uPN] uPN_merg = ['PN ' + name for name in uPN_merg] LN = ['Broad T1', 'Broad T2', 'Broad T3', 'Broad D1', 'Broad D2', 'Keystone L', 'Keystone R', 'Picky 0 [dend]', 'Picky 0 [axon]', 'Picky 1 [dend]', 'Picky 1 [axon]', 'Picky 2 [dend]', 'Picky 2 [axon]', 'Picky 3 [dend]', 'Picky 3 [axon]', 'Picky 4 [dend]', 'Picky 4 [axon]', 'Choosy 1 [dend]', 'Choosy 1 [axon]', 'Choosy 2 [dend]', 'Choosy 2 [axon]', 'Ventral LN'] dict_str_replace = {'47a & 33b': '33b/47a', '94a & 94b': '94a/94b'}
<filename>bin/params/con.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 30 14:24:44 2017 @author: <NAME> """ file_L = 'data/Berck_2016/elife-14859-supp1-v2_no_blanks.xlsx' file_R = 'data/Berck_2016/elife-14859-supp2-v2_no_blanks.xlsx' # this is some information from the excel sheet # not sure if it is meaningful to put it here, or somewhere else # or to read out from some parameter file. Let's leave it here for the moment ORN_begin = 2 ORN_end = 22 ORN_n = ORN_end - ORN_begin + 1 uPN_begin = 23 uPN_end = 44 uPN_n = uPN_end - uPN_begin + 1 Broad_begin = 45 Broad_end = 49 Broad_n = Broad_end - Broad_begin + 1 Picky_begin = 52 Picky_end = 61 Picky_n = Picky_end - Picky_begin + 1 Choosy_begin = 62 Choosy_end = 65 Choosy_n = Choosy_end - Choosy_begin + 1 mPN_begin = 67 mPN_end = 84 mPN_n = mPN_end - mPN_begin + 1 all_begin = 2 all_end = 97 all_n = all_end - all_begin + 1 ORN = ['1a', '13a', '22c', '24a', '30a', '33a', '35a', '42a', '42b', '45a', '45b', '33b/47a', '49a', '59a', '63a', '67b', '74a', '82a', '83a', '85c', '94a/94b'] ORN = ['ORN ' + name for name in ORN] ORN_L = [name + ' L' for name in ORN] ORN_R = [name + ' R' for name in ORN] ORN_A = [name + ' L&R' for name in ORN] # A being all uPN = ['1a', '13a', '22c', '24a', '30a', '33a', '35a bil. L', '35a bil. R', '42a', '42b', '45a', '45b', '33b/47a', '49a', '59a', '63a', '67b', '74a', '82a', '83a', '85c', '94a/94b'] uPN_merg = ['1a', '13a', '22c', '24a', '30a', '33a', '35a bil. L', '42a', '42b', '45a', '45b', '33b/47a', '49a', '59a', '63a', '67b', '74a', '82a', '83a', '85c', '94a/94b'] uPN = ['PN ' + name for name in uPN] uPN_merg = ['PN ' + name for name in uPN_merg] LN = ['Broad T1', 'Broad T2', 'Broad T3', 'Broad D1', 'Broad D2', 'Keystone L', 'Keystone R', 'Picky 0 [dend]', 'Picky 0 [axon]', 'Picky 1 [dend]', 'Picky 1 [axon]', 'Picky 2 [dend]', 'Picky 2 [axon]', 'Picky 3 [dend]', 'Picky 3 [axon]', 'Picky 4 [dend]', 'Picky 4 [axon]', 'Choosy 1 [dend]', 'Choosy 1 [axon]', 'Choosy 2 [dend]', 'Choosy 2 [axon]', 'Ventral LN'] dict_str_replace = {'47a & 33b': '33b/47a', '94a & 94b': '94a/94b'}
en
0.856579
#!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Thu Nov 30 14:24:44 2017 @author: <NAME> # this is some information from the excel sheet # not sure if it is meaningful to put it here, or somewhere else # or to read out from some parameter file. Let's leave it here for the moment # A being all
2.425056
2
swagger_client/models/market_filter.py
akxlr/bf-stream-py
0
6623710
<gh_stars>0 # coding: utf-8 """ Betfair: Exchange Streaming API API to receive streamed updates. This is an ssl socket connection of CRLF delimited json messages (see RequestMessage & ResponseMessage) OpenAPI spec version: 1.0.1423 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pprint import pformat from six import iteritems import re class MarketFilter(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ MarketFilter - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'country_codes': 'list[str]', 'betting_types': 'list[str]', 'turn_in_play_enabled': 'bool', 'market_types': 'list[str]', 'venues': 'list[str]', 'market_ids': 'list[str]', 'event_type_ids': 'list[str]', 'event_ids': 'list[str]', 'bsp_market': 'bool' } self.attribute_map = { 'country_codes': 'countryCodes', 'betting_types': 'bettingTypes', 'turn_in_play_enabled': 'turnInPlayEnabled', 'market_types': 'marketTypes', 'venues': 'venues', 'market_ids': 'marketIds', 'event_type_ids': 'eventTypeIds', 'event_ids': 'eventIds', 'bsp_market': 'bspMarket' } self._country_codes = None self._betting_types = None self._turn_in_play_enabled = None self._market_types = None self._venues = None self._market_ids = None self._event_type_ids = None self._event_ids = None self._bsp_market = None @property def country_codes(self): """ Gets the country_codes of this MarketFilter. :return: The country_codes of this MarketFilter. :rtype: list[str] """ return self._country_codes @country_codes.setter def country_codes(self, country_codes): """ Sets the country_codes of this MarketFilter. :param country_codes: The country_codes of this MarketFilter. :type: list[str] """ self._country_codes = country_codes @property def betting_types(self): """ Gets the betting_types of this MarketFilter. :return: The betting_types of this MarketFilter. :rtype: list[str] """ return self._betting_types @betting_types.setter def betting_types(self, betting_types): """ Sets the betting_types of this MarketFilter. :param betting_types: The betting_types of this MarketFilter. :type: list[str] """ self._betting_types = betting_types @property def turn_in_play_enabled(self): """ Gets the turn_in_play_enabled of this MarketFilter. :return: The turn_in_play_enabled of this MarketFilter. :rtype: bool """ return self._turn_in_play_enabled @turn_in_play_enabled.setter def turn_in_play_enabled(self, turn_in_play_enabled): """ Sets the turn_in_play_enabled of this MarketFilter. :param turn_in_play_enabled: The turn_in_play_enabled of this MarketFilter. :type: bool """ self._turn_in_play_enabled = turn_in_play_enabled @property def market_types(self): """ Gets the market_types of this MarketFilter. :return: The market_types of this MarketFilter. :rtype: list[str] """ return self._market_types @market_types.setter def market_types(self, market_types): """ Sets the market_types of this MarketFilter. :param market_types: The market_types of this MarketFilter. :type: list[str] """ self._market_types = market_types @property def venues(self): """ Gets the venues of this MarketFilter. :return: The venues of this MarketFilter. :rtype: list[str] """ return self._venues @venues.setter def venues(self, venues): """ Sets the venues of this MarketFilter. :param venues: The venues of this MarketFilter. :type: list[str] """ self._venues = venues @property def market_ids(self): """ Gets the market_ids of this MarketFilter. :return: The market_ids of this MarketFilter. :rtype: list[str] """ return self._market_ids @market_ids.setter def market_ids(self, market_ids): """ Sets the market_ids of this MarketFilter. :param market_ids: The market_ids of this MarketFilter. :type: list[str] """ self._market_ids = market_ids @property def event_type_ids(self): """ Gets the event_type_ids of this MarketFilter. :return: The event_type_ids of this MarketFilter. :rtype: list[str] """ return self._event_type_ids @event_type_ids.setter def event_type_ids(self, event_type_ids): """ Sets the event_type_ids of this MarketFilter. :param event_type_ids: The event_type_ids of this MarketFilter. :type: list[str] """ self._event_type_ids = event_type_ids @property def event_ids(self): """ Gets the event_ids of this MarketFilter. :return: The event_ids of this MarketFilter. :rtype: list[str] """ return self._event_ids @event_ids.setter def event_ids(self, event_ids): """ Sets the event_ids of this MarketFilter. :param event_ids: The event_ids of this MarketFilter. :type: list[str] """ self._event_ids = event_ids @property def bsp_market(self): """ Gets the bsp_market of this MarketFilter. :return: The bsp_market of this MarketFilter. :rtype: bool """ return self._bsp_market @bsp_market.setter def bsp_market(self, bsp_market): """ Sets the bsp_market of this MarketFilter. :param bsp_market: The bsp_market of this MarketFilter. :type: bool """ self._bsp_market = bsp_market def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
# coding: utf-8 """ Betfair: Exchange Streaming API API to receive streamed updates. This is an ssl socket connection of CRLF delimited json messages (see RequestMessage & ResponseMessage) OpenAPI spec version: 1.0.1423 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pprint import pformat from six import iteritems import re class MarketFilter(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ MarketFilter - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'country_codes': 'list[str]', 'betting_types': 'list[str]', 'turn_in_play_enabled': 'bool', 'market_types': 'list[str]', 'venues': 'list[str]', 'market_ids': 'list[str]', 'event_type_ids': 'list[str]', 'event_ids': 'list[str]', 'bsp_market': 'bool' } self.attribute_map = { 'country_codes': 'countryCodes', 'betting_types': 'bettingTypes', 'turn_in_play_enabled': 'turnInPlayEnabled', 'market_types': 'marketTypes', 'venues': 'venues', 'market_ids': 'marketIds', 'event_type_ids': 'eventTypeIds', 'event_ids': 'eventIds', 'bsp_market': 'bspMarket' } self._country_codes = None self._betting_types = None self._turn_in_play_enabled = None self._market_types = None self._venues = None self._market_ids = None self._event_type_ids = None self._event_ids = None self._bsp_market = None @property def country_codes(self): """ Gets the country_codes of this MarketFilter. :return: The country_codes of this MarketFilter. :rtype: list[str] """ return self._country_codes @country_codes.setter def country_codes(self, country_codes): """ Sets the country_codes of this MarketFilter. :param country_codes: The country_codes of this MarketFilter. :type: list[str] """ self._country_codes = country_codes @property def betting_types(self): """ Gets the betting_types of this MarketFilter. :return: The betting_types of this MarketFilter. :rtype: list[str] """ return self._betting_types @betting_types.setter def betting_types(self, betting_types): """ Sets the betting_types of this MarketFilter. :param betting_types: The betting_types of this MarketFilter. :type: list[str] """ self._betting_types = betting_types @property def turn_in_play_enabled(self): """ Gets the turn_in_play_enabled of this MarketFilter. :return: The turn_in_play_enabled of this MarketFilter. :rtype: bool """ return self._turn_in_play_enabled @turn_in_play_enabled.setter def turn_in_play_enabled(self, turn_in_play_enabled): """ Sets the turn_in_play_enabled of this MarketFilter. :param turn_in_play_enabled: The turn_in_play_enabled of this MarketFilter. :type: bool """ self._turn_in_play_enabled = turn_in_play_enabled @property def market_types(self): """ Gets the market_types of this MarketFilter. :return: The market_types of this MarketFilter. :rtype: list[str] """ return self._market_types @market_types.setter def market_types(self, market_types): """ Sets the market_types of this MarketFilter. :param market_types: The market_types of this MarketFilter. :type: list[str] """ self._market_types = market_types @property def venues(self): """ Gets the venues of this MarketFilter. :return: The venues of this MarketFilter. :rtype: list[str] """ return self._venues @venues.setter def venues(self, venues): """ Sets the venues of this MarketFilter. :param venues: The venues of this MarketFilter. :type: list[str] """ self._venues = venues @property def market_ids(self): """ Gets the market_ids of this MarketFilter. :return: The market_ids of this MarketFilter. :rtype: list[str] """ return self._market_ids @market_ids.setter def market_ids(self, market_ids): """ Sets the market_ids of this MarketFilter. :param market_ids: The market_ids of this MarketFilter. :type: list[str] """ self._market_ids = market_ids @property def event_type_ids(self): """ Gets the event_type_ids of this MarketFilter. :return: The event_type_ids of this MarketFilter. :rtype: list[str] """ return self._event_type_ids @event_type_ids.setter def event_type_ids(self, event_type_ids): """ Sets the event_type_ids of this MarketFilter. :param event_type_ids: The event_type_ids of this MarketFilter. :type: list[str] """ self._event_type_ids = event_type_ids @property def event_ids(self): """ Gets the event_ids of this MarketFilter. :return: The event_ids of this MarketFilter. :rtype: list[str] """ return self._event_ids @event_ids.setter def event_ids(self, event_ids): """ Sets the event_ids of this MarketFilter. :param event_ids: The event_ids of this MarketFilter. :type: list[str] """ self._event_ids = event_ids @property def bsp_market(self): """ Gets the bsp_market of this MarketFilter. :return: The bsp_market of this MarketFilter. :rtype: bool """ return self._bsp_market @bsp_market.setter def bsp_market(self, bsp_market): """ Sets the bsp_market of this MarketFilter. :param bsp_market: The bsp_market of this MarketFilter. :type: bool """ self._bsp_market = bsp_market def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
en
0.733245
# coding: utf-8 Betfair: Exchange Streaming API API to receive streamed updates. This is an ssl socket connection of CRLF delimited json messages (see RequestMessage & ResponseMessage) OpenAPI spec version: 1.0.1423 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. MarketFilter - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. Gets the country_codes of this MarketFilter. :return: The country_codes of this MarketFilter. :rtype: list[str] Sets the country_codes of this MarketFilter. :param country_codes: The country_codes of this MarketFilter. :type: list[str] Gets the betting_types of this MarketFilter. :return: The betting_types of this MarketFilter. :rtype: list[str] Sets the betting_types of this MarketFilter. :param betting_types: The betting_types of this MarketFilter. :type: list[str] Gets the turn_in_play_enabled of this MarketFilter. :return: The turn_in_play_enabled of this MarketFilter. :rtype: bool Sets the turn_in_play_enabled of this MarketFilter. :param turn_in_play_enabled: The turn_in_play_enabled of this MarketFilter. :type: bool Gets the market_types of this MarketFilter. :return: The market_types of this MarketFilter. :rtype: list[str] Sets the market_types of this MarketFilter. :param market_types: The market_types of this MarketFilter. :type: list[str] Gets the venues of this MarketFilter. :return: The venues of this MarketFilter. :rtype: list[str] Sets the venues of this MarketFilter. :param venues: The venues of this MarketFilter. :type: list[str] Gets the market_ids of this MarketFilter. :return: The market_ids of this MarketFilter. :rtype: list[str] Sets the market_ids of this MarketFilter. :param market_ids: The market_ids of this MarketFilter. :type: list[str] Gets the event_type_ids of this MarketFilter. :return: The event_type_ids of this MarketFilter. :rtype: list[str] Sets the event_type_ids of this MarketFilter. :param event_type_ids: The event_type_ids of this MarketFilter. :type: list[str] Gets the event_ids of this MarketFilter. :return: The event_ids of this MarketFilter. :rtype: list[str] Sets the event_ids of this MarketFilter. :param event_ids: The event_ids of this MarketFilter. :type: list[str] Gets the bsp_market of this MarketFilter. :return: The bsp_market of this MarketFilter. :rtype: bool Sets the bsp_market of this MarketFilter. :param bsp_market: The bsp_market of this MarketFilter. :type: bool Returns the model properties as a dict Returns the string representation of the model For `print` and `pprint` Returns true if both objects are equal Returns true if both objects are not equal
1.377378
1
week_3/string/fstring.py
mikolevy/python-zp
0
6623711
python_age = 30 # info = "Python ma już prawie: " + str(python_age) + " lat!" # info = f"Python ma już prawie {python_age} lat!" # calculation = f"Wynik działania 3 x 6 to {3 * 6}" # name = "Mikołaj" # hello = f"Nazywam się {name}"
python_age = 30 # info = "Python ma już prawie: " + str(python_age) + " lat!" # info = f"Python ma już prawie {python_age} lat!" # calculation = f"Wynik działania 3 x 6 to {3 * 6}" # name = "Mikołaj" # hello = f"Nazywam się {name}"
pl
0.767946
# info = "Python ma już prawie: " + str(python_age) + " lat!" # info = f"Python ma już prawie {python_age} lat!" # calculation = f"Wynik działania 3 x 6 to {3 * 6}" # name = "Mikołaj" # hello = f"Nazywam się {name}"
2.993298
3
social/urls.py
mashiyathussain2/SocialMediaApp
1
6623712
from django.urls import path from social import views urlpatterns = [ path('home/',views.Home.as_view()), path('post/',views.Post.as_view()), path('post/<int:pk>/like',views.PostLike.as_view()), path('post/<int:pk>/comment',views.PostComment.as_view()), path('', views.Wall.as_view()) ]
from django.urls import path from social import views urlpatterns = [ path('home/',views.Home.as_view()), path('post/',views.Post.as_view()), path('post/<int:pk>/like',views.PostLike.as_view()), path('post/<int:pk>/comment',views.PostComment.as_view()), path('', views.Wall.as_view()) ]
none
1
1.857475
2
pyppmc/notification.py
aleofreitas/pyppmc
0
6623713
# -*- coding: utf-8 -*- # Copyright 2018 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing SMTP methods. """ import smtplib from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # noinspection SpellCheckingInspection def send(host, port, rcpt_from, rcpt_to, username='', password='', starttls=False, rcpt_cc='', rcpt_bcc='', subject='', message='', mime_type='plain'): """Sends an e-mail message. Parameters ---------- host : str SMTP server. port : int SMTP server port. rcpt_from : str E-mail address of the message sender. rcpt_to : str Semicolon (;) separated list of e-mail addresses to be sent a notification via To field. username : str, optional Username to authenticate on SMTP server. password : str, optional Password of the username to authenticate on SMTP server. Required if username is informed. starttls : bool, optional Flag to indicate if the connection to the SMTP server must use STARTTLS or not. Default is False (do not use). rcpt_cc : str, optional Semicolon (;) separated list of e-mail addresses to be sent a notification via Cc field. rcpt_bcc : str, optional Semicolon (;) separated list of e-mail addresses to be sent a notification via Bcc field. subject : str, optional Message subject. message : str, optional Body of the message. Accepts HTML content. mime_type : str, optional Message MIME Type. Must be 'plain' or 'html'. Default is 'plain' Returns ------- dict Refused recipients. """ if mime_type not in ['plain', 'html']: raise ValueError("Invalid MIME type: %s. Valid values are: 'plain', 'html'.") msg = MIMEMultipart('alternative') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = rcpt_from msg['To'] = rcpt_to msg['Cc'] = rcpt_cc contents = MIMEText(message, mime_type, 'utf-8') msg.attach(contents) server = smtplib.SMTP(host, port) if starttls: server.starttls() if username != '' and password != '': server.login(username, password) server.set_debuglevel(False) try: rcpt = list(set(rcpt_to.split(';') + rcpt_cc.split(';') + rcpt_bcc.split(';'))) return server.sendmail(rcpt_from, rcpt, msg.as_string()) finally: server.quit()
# -*- coding: utf-8 -*- # Copyright 2018 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing SMTP methods. """ import smtplib from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # noinspection SpellCheckingInspection def send(host, port, rcpt_from, rcpt_to, username='', password='', starttls=False, rcpt_cc='', rcpt_bcc='', subject='', message='', mime_type='plain'): """Sends an e-mail message. Parameters ---------- host : str SMTP server. port : int SMTP server port. rcpt_from : str E-mail address of the message sender. rcpt_to : str Semicolon (;) separated list of e-mail addresses to be sent a notification via To field. username : str, optional Username to authenticate on SMTP server. password : str, optional Password of the username to authenticate on SMTP server. Required if username is informed. starttls : bool, optional Flag to indicate if the connection to the SMTP server must use STARTTLS or not. Default is False (do not use). rcpt_cc : str, optional Semicolon (;) separated list of e-mail addresses to be sent a notification via Cc field. rcpt_bcc : str, optional Semicolon (;) separated list of e-mail addresses to be sent a notification via Bcc field. subject : str, optional Message subject. message : str, optional Body of the message. Accepts HTML content. mime_type : str, optional Message MIME Type. Must be 'plain' or 'html'. Default is 'plain' Returns ------- dict Refused recipients. """ if mime_type not in ['plain', 'html']: raise ValueError("Invalid MIME type: %s. Valid values are: 'plain', 'html'.") msg = MIMEMultipart('alternative') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = rcpt_from msg['To'] = rcpt_to msg['Cc'] = rcpt_cc contents = MIMEText(message, mime_type, 'utf-8') msg.attach(contents) server = smtplib.SMTP(host, port) if starttls: server.starttls() if username != '' and password != '': server.login(username, password) server.set_debuglevel(False) try: rcpt = list(set(rcpt_to.split(';') + rcpt_cc.split(';') + rcpt_bcc.split(';'))) return server.sendmail(rcpt_from, rcpt, msg.as_string()) finally: server.quit()
en
0.633535
# -*- coding: utf-8 -*- # Copyright 2018 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Module containing SMTP methods. # noinspection SpellCheckingInspection Sends an e-mail message. Parameters ---------- host : str SMTP server. port : int SMTP server port. rcpt_from : str E-mail address of the message sender. rcpt_to : str Semicolon (;) separated list of e-mail addresses to be sent a notification via To field. username : str, optional Username to authenticate on SMTP server. password : str, optional Password of the username to authenticate on SMTP server. Required if username is informed. starttls : bool, optional Flag to indicate if the connection to the SMTP server must use STARTTLS or not. Default is False (do not use). rcpt_cc : str, optional Semicolon (;) separated list of e-mail addresses to be sent a notification via Cc field. rcpt_bcc : str, optional Semicolon (;) separated list of e-mail addresses to be sent a notification via Bcc field. subject : str, optional Message subject. message : str, optional Body of the message. Accepts HTML content. mime_type : str, optional Message MIME Type. Must be 'plain' or 'html'. Default is 'plain' Returns ------- dict Refused recipients.
2.377278
2
nlp_demo/seomap/TextTool.py
maliozer/cs224n
0
6623714
import sys assert sys.version_info[0]==3 assert sys.version_info[1] >= 5 from gensim.models import KeyedVectors from gensim.test.utils import datapath import pprint import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [10, 5] import numpy as np import random import scipy as sp from sklearn.decomposition import TruncatedSVD from sklearn.decomposition import PCA START_TOKEN = '<START>' END_TOKEN = '<END>' np.random.seed(0) random.seed(0) def get_sentences(text): text_list = text.split('.') text_words_list = [d.split(' ') for d in text_list] return text_words_list def get_words(documents): return [[START_TOKEN] + [w.lower() for w in d] + [END_TOKEN] for d in documents]
import sys assert sys.version_info[0]==3 assert sys.version_info[1] >= 5 from gensim.models import KeyedVectors from gensim.test.utils import datapath import pprint import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [10, 5] import numpy as np import random import scipy as sp from sklearn.decomposition import TruncatedSVD from sklearn.decomposition import PCA START_TOKEN = '<START>' END_TOKEN = '<END>' np.random.seed(0) random.seed(0) def get_sentences(text): text_list = text.split('.') text_words_list = [d.split(' ') for d in text_list] return text_words_list def get_words(documents): return [[START_TOKEN] + [w.lower() for w in d] + [END_TOKEN] for d in documents]
none
1
2.422242
2
reduce.py
axipher/palette-reducer-inputs
1
6623715
# dependencies import matplotlib.pyplot as pyplot from PIL import Image import os import time import math import numpy import sklearn.cluster import sklearn.preprocessing import sys, getopt import ntpath def main(argv): tic = time.perf_counter() # Waifu2x-caffe available from: https://github.com/lltcggie/waifu2x-caffe/releases waifuPath = "C:\Programs\waifu2x-caffe\waifu2x-caffe-cui.exe" waifuOptionsPre = '-i ' waifuOptionsMid = ' -o ' waifuOptionsPost = ' -p cpu -mode_dir --model_dir\\upconv_7_anime_style_art_rgb' # -mode_dir options # models\anime_style_art_rgb: 2-dimensional image model for converting all RGB # models\anime_style_art: model for two-dimensional image that converts only luminance # models\photo: Photos that convert all RGB, models for animated images # models\upconv_7_anime_style_art_rgb: Anime_style_art_rgb A model to convert at higher speed and equal or higher image quality # models\upconv_7_photo: A model that converts with higher image quality than the photo at higher speed # models\ukbench: old-fashioned model for photography (only models that are enlarged are attached, noise can not be removed) # OptiPNG available from: http://optipng.sourceforge.net/ optiPNGPath = "C:\Programs\optipng-0.7.7-win32\optipng.exe" optiPNGOptionsPre = '' optiPNGOptionsMid = ' -out ' optiPNGOptionsPost = ' -clobber' # Put the EXACT filename you uploaded between the quotes # Can be set using '-i <inputfile>' option filename = 'photo2.jpg' #filename = 'slime_000195.png' # The number of colors you want in the final image # Can be changed using the '-p <palette-size>' option targetColors = 16 # Default output file # The output file uses the base file name # The Target Colour count can be appended to the filename using the '-a' option # The output file will be a PNG # Can be set using '-o <outputfile>' option and will be corrected to a PNG outfile = '' # this seed keeps the algorithm deterministic # you can change it to a different number if you want seed = 0xabad1dea inputfile = '' outputfile = '' palettesize = '' append = 'false' speedUp = 'false' print('') print('Palette Reducer with inputs!') print('---------------------------------------') print('Orignal code by 0xabad1dea') print(' Modified by Axipher and NavJack27') print('') print('') if not os.path.exists('reduced'): os.makedirs('reduced') if not os.path.exists('reduced\\' + str(targetColors)): os.makedirs('reduced\\' + str(targetColors)) try: opts, args = getopt.getopt(argv,"hi:o:p:as",["ifile=","ofile=","psize="]) except getopt.GetoptError: print('reduce.py can be used like this:') print('reduce.py -i <inputfile> -o <outputfile> -p <palette-size> -a -s') sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): print('reduce.py can be used like this:') print('reduce.py -i <inputfile> -o <outputfile> -p <palette-size> -a -s') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg filename = inputfile elif opt in ("-o", "--ofile"): outputfile = arg outfile = outputfile elif opt in ("-p", "--psize"): palettesize = arg targetColors = int(palettesize) elif opt in ("-a", "--append"): append = 'true' elif opt in ("-s", "--speed-up"): speedUp = 'true' if outfile == '': outfile = 'reduced\\' + str(targetColors) + '\\' + ntpath.basename(os.path.splitext(filename)[0]) else: outfile = 'reduced\\' + str(targetColors) + '\\' + ntpath.basename(os.path.splitext(outputfile)[0]) if append == 'true': outfile = outfile + '-' + str(targetColors) outfileWaifu = outfile + '_waifu2x.png' outfileoptiPNG = outfile + '_optiPNG.png' outfile = outfile + '.png' if len(opts) == 0: print('Number of opts',len(opts)) print('') print('reduce.py can be used like this:') print('reduce.py -i <inputfile> -o <outputfile> -p <palette-size> -a') print('') print('') print(f"Input file is '{filename}'") print(f"Output file is '{outfile}'") print(f"palette size is '{targetColors}'") print('') # massage the file into a consistent colorspace # (if one skips the convert("RGB"), some images # will work fine and others not at all) print('Attempting to load image:') print(filename) print('') im = Image.open(filename) # Provide the target width and height of the image and resize it 50% (width, height) = (im.width, im.height) print(f"Input Image: {outfile}") print(f"Dimensions: {width}x{height}") source = im if speedUp == 'true': (width_5, height_5) = (width // 2, height // 2) source = im.resize((width_5, height_5)) (width2, height2) = (source.width, source.height) print(f"Halved dimensions: {width2}x{height2}") source = source.convert("RGB") source = numpy.asarray(source) # throw out the alpha channel if present # (will screw up the palette reduction otherwise) source = source[:,:,:3] sourcecolors = numpy.unique(source.reshape(-1, source.shape[2]), axis=0) # print(sourcecolors) print(f"Number of colors in original: {len(sourcecolors)}") print('') # pitch a fit if the image is already below target color count assert(len(sourcecolors) >= targetColors) pyplot.axis("off") # pyplot.imshow(source, interpolation="none") # the actual magic # basically, what this does is create n pixel clusters that work like galaxies # and at the end, every pixel takes the color at the heart of its own galaxy. # this is better than "just take the n most common pixel values" because # the cluster galaxies are ~evenly spaced through the colors used, while # just taking the n most common can miss large ranges of the color space sourceArray = source.reshape(-1, 3) simplifier = sklearn.cluster.KMeans(n_clusters=targetColors, random_state=seed).fit(sourceArray) simplifiedSource = simplifier.cluster_centers_[simplifier.labels_] simplifiedSource = simplifiedSource.reshape(source.shape) #print("Result palette:") #print(simplifier.cluster_centers_) #print('') #print("\n\n➡️THIS IS A PREVIEW THUMBNAIL.⬅️\nYOUR RESULT IS IN palette-result.png IN THE FILE BROWSER ON THE LEFT.") #print("YOU MAY NEED TO CLICK THE REFRESH-FOLDER ICON TO SEE IT.") pyplot.axis("off") # pyplot.imshow(simplifiedSource.astype(numpy.uint8), interpolation="none") print('Attempting to write new image:') print(outfile) print('') pyplot.imsave(fname=outfile, arr=simplifiedSource.astype(numpy.uint8), format='png') toc = time.perf_counter() print(f"Reduced the palette in {toc - tic:0.4f} seconds") print('') tic = time.perf_counter() print("Attempting Waifu2x-caffe transformation with 2x scale") waifuOptions = waifuOptionsPre + outfile + waifuOptionsMid + outfileWaifu + waifuOptionsPost if speedUp == 'true': waifuOptions = waifuOptions + ' -s 2.0' if speedUp == 'false': waifuOptions = waifuOptions + ' -s 1.0' print(f"Command: {waifuPath}") print(f"Options: {waifuOptions}") os.system(waifuPath + " " + waifuOptions) toc = time.perf_counter() print(f"Ran through Waifu2x-caffe in {toc - tic:0.4f} seconds") print('') tic = time.perf_counter() print("Attempting optiPNG processing") #optiPNGOptions = optiPNGOptionsPre + outfileWaifu + optiPNGOptionsMid + outfileoptiPNG + optiPNGOptionsPost optiPNGOptions = optiPNGOptionsPre + outfileWaifu + optiPNGOptionsPost print(f"Command: {optiPNGPath}") print(f"Options: {optiPNGOptions}") os.system(optiPNGPath + " " + optiPNGOptions) toc = time.perf_counter() print(f"Ran through OptiPNG in {toc - tic:0.4f} seconds") print('') # Provide the target width and height of the final image imFinal = Image.open(filename) (widthFinal, heightFinal) = (imFinal.width, imFinal.height) print(f"Final Image: {outfileoptiPNG}") print(f"Dimensions: {widthFinal}x{heightFinal}") if __name__ == "__main__": main(sys.argv[1:])
# dependencies import matplotlib.pyplot as pyplot from PIL import Image import os import time import math import numpy import sklearn.cluster import sklearn.preprocessing import sys, getopt import ntpath def main(argv): tic = time.perf_counter() # Waifu2x-caffe available from: https://github.com/lltcggie/waifu2x-caffe/releases waifuPath = "C:\Programs\waifu2x-caffe\waifu2x-caffe-cui.exe" waifuOptionsPre = '-i ' waifuOptionsMid = ' -o ' waifuOptionsPost = ' -p cpu -mode_dir --model_dir\\upconv_7_anime_style_art_rgb' # -mode_dir options # models\anime_style_art_rgb: 2-dimensional image model for converting all RGB # models\anime_style_art: model for two-dimensional image that converts only luminance # models\photo: Photos that convert all RGB, models for animated images # models\upconv_7_anime_style_art_rgb: Anime_style_art_rgb A model to convert at higher speed and equal or higher image quality # models\upconv_7_photo: A model that converts with higher image quality than the photo at higher speed # models\ukbench: old-fashioned model for photography (only models that are enlarged are attached, noise can not be removed) # OptiPNG available from: http://optipng.sourceforge.net/ optiPNGPath = "C:\Programs\optipng-0.7.7-win32\optipng.exe" optiPNGOptionsPre = '' optiPNGOptionsMid = ' -out ' optiPNGOptionsPost = ' -clobber' # Put the EXACT filename you uploaded between the quotes # Can be set using '-i <inputfile>' option filename = 'photo2.jpg' #filename = 'slime_000195.png' # The number of colors you want in the final image # Can be changed using the '-p <palette-size>' option targetColors = 16 # Default output file # The output file uses the base file name # The Target Colour count can be appended to the filename using the '-a' option # The output file will be a PNG # Can be set using '-o <outputfile>' option and will be corrected to a PNG outfile = '' # this seed keeps the algorithm deterministic # you can change it to a different number if you want seed = 0xabad1dea inputfile = '' outputfile = '' palettesize = '' append = 'false' speedUp = 'false' print('') print('Palette Reducer with inputs!') print('---------------------------------------') print('Orignal code by 0xabad1dea') print(' Modified by Axipher and NavJack27') print('') print('') if not os.path.exists('reduced'): os.makedirs('reduced') if not os.path.exists('reduced\\' + str(targetColors)): os.makedirs('reduced\\' + str(targetColors)) try: opts, args = getopt.getopt(argv,"hi:o:p:as",["ifile=","ofile=","psize="]) except getopt.GetoptError: print('reduce.py can be used like this:') print('reduce.py -i <inputfile> -o <outputfile> -p <palette-size> -a -s') sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): print('reduce.py can be used like this:') print('reduce.py -i <inputfile> -o <outputfile> -p <palette-size> -a -s') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg filename = inputfile elif opt in ("-o", "--ofile"): outputfile = arg outfile = outputfile elif opt in ("-p", "--psize"): palettesize = arg targetColors = int(palettesize) elif opt in ("-a", "--append"): append = 'true' elif opt in ("-s", "--speed-up"): speedUp = 'true' if outfile == '': outfile = 'reduced\\' + str(targetColors) + '\\' + ntpath.basename(os.path.splitext(filename)[0]) else: outfile = 'reduced\\' + str(targetColors) + '\\' + ntpath.basename(os.path.splitext(outputfile)[0]) if append == 'true': outfile = outfile + '-' + str(targetColors) outfileWaifu = outfile + '_waifu2x.png' outfileoptiPNG = outfile + '_optiPNG.png' outfile = outfile + '.png' if len(opts) == 0: print('Number of opts',len(opts)) print('') print('reduce.py can be used like this:') print('reduce.py -i <inputfile> -o <outputfile> -p <palette-size> -a') print('') print('') print(f"Input file is '{filename}'") print(f"Output file is '{outfile}'") print(f"palette size is '{targetColors}'") print('') # massage the file into a consistent colorspace # (if one skips the convert("RGB"), some images # will work fine and others not at all) print('Attempting to load image:') print(filename) print('') im = Image.open(filename) # Provide the target width and height of the image and resize it 50% (width, height) = (im.width, im.height) print(f"Input Image: {outfile}") print(f"Dimensions: {width}x{height}") source = im if speedUp == 'true': (width_5, height_5) = (width // 2, height // 2) source = im.resize((width_5, height_5)) (width2, height2) = (source.width, source.height) print(f"Halved dimensions: {width2}x{height2}") source = source.convert("RGB") source = numpy.asarray(source) # throw out the alpha channel if present # (will screw up the palette reduction otherwise) source = source[:,:,:3] sourcecolors = numpy.unique(source.reshape(-1, source.shape[2]), axis=0) # print(sourcecolors) print(f"Number of colors in original: {len(sourcecolors)}") print('') # pitch a fit if the image is already below target color count assert(len(sourcecolors) >= targetColors) pyplot.axis("off") # pyplot.imshow(source, interpolation="none") # the actual magic # basically, what this does is create n pixel clusters that work like galaxies # and at the end, every pixel takes the color at the heart of its own galaxy. # this is better than "just take the n most common pixel values" because # the cluster galaxies are ~evenly spaced through the colors used, while # just taking the n most common can miss large ranges of the color space sourceArray = source.reshape(-1, 3) simplifier = sklearn.cluster.KMeans(n_clusters=targetColors, random_state=seed).fit(sourceArray) simplifiedSource = simplifier.cluster_centers_[simplifier.labels_] simplifiedSource = simplifiedSource.reshape(source.shape) #print("Result palette:") #print(simplifier.cluster_centers_) #print('') #print("\n\n➡️THIS IS A PREVIEW THUMBNAIL.⬅️\nYOUR RESULT IS IN palette-result.png IN THE FILE BROWSER ON THE LEFT.") #print("YOU MAY NEED TO CLICK THE REFRESH-FOLDER ICON TO SEE IT.") pyplot.axis("off") # pyplot.imshow(simplifiedSource.astype(numpy.uint8), interpolation="none") print('Attempting to write new image:') print(outfile) print('') pyplot.imsave(fname=outfile, arr=simplifiedSource.astype(numpy.uint8), format='png') toc = time.perf_counter() print(f"Reduced the palette in {toc - tic:0.4f} seconds") print('') tic = time.perf_counter() print("Attempting Waifu2x-caffe transformation with 2x scale") waifuOptions = waifuOptionsPre + outfile + waifuOptionsMid + outfileWaifu + waifuOptionsPost if speedUp == 'true': waifuOptions = waifuOptions + ' -s 2.0' if speedUp == 'false': waifuOptions = waifuOptions + ' -s 1.0' print(f"Command: {waifuPath}") print(f"Options: {waifuOptions}") os.system(waifuPath + " " + waifuOptions) toc = time.perf_counter() print(f"Ran through Waifu2x-caffe in {toc - tic:0.4f} seconds") print('') tic = time.perf_counter() print("Attempting optiPNG processing") #optiPNGOptions = optiPNGOptionsPre + outfileWaifu + optiPNGOptionsMid + outfileoptiPNG + optiPNGOptionsPost optiPNGOptions = optiPNGOptionsPre + outfileWaifu + optiPNGOptionsPost print(f"Command: {optiPNGPath}") print(f"Options: {optiPNGOptions}") os.system(optiPNGPath + " " + optiPNGOptions) toc = time.perf_counter() print(f"Ran through OptiPNG in {toc - tic:0.4f} seconds") print('') # Provide the target width and height of the final image imFinal = Image.open(filename) (widthFinal, heightFinal) = (imFinal.width, imFinal.height) print(f"Final Image: {outfileoptiPNG}") print(f"Dimensions: {widthFinal}x{heightFinal}") if __name__ == "__main__": main(sys.argv[1:])
en
0.741393
# dependencies # Waifu2x-caffe available from: https://github.com/lltcggie/waifu2x-caffe/releases # -mode_dir options # models\anime_style_art_rgb: 2-dimensional image model for converting all RGB # models\anime_style_art: model for two-dimensional image that converts only luminance # models\photo: Photos that convert all RGB, models for animated images # models\upconv_7_anime_style_art_rgb: Anime_style_art_rgb A model to convert at higher speed and equal or higher image quality # models\upconv_7_photo: A model that converts with higher image quality than the photo at higher speed # models\ukbench: old-fashioned model for photography (only models that are enlarged are attached, noise can not be removed) # OptiPNG available from: http://optipng.sourceforge.net/ # Put the EXACT filename you uploaded between the quotes # Can be set using '-i <inputfile>' option #filename = 'slime_000195.png' # The number of colors you want in the final image # Can be changed using the '-p <palette-size>' option # Default output file # The output file uses the base file name # The Target Colour count can be appended to the filename using the '-a' option # The output file will be a PNG # Can be set using '-o <outputfile>' option and will be corrected to a PNG # this seed keeps the algorithm deterministic # you can change it to a different number if you want # massage the file into a consistent colorspace # (if one skips the convert("RGB"), some images # will work fine and others not at all) # Provide the target width and height of the image and resize it 50% # throw out the alpha channel if present # (will screw up the palette reduction otherwise) # print(sourcecolors) # pitch a fit if the image is already below target color count # pyplot.imshow(source, interpolation="none") # the actual magic # basically, what this does is create n pixel clusters that work like galaxies # and at the end, every pixel takes the color at the heart of its own galaxy. # this is better than "just take the n most common pixel values" because # the cluster galaxies are ~evenly spaced through the colors used, while # just taking the n most common can miss large ranges of the color space #print("Result palette:") #print(simplifier.cluster_centers_) #print('') #print("\n\n➡️THIS IS A PREVIEW THUMBNAIL.⬅️\nYOUR RESULT IS IN palette-result.png IN THE FILE BROWSER ON THE LEFT.") #print("YOU MAY NEED TO CLICK THE REFRESH-FOLDER ICON TO SEE IT.") # pyplot.imshow(simplifiedSource.astype(numpy.uint8), interpolation="none") #optiPNGOptions = optiPNGOptionsPre + outfileWaifu + optiPNGOptionsMid + outfileoptiPNG + optiPNGOptionsPost # Provide the target width and height of the final image
2.263386
2
example_project/example_app/models.py
liberation/django-carrier-pigeon
5
6623716
<gh_stars>1-10 # -*- coding: utf-8 -*- from django.db import models from extended_choices import Choices from carrier_pigeon.models import BasicDirtyFieldsMixin WORKFLOW_STATE = Choices( ('OFFLINE', 10, u'Hors ligne'), ('ONLINE', 20, u'En ligne'), ('DELETED', 99, u'Supprimé'), ) class Photo(models.Model): """One content illustration.""" title = models.CharField(blank=True, max_length=512) credits = models.CharField(blank=True, max_length=100) caption = models.CharField(blank=True, max_length=512) original_file = models.FileField(upload_to="photo/%Y/%m/%d", max_length=200) def __unicode__(self): return self.title class Story(models.Model, BasicDirtyFieldsMixin): """One content object of a news site.""" WORKFLOW_STATE = WORKFLOW_STATE title = models.CharField(max_length=512) workflow_state = models.PositiveSmallIntegerField( choices=WORKFLOW_STATE.CHOICES, default=WORKFLOW_STATE.OFFLINE, db_index=True ) content = models.TextField(blank=True, null=True) photo = models.ForeignKey(Photo, blank=True, null=True) updating_date = models.DateTimeField() def __unicode__(self): return self.title
# -*- coding: utf-8 -*- from django.db import models from extended_choices import Choices from carrier_pigeon.models import BasicDirtyFieldsMixin WORKFLOW_STATE = Choices( ('OFFLINE', 10, u'Hors ligne'), ('ONLINE', 20, u'En ligne'), ('DELETED', 99, u'Supprimé'), ) class Photo(models.Model): """One content illustration.""" title = models.CharField(blank=True, max_length=512) credits = models.CharField(blank=True, max_length=100) caption = models.CharField(blank=True, max_length=512) original_file = models.FileField(upload_to="photo/%Y/%m/%d", max_length=200) def __unicode__(self): return self.title class Story(models.Model, BasicDirtyFieldsMixin): """One content object of a news site.""" WORKFLOW_STATE = WORKFLOW_STATE title = models.CharField(max_length=512) workflow_state = models.PositiveSmallIntegerField( choices=WORKFLOW_STATE.CHOICES, default=WORKFLOW_STATE.OFFLINE, db_index=True ) content = models.TextField(blank=True, null=True) photo = models.ForeignKey(Photo, blank=True, null=True) updating_date = models.DateTimeField() def __unicode__(self): return self.title
en
0.693644
# -*- coding: utf-8 -*- One content illustration. One content object of a news site.
2.292847
2
pipeit/__init__.py
GoodManWEN/pipe
3
6623717
<filename>pipeit/__init__.py<gh_stars>1-10 __author__ = 'WEN (github.com/GoodManWEN)' __version__ = '' from .utils import * from .wrapper import * from .timer import timeit from .io import * __all__ = ( 'timeit', 'PIPE', 'END', 'Filter', 'Map', 'Reduce', 'Read', 'Write' )
<filename>pipeit/__init__.py<gh_stars>1-10 __author__ = 'WEN (github.com/GoodManWEN)' __version__ = '' from .utils import * from .wrapper import * from .timer import timeit from .io import * __all__ = ( 'timeit', 'PIPE', 'END', 'Filter', 'Map', 'Reduce', 'Read', 'Write' )
none
1
1.058932
1
libevent/client.py
matrix65537/lab
0
6623718
#!/usr/bin/python #coding:utf8 import socket import time IP = "127.0.0.1" PORT = 9995 max_sock_count = 100 addr = (IP, PORT) sock_list = [] for i in range(max_sock_count): print "connect", i s = socket.socket(2, 1, 0) s.connect(addr) sock_list.append(s) for i in range(max_sock_count): s = sock_list[i] s.send(b"ABCD") v = s.recv(20) print "read", i, v
#!/usr/bin/python #coding:utf8 import socket import time IP = "127.0.0.1" PORT = 9995 max_sock_count = 100 addr = (IP, PORT) sock_list = [] for i in range(max_sock_count): print "connect", i s = socket.socket(2, 1, 0) s.connect(addr) sock_list.append(s) for i in range(max_sock_count): s = sock_list[i] s.send(b"ABCD") v = s.recv(20) print "read", i, v
ru
0.160139
#!/usr/bin/python #coding:utf8
3.037764
3
app/utils.py
chushijituan/job_analysis
45
6623719
<filename>app/utils.py<gh_stars>10-100 # coding: utf-8 import traceback import logging from functools import wraps from flask import abort, current_app from werkzeug.exceptions import HTTPException logger = logging.getLogger() def handle_exception(func): ''' Since the flask does not provide a function for catching and analysing the exceptions, it's difficult that knowing what happened on the fly. If you decorate a view with this, the wrapper can handle the exceptions and log it automatically. :param func: The view function to decorate. :type func: function ''' @wraps(func) def decorated_view(*args, **kwargs): try: return func(*args, **kwargs) except HTTPException, e: raise e except Exception, e: current_app.logger.warn(traceback.format_exc()) abort(500) return decorated_view
<filename>app/utils.py<gh_stars>10-100 # coding: utf-8 import traceback import logging from functools import wraps from flask import abort, current_app from werkzeug.exceptions import HTTPException logger = logging.getLogger() def handle_exception(func): ''' Since the flask does not provide a function for catching and analysing the exceptions, it's difficult that knowing what happened on the fly. If you decorate a view with this, the wrapper can handle the exceptions and log it automatically. :param func: The view function to decorate. :type func: function ''' @wraps(func) def decorated_view(*args, **kwargs): try: return func(*args, **kwargs) except HTTPException, e: raise e except Exception, e: current_app.logger.warn(traceback.format_exc()) abort(500) return decorated_view
en
0.888474
# coding: utf-8 Since the flask does not provide a function for catching and analysing the exceptions, it's difficult that knowing what happened on the fly. If you decorate a view with this, the wrapper can handle the exceptions and log it automatically. :param func: The view function to decorate. :type func: function
2.498326
2
app/send_email.py
maxwellwachira/FastAPI-Mail
1
6623720
from fastapi import FastAPI, BackgroundTasks from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse from fastapi_mail import FastMail, MessageSchema, ConnectionConfig from starlette.responses import JSONResponse from starlette.requests import Request from decouple import config from app.models import EmailSchema from pathlib import Path #Landing page template templates = Jinja2Templates(directory=Path(__file__).parent / '../templates/') conf = ConnectionConfig( MAIL_USERNAME = config("MAIL_USERNAME"), MAIL_PASSWORD = config("<PASSWORD>"), MAIL_FROM = config("MAIL_FROM"), MAIL_PORT = config("MAIL_PORT"), MAIL_SERVER = config("MAIL_SERVER"), MAIL_TLS = config("MAIL_TLS"), MAIL_SSL = config("MAIL_SSL"), USE_CREDENTIALS = config("USE_CREDENTIALS"), VALIDATE_CERTS = config("VALIDATE_CERTS"), TEMPLATE_FOLDER = Path(__file__).parent / '../templates/email', ) app = FastAPI(title='Sending Email using FastAPI') @app.get("/", response_class=HTMLResponse, tags=["root"]) async def root(request: Request): return templates.TemplateResponse('landing_page.html', context={'request': request}) #Send Email Asynchronously @app.post("/email-async", tags=["Send Email Asynchronously"]) async def send_email_async(data: EmailSchema) -> JSONResponse: message = MessageSchema ( subject = data.subject, recipients = data.dict().get("email"), template_body=data.dict().get("body"), subtype="html" ) fm = FastMail(conf) await fm.send_message(message, template_name="email.html") return JSONResponse(status_code=200, content={"message": "Email has been sent"}) #SEnd Email using Background Tasks @app.post("/email-background", tags=["Send Email using Background Tasks"]) async def send_email_background(data: EmailSchema, background_tasks: BackgroundTasks) -> JSONResponse: message = MessageSchema ( subject = data.subject, recipients = data.dict().get("email"), template_body=data.dict().get("body"), subtype="html" ) fm = FastMail(conf) background_tasks.add_task(fm.send_message, message, template_name="email.html") return JSONResponse(status_code=200, content={"message": "Email has been sent"})
from fastapi import FastAPI, BackgroundTasks from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse from fastapi_mail import FastMail, MessageSchema, ConnectionConfig from starlette.responses import JSONResponse from starlette.requests import Request from decouple import config from app.models import EmailSchema from pathlib import Path #Landing page template templates = Jinja2Templates(directory=Path(__file__).parent / '../templates/') conf = ConnectionConfig( MAIL_USERNAME = config("MAIL_USERNAME"), MAIL_PASSWORD = config("<PASSWORD>"), MAIL_FROM = config("MAIL_FROM"), MAIL_PORT = config("MAIL_PORT"), MAIL_SERVER = config("MAIL_SERVER"), MAIL_TLS = config("MAIL_TLS"), MAIL_SSL = config("MAIL_SSL"), USE_CREDENTIALS = config("USE_CREDENTIALS"), VALIDATE_CERTS = config("VALIDATE_CERTS"), TEMPLATE_FOLDER = Path(__file__).parent / '../templates/email', ) app = FastAPI(title='Sending Email using FastAPI') @app.get("/", response_class=HTMLResponse, tags=["root"]) async def root(request: Request): return templates.TemplateResponse('landing_page.html', context={'request': request}) #Send Email Asynchronously @app.post("/email-async", tags=["Send Email Asynchronously"]) async def send_email_async(data: EmailSchema) -> JSONResponse: message = MessageSchema ( subject = data.subject, recipients = data.dict().get("email"), template_body=data.dict().get("body"), subtype="html" ) fm = FastMail(conf) await fm.send_message(message, template_name="email.html") return JSONResponse(status_code=200, content={"message": "Email has been sent"}) #SEnd Email using Background Tasks @app.post("/email-background", tags=["Send Email using Background Tasks"]) async def send_email_background(data: EmailSchema, background_tasks: BackgroundTasks) -> JSONResponse: message = MessageSchema ( subject = data.subject, recipients = data.dict().get("email"), template_body=data.dict().get("body"), subtype="html" ) fm = FastMail(conf) background_tasks.add_task(fm.send_message, message, template_name="email.html") return JSONResponse(status_code=200, content={"message": "Email has been sent"})
en
0.632786
#Landing page template #Send Email Asynchronously #SEnd Email using Background Tasks
2.327624
2
006-ZigZag-Conversion/solution01.py
Eroica-cpp/LeetCode
7
6623721
#!/usr/bin/python # ============================================================================== # Author: <NAME> (<EMAIL>) # Date: May 1, 2015 # Question: 006-ZigZag-Conversion # Link: https://leetcode.com/problems/zigzag-conversion/ # ============================================================================== # The string "PAYPALISHIRING" is written in a zigzag pattern on a given number # of rows like this: (you may want to display this pattern in a fixed font for # better legibility) # # P A H N # A P L S I I G # Y I R # # And then read line by line: "PAHNAPLSIIGYIR" # # Write the code that will take a string and make this conversion given a number of rows: # # string convert(string text, int nRows); # # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". # ============================================================================== class Solution: # @param {string} s # @param {integer} numRows # @return {string} def convert(self, s, numRows): if numRows == 1 or len(s) <= numRows: return s div = 2 * numRows - 2 dic = {} for i in range(numRows): dic[i] = "" for j in range(len(s)): mod = j % div if mod <= (numRows-1): dic[mod] += s[j] else: dic[numRows-1-(mod-(numRows-1))] += s[j] newStr = "" for k in range(numRows): newStr += dic[k] return newStr
#!/usr/bin/python # ============================================================================== # Author: <NAME> (<EMAIL>) # Date: May 1, 2015 # Question: 006-ZigZag-Conversion # Link: https://leetcode.com/problems/zigzag-conversion/ # ============================================================================== # The string "PAYPALISHIRING" is written in a zigzag pattern on a given number # of rows like this: (you may want to display this pattern in a fixed font for # better legibility) # # P A H N # A P L S I I G # Y I R # # And then read line by line: "PAHNAPLSIIGYIR" # # Write the code that will take a string and make this conversion given a number of rows: # # string convert(string text, int nRows); # # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". # ============================================================================== class Solution: # @param {string} s # @param {integer} numRows # @return {string} def convert(self, s, numRows): if numRows == 1 or len(s) <= numRows: return s div = 2 * numRows - 2 dic = {} for i in range(numRows): dic[i] = "" for j in range(len(s)): mod = j % div if mod <= (numRows-1): dic[mod] += s[j] else: dic[numRows-1-(mod-(numRows-1))] += s[j] newStr = "" for k in range(numRows): newStr += dic[k] return newStr
en
0.551294
#!/usr/bin/python # ============================================================================== # Author: <NAME> (<EMAIL>) # Date: May 1, 2015 # Question: 006-ZigZag-Conversion # Link: https://leetcode.com/problems/zigzag-conversion/ # ============================================================================== # The string "PAYPALISHIRING" is written in a zigzag pattern on a given number # of rows like this: (you may want to display this pattern in a fixed font for # better legibility) # # P A H N # A P L S I I G # Y I R # # And then read line by line: "PAHNAPLSIIGYIR" # # Write the code that will take a string and make this conversion given a number of rows: # # string convert(string text, int nRows); # # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". # ============================================================================== # @param {string} s # @param {integer} numRows # @return {string}
4.166969
4
backend/apps/membership/admin.py
jaliste/mi_coop
0
6623722
<reponame>jaliste/mi_coop from django.contrib import admin # Register your models here. from .models import CoopMember, Coop @admin.register(CoopMember) class CoopMemberadmin(admin.ModelAdmin): change_list_template = 'admin/change_list.html' @admin.register(Coop) class Coop(admin.ModelAdmin): pass
from django.contrib import admin # Register your models here. from .models import CoopMember, Coop @admin.register(CoopMember) class CoopMemberadmin(admin.ModelAdmin): change_list_template = 'admin/change_list.html' @admin.register(Coop) class Coop(admin.ModelAdmin): pass
en
0.968259
# Register your models here.
1.387264
1
test_gauss.py
Basi1i0/LightPipesPulses
0
6623723
# -*- coding: utf-8 -*- """ Created on Mon Aug 13 17:41:21 2018 @author: Basil """ import matplotlib.pyplot as plt import gc import numpy import random from joblib import Parallel, delayed from LightPipes import cm, mm, nm import scipy import StepsGenerator import copy def AxiconZ(z): return 2*numpy.pi* k0**2 * w1**6 *z/a**2/(k0**2 * w1**4 + z**2)**(3/2) *numpy.exp( - z**2 * w1**2 /a**2 /(k0**2 * w1**4 + z**2) ) # 2*numpy.pi*z/a**2/k0*numpy.exp( - z**2 /a**2 /k0**2 / w1**2 ) ms = list([]) #for scale in range(0,20): #print(scale) lambda0 = 805*nm N = 1000 size = 9*mm xs = numpy.linspace(-size/2, size/2, N) f = 50*mm k0 = (2*numpy.pi/lambda0) w1 = 6.366197723675813e-05#f/k0/(1*mm) #sigma_zw #0.0005 w0 = f/(k0*w1) sz = k0*w1**2 alpha = (0.15*mm) x = LP(size, lambda0, N) x.GaussAperture(w1, 0*mm, 0, 1) x.GratingX( alpha*2*numpy.pi*(2.998*1e-4) / (f*lambda0**2) , 800e-9) #x.RandomPhase(1, 1) #x.Forvard(f) #x.Lens(f, 0.00, 0) #x.Forvard(2*f) #x.Lens(f, 0.00, 0) zs,start_z,end_z,steps_z,delta_z = StepsGenerator.StepsGenerate(0, 2*f, 200) intensities_z = numpy.full( (len(zs), x.getGridDimension(), x.getGridDimension()), numpy.NaN); for iz in range(0, len(zs)): # xc = copy.deepcopy(x) z_prev = zs[iz-1] if iz != 0 else 0 dz = zs[iz] - z_prev; if( dz > 0): x.Forvard(dz) #t + z - z0 intensities_z[iz] = x.Intensity(0) plt.imshow(intensities_z[:,N//2]) plt.show() plt.plot(zs / mm, intensities_z[:,N//2, N//2] / max(intensities_z[:,N//2, N//2]), 'o' ) plt.plot(zs / mm, 1/( 1 + ( (f - zs)/(k0*w1**2) )**2 ) ) plt.axvline(f / mm, ) plt.xlabel('Z, mm'); plt.ylabel('I') plt.show() plt.plot(xs / mm, intensities_z[ numpy.argmax(intensities_z[:,N//2, N//2]), N//2, :] / max(intensities_z[ numpy.argmax(intensities_z[:,N//2, N//2]), :, N//2] ), 'o' ) plt.plot(xs / mm, numpy.exp( -xs**2 / w1**2 ) ) plt.xlabel('X, mm'); plt.ylabel('I') plt.show() # #plt.plot(xs / mm, intensities_z[200-1,N//2,] , 'o' ) #plt.xlabel('X, mm'); plt.ylabel('I') #plt.show()
# -*- coding: utf-8 -*- """ Created on Mon Aug 13 17:41:21 2018 @author: Basil """ import matplotlib.pyplot as plt import gc import numpy import random from joblib import Parallel, delayed from LightPipes import cm, mm, nm import scipy import StepsGenerator import copy def AxiconZ(z): return 2*numpy.pi* k0**2 * w1**6 *z/a**2/(k0**2 * w1**4 + z**2)**(3/2) *numpy.exp( - z**2 * w1**2 /a**2 /(k0**2 * w1**4 + z**2) ) # 2*numpy.pi*z/a**2/k0*numpy.exp( - z**2 /a**2 /k0**2 / w1**2 ) ms = list([]) #for scale in range(0,20): #print(scale) lambda0 = 805*nm N = 1000 size = 9*mm xs = numpy.linspace(-size/2, size/2, N) f = 50*mm k0 = (2*numpy.pi/lambda0) w1 = 6.366197723675813e-05#f/k0/(1*mm) #sigma_zw #0.0005 w0 = f/(k0*w1) sz = k0*w1**2 alpha = (0.15*mm) x = LP(size, lambda0, N) x.GaussAperture(w1, 0*mm, 0, 1) x.GratingX( alpha*2*numpy.pi*(2.998*1e-4) / (f*lambda0**2) , 800e-9) #x.RandomPhase(1, 1) #x.Forvard(f) #x.Lens(f, 0.00, 0) #x.Forvard(2*f) #x.Lens(f, 0.00, 0) zs,start_z,end_z,steps_z,delta_z = StepsGenerator.StepsGenerate(0, 2*f, 200) intensities_z = numpy.full( (len(zs), x.getGridDimension(), x.getGridDimension()), numpy.NaN); for iz in range(0, len(zs)): # xc = copy.deepcopy(x) z_prev = zs[iz-1] if iz != 0 else 0 dz = zs[iz] - z_prev; if( dz > 0): x.Forvard(dz) #t + z - z0 intensities_z[iz] = x.Intensity(0) plt.imshow(intensities_z[:,N//2]) plt.show() plt.plot(zs / mm, intensities_z[:,N//2, N//2] / max(intensities_z[:,N//2, N//2]), 'o' ) plt.plot(zs / mm, 1/( 1 + ( (f - zs)/(k0*w1**2) )**2 ) ) plt.axvline(f / mm, ) plt.xlabel('Z, mm'); plt.ylabel('I') plt.show() plt.plot(xs / mm, intensities_z[ numpy.argmax(intensities_z[:,N//2, N//2]), N//2, :] / max(intensities_z[ numpy.argmax(intensities_z[:,N//2, N//2]), :, N//2] ), 'o' ) plt.plot(xs / mm, numpy.exp( -xs**2 / w1**2 ) ) plt.xlabel('X, mm'); plt.ylabel('I') plt.show() # #plt.plot(xs / mm, intensities_z[200-1,N//2,] , 'o' ) #plt.xlabel('X, mm'); plt.ylabel('I') #plt.show()
en
0.184369
# -*- coding: utf-8 -*- Created on Mon Aug 13 17:41:21 2018 @author: Basil # 2*numpy.pi*z/a**2/k0*numpy.exp( - z**2 /a**2 /k0**2 / w1**2 ) #for scale in range(0,20): #print(scale) #f/k0/(1*mm) #sigma_zw #0.0005 #x.RandomPhase(1, 1) #x.Forvard(f) #x.Lens(f, 0.00, 0) #x.Forvard(2*f) #x.Lens(f, 0.00, 0) # xc = copy.deepcopy(x) #t + z - z0 # #plt.plot(xs / mm, intensities_z[200-1,N//2,] , 'o' ) #plt.xlabel('X, mm'); plt.ylabel('I') #plt.show()
2.059003
2
setup.py
NickWoods1/pcask1d
1
6623724
from setuptools import setup, find_packages # User defines the location of the script output, and which method is being used. #Version of the test suite used __version__ = 0.1 setup( name = 'pcask1d', version = __version__, description = 'Find the ground state energy given a certain approximation to the many-body problem', author = '<NAME>', author_email = '<EMAIL>', url = "http://www.tcm.phy.cam.ac.uk/profiles/nw361/", packages = find_packages(), entry_points={'console_scripts': 'pcask1d = pcask1d.src.main:main'}, )
from setuptools import setup, find_packages # User defines the location of the script output, and which method is being used. #Version of the test suite used __version__ = 0.1 setup( name = 'pcask1d', version = __version__, description = 'Find the ground state energy given a certain approximation to the many-body problem', author = '<NAME>', author_email = '<EMAIL>', url = "http://www.tcm.phy.cam.ac.uk/profiles/nw361/", packages = find_packages(), entry_points={'console_scripts': 'pcask1d = pcask1d.src.main:main'}, )
en
0.921192
# User defines the location of the script output, and which method is being used. #Version of the test suite used
1.633774
2
modules/training_helper.py
BoyoChen/TCSA-CNN_profiler
2
6623725
<gh_stars>1-10 import tensorflow as tf import numpy as np from modules.feature_generator import load_dataset from modules.image_processor import image_augmentation, evenly_rotate import matplotlib.pyplot as plt import imageio def draw_profile_chart(profile, pred_profile, calculated_Vmax, calculated_R34): km = np.arange(0, 751, 5) plt.figure(figsize=(15, 10), linewidth=2) plt.plot(km, profile, color='r', label="profile") plt.plot(km, pred_profile, color='g', label="pred_profile") plt.axhline(y=calculated_Vmax, color='b', linestyle='-') plt.axvline(x=calculated_R34, color='y', linestyle='-') plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.ylim(0, 120) plt.xlabel("Radius", fontsize=30) plt.ylabel("Velocity", fontsize=30) plt.legend(loc="best", fontsize=20) plt.savefig('tmp.png') plt.close('all') RGB_matrix = imageio.imread('tmp.png') return RGB_matrix def output_sample_profile_chart(profiler, sample_data, summary_writer, epoch_index): for phase, (sample_images, sample_feature, sample_profile, sample_Vmax, sample_R34) in sample_data.items(): pred_profile, calculated_Vmax, calculated_R34 = profiler(sample_images, sample_feature, training=False) charts = [] for i in range(10): charts.append( draw_profile_chart(sample_profile[i], pred_profile[i], calculated_Vmax[i], calculated_R34[i]) ) chart_matrix = np.stack(charts).astype(np.int) with summary_writer.as_default(): tf.summary.image( f'{phase}_profile_chart', chart_matrix.astype(np.float)/255, step=epoch_index, max_outputs=chart_matrix.shape[0] ) def get_sample_data(dataset, count): for batch_index, (images, feature, profile, Vmax, R34) in dataset.enumerate(): valid_profile = profile[:, 0] != -999 preprocessed_images = image_augmentation(images) sample_images = tf.boolean_mask(preprocessed_images, valid_profile)[:count, ...] sample_feature = tf.boolean_mask(feature, valid_profile)[:count, ...] sample_profile = tf.boolean_mask(profile, valid_profile)[:count, ...] sample_Vmax = tf.boolean_mask(Vmax, valid_profile)[:count, ...] sample_R34 = tf.boolean_mask(R34, valid_profile)[:count, ...] return sample_images, sample_feature, sample_profile, sample_Vmax, sample_R34 def blend_profiles(profiles): return sum(profiles)/len(profiles) def rotation_blending(model, blending_num, images, feature): evenly_rotated_images = evenly_rotate(images, blending_num) profiles = [] Vmax = [] R34 = [] for image in evenly_rotated_images: pred_profile, pred_Vmax, pred_R34 = model(image, feature, training=False) profiles.append(pred_profile) Vmax.append(pred_Vmax) R34.append(pred_R34) return blend_profiles(profiles), tf.reduce_mean(Vmax, 0), tf.reduce_mean(R34, 0) def evaluate_loss(model, dataset, loss_function, blending_num=10): if loss_function == 'MSE': loss = tf.keras.losses.MeanSquaredError() elif loss_function == 'MAE': loss = tf.keras.losses.MeanAbsoluteError() avg_profile_loss = tf.keras.metrics.Mean(dtype=tf.float32) avg_Vmax_loss = tf.keras.metrics.Mean(dtype=tf.float32) avg_R34_loss = tf.keras.metrics.Mean(dtype=tf.float32) for batch_index, (images, feature, profile, Vmax, R34) in dataset.enumerate(): pred_profile, pred_Vmax, pred_R34 = rotation_blending(model, blending_num, images, feature) batch_profile_loss = loss(profile, pred_profile) avg_profile_loss.update_state(batch_profile_loss) batch_Vmax_loss = loss(Vmax, pred_Vmax) avg_Vmax_loss.update_state(batch_Vmax_loss) batch_R34_loss = loss(R34, pred_R34) avg_R34_loss.update_state(batch_R34_loss) profile_loss = avg_profile_loss.result() Vmax_loss = avg_Vmax_loss.result() R34_loss = avg_R34_loss.result() return profile_loss, Vmax_loss, R34_loss def get_tensorflow_datasets(data_folder, batch_size, shuffle_buffer, good_VIS_only=False, valid_profile_only=False, coordinate='cart'): datasets = dict() for phase in ['train', 'valid', 'test']: phase_data = load_dataset(data_folder, phase, good_VIS_only, valid_profile_only, coordinate) images = tf.data.Dataset.from_tensor_slices(phase_data['image']) feature = tf.data.Dataset.from_tensor_slices( phase_data['feature'].to_numpy(dtype='float32') ) profile = tf.data.Dataset.from_tensor_slices(phase_data['profile']) Vmax = tf.data.Dataset.from_tensor_slices( phase_data['label'][['Vmax']].to_numpy(dtype='float32') ) R34 = tf.data.Dataset.from_tensor_slices( phase_data['label'][['R34']].to_numpy(dtype='float32') ) datasets[phase] = tf.data.Dataset.zip((images, feature, profile, Vmax, R34)) \ .shuffle(shuffle_buffer) \ .batch(batch_size) return datasets
import tensorflow as tf import numpy as np from modules.feature_generator import load_dataset from modules.image_processor import image_augmentation, evenly_rotate import matplotlib.pyplot as plt import imageio def draw_profile_chart(profile, pred_profile, calculated_Vmax, calculated_R34): km = np.arange(0, 751, 5) plt.figure(figsize=(15, 10), linewidth=2) plt.plot(km, profile, color='r', label="profile") plt.plot(km, pred_profile, color='g', label="pred_profile") plt.axhline(y=calculated_Vmax, color='b', linestyle='-') plt.axvline(x=calculated_R34, color='y', linestyle='-') plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.ylim(0, 120) plt.xlabel("Radius", fontsize=30) plt.ylabel("Velocity", fontsize=30) plt.legend(loc="best", fontsize=20) plt.savefig('tmp.png') plt.close('all') RGB_matrix = imageio.imread('tmp.png') return RGB_matrix def output_sample_profile_chart(profiler, sample_data, summary_writer, epoch_index): for phase, (sample_images, sample_feature, sample_profile, sample_Vmax, sample_R34) in sample_data.items(): pred_profile, calculated_Vmax, calculated_R34 = profiler(sample_images, sample_feature, training=False) charts = [] for i in range(10): charts.append( draw_profile_chart(sample_profile[i], pred_profile[i], calculated_Vmax[i], calculated_R34[i]) ) chart_matrix = np.stack(charts).astype(np.int) with summary_writer.as_default(): tf.summary.image( f'{phase}_profile_chart', chart_matrix.astype(np.float)/255, step=epoch_index, max_outputs=chart_matrix.shape[0] ) def get_sample_data(dataset, count): for batch_index, (images, feature, profile, Vmax, R34) in dataset.enumerate(): valid_profile = profile[:, 0] != -999 preprocessed_images = image_augmentation(images) sample_images = tf.boolean_mask(preprocessed_images, valid_profile)[:count, ...] sample_feature = tf.boolean_mask(feature, valid_profile)[:count, ...] sample_profile = tf.boolean_mask(profile, valid_profile)[:count, ...] sample_Vmax = tf.boolean_mask(Vmax, valid_profile)[:count, ...] sample_R34 = tf.boolean_mask(R34, valid_profile)[:count, ...] return sample_images, sample_feature, sample_profile, sample_Vmax, sample_R34 def blend_profiles(profiles): return sum(profiles)/len(profiles) def rotation_blending(model, blending_num, images, feature): evenly_rotated_images = evenly_rotate(images, blending_num) profiles = [] Vmax = [] R34 = [] for image in evenly_rotated_images: pred_profile, pred_Vmax, pred_R34 = model(image, feature, training=False) profiles.append(pred_profile) Vmax.append(pred_Vmax) R34.append(pred_R34) return blend_profiles(profiles), tf.reduce_mean(Vmax, 0), tf.reduce_mean(R34, 0) def evaluate_loss(model, dataset, loss_function, blending_num=10): if loss_function == 'MSE': loss = tf.keras.losses.MeanSquaredError() elif loss_function == 'MAE': loss = tf.keras.losses.MeanAbsoluteError() avg_profile_loss = tf.keras.metrics.Mean(dtype=tf.float32) avg_Vmax_loss = tf.keras.metrics.Mean(dtype=tf.float32) avg_R34_loss = tf.keras.metrics.Mean(dtype=tf.float32) for batch_index, (images, feature, profile, Vmax, R34) in dataset.enumerate(): pred_profile, pred_Vmax, pred_R34 = rotation_blending(model, blending_num, images, feature) batch_profile_loss = loss(profile, pred_profile) avg_profile_loss.update_state(batch_profile_loss) batch_Vmax_loss = loss(Vmax, pred_Vmax) avg_Vmax_loss.update_state(batch_Vmax_loss) batch_R34_loss = loss(R34, pred_R34) avg_R34_loss.update_state(batch_R34_loss) profile_loss = avg_profile_loss.result() Vmax_loss = avg_Vmax_loss.result() R34_loss = avg_R34_loss.result() return profile_loss, Vmax_loss, R34_loss def get_tensorflow_datasets(data_folder, batch_size, shuffle_buffer, good_VIS_only=False, valid_profile_only=False, coordinate='cart'): datasets = dict() for phase in ['train', 'valid', 'test']: phase_data = load_dataset(data_folder, phase, good_VIS_only, valid_profile_only, coordinate) images = tf.data.Dataset.from_tensor_slices(phase_data['image']) feature = tf.data.Dataset.from_tensor_slices( phase_data['feature'].to_numpy(dtype='float32') ) profile = tf.data.Dataset.from_tensor_slices(phase_data['profile']) Vmax = tf.data.Dataset.from_tensor_slices( phase_data['label'][['Vmax']].to_numpy(dtype='float32') ) R34 = tf.data.Dataset.from_tensor_slices( phase_data['label'][['R34']].to_numpy(dtype='float32') ) datasets[phase] = tf.data.Dataset.zip((images, feature, profile, Vmax, R34)) \ .shuffle(shuffle_buffer) \ .batch(batch_size) return datasets
none
1
2.47517
2
tests/test_config_examples.py
turing4ever/flask_jsondash
3,503
6623726
""" Test the validation for the core configuration schema. Also test any example config files. """ import os import json import pytest from flask_jsondash import schema ROOT_DIR = 'example_app/examples/config' def get_example_configs(): return [ f for f in os.listdir(ROOT_DIR) if f.endswith('.json') ] @pytest.mark.schema @pytest.mark.examples @pytest.mark.parametrize('conf', get_example_configs()) def test_example_configs_from_example_folder_load_as_valid_json(conf): data = open('{}/{}'.format(ROOT_DIR, conf)).read() assert json.loads(data) @pytest.mark.schema @pytest.mark.validation @pytest.mark.examples @pytest.mark.parametrize('conf', get_example_configs()) def test_example_configs_from_example_folder_load_as_valid_schema(conf): data = open('{}/{}'.format(ROOT_DIR, conf)).read() data = json.loads(data) res = schema.validate(data) assert res is None
""" Test the validation for the core configuration schema. Also test any example config files. """ import os import json import pytest from flask_jsondash import schema ROOT_DIR = 'example_app/examples/config' def get_example_configs(): return [ f for f in os.listdir(ROOT_DIR) if f.endswith('.json') ] @pytest.mark.schema @pytest.mark.examples @pytest.mark.parametrize('conf', get_example_configs()) def test_example_configs_from_example_folder_load_as_valid_json(conf): data = open('{}/{}'.format(ROOT_DIR, conf)).read() assert json.loads(data) @pytest.mark.schema @pytest.mark.validation @pytest.mark.examples @pytest.mark.parametrize('conf', get_example_configs()) def test_example_configs_from_example_folder_load_as_valid_schema(conf): data = open('{}/{}'.format(ROOT_DIR, conf)).read() data = json.loads(data) res = schema.validate(data) assert res is None
en
0.325978
Test the validation for the core configuration schema. Also test any example config files.
2.628419
3
sotd/frontend/routes.py
huntermatthews/sot
0
6623727
<filename>sotd/frontend/routes.py # -*- coding: utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import frontend def add_routes(app): # Application level API app.add_url_rule('/', 'summary', frontend.summary, methods=['GET']) # DEBUG API app.add_url_rule('/query', 'debug_query', frontend.debug_query, methods=['GET']) # COLLECTIONS API app.add_url_rule('/collections', 'list_collections', frontend.list_collections, methods=['GET']) app.add_url_rule('/collections', 'create_collections', frontend.create_collections, methods=['POST']) # ITEMS API app.add_url_rule('/collections/<collection>/items', 'list_items', frontend.list_items, methods=['GET']) app.add_url_rule('/collections/<collection>/items', 'create_items', frontend.create_items, methods=['POST']) app.add_url_rule('/collections/<collection>/items/<item>/fields/<field>', 'get_field', frontend.get_field, methods=['GET']) ## END OF LINE ##
<filename>sotd/frontend/routes.py # -*- coding: utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import frontend def add_routes(app): # Application level API app.add_url_rule('/', 'summary', frontend.summary, methods=['GET']) # DEBUG API app.add_url_rule('/query', 'debug_query', frontend.debug_query, methods=['GET']) # COLLECTIONS API app.add_url_rule('/collections', 'list_collections', frontend.list_collections, methods=['GET']) app.add_url_rule('/collections', 'create_collections', frontend.create_collections, methods=['POST']) # ITEMS API app.add_url_rule('/collections/<collection>/items', 'list_items', frontend.list_items, methods=['GET']) app.add_url_rule('/collections/<collection>/items', 'create_items', frontend.create_items, methods=['POST']) app.add_url_rule('/collections/<collection>/items/<item>/fields/<field>', 'get_field', frontend.get_field, methods=['GET']) ## END OF LINE ##
en
0.433536
# -*- coding: utf-8 -*- # Application level API # DEBUG API # COLLECTIONS API # ITEMS API ## END OF LINE ##
2.194052
2
api/src/api/endpoints/send_gift.py
whynft/nft-gift-button-backend
0
6623728
<filename>api/src/api/endpoints/send_gift.py from fastapi import APIRouter, status from fastapi.responses import JSONResponse import schemas from config.misc import redis from utils.logger import get_app_logger from utils.redisdb import NftGiftRedisKeys from utils.security import create_verification_code, get_verification_code_hash router = APIRouter() logger = get_app_logger() @router.post( '/verification-code', description=( 'Get verification code that receiver will need to proof himself to backend, i.e. book a gift.' ), response_model=schemas.VerificationCodeOut, responses={ status.HTTP_410_GONE: { "model": schemas.Message, "description": "Gift has been already reported to backend and verification code was sent as response.", }, } ) async def verification_code(gift_in: schemas.Gift): gift_verification_code_key = NftGiftRedisKeys( gift_in.sender_address, gift_in.nft_contract, gift_in.nft_token, ).key_to_verification_code() gift_verification_code = await redis.get(gift_verification_code_key) if gift_verification_code: return JSONResponse( status_code=status.HTTP_410_GONE, content={"message": f"Gift has been already reported to backend and verification code was sent as response."}, ) logger.info(f"Create pass phrase for {gift_in} and store in Redis its hash...") gift_verification_code = create_verification_code() await redis.set(gift_verification_code_key, get_verification_code_hash(gift_verification_code)) return {'verification_code': gift_verification_code, **gift_in.dict()}
<filename>api/src/api/endpoints/send_gift.py from fastapi import APIRouter, status from fastapi.responses import JSONResponse import schemas from config.misc import redis from utils.logger import get_app_logger from utils.redisdb import NftGiftRedisKeys from utils.security import create_verification_code, get_verification_code_hash router = APIRouter() logger = get_app_logger() @router.post( '/verification-code', description=( 'Get verification code that receiver will need to proof himself to backend, i.e. book a gift.' ), response_model=schemas.VerificationCodeOut, responses={ status.HTTP_410_GONE: { "model": schemas.Message, "description": "Gift has been already reported to backend and verification code was sent as response.", }, } ) async def verification_code(gift_in: schemas.Gift): gift_verification_code_key = NftGiftRedisKeys( gift_in.sender_address, gift_in.nft_contract, gift_in.nft_token, ).key_to_verification_code() gift_verification_code = await redis.get(gift_verification_code_key) if gift_verification_code: return JSONResponse( status_code=status.HTTP_410_GONE, content={"message": f"Gift has been already reported to backend and verification code was sent as response."}, ) logger.info(f"Create pass phrase for {gift_in} and store in Redis its hash...") gift_verification_code = create_verification_code() await redis.set(gift_verification_code_key, get_verification_code_hash(gift_verification_code)) return {'verification_code': gift_verification_code, **gift_in.dict()}
none
1
2.475294
2
Textbook/Chapter 5/twoDimList.py
hunterluepke/Learn-Python-for-Stats-and-Econ
16
6623729
#twoDimensionalListAndNumpyArray.py import numpy as np twoDimList = [[1,2,3,4],[2,3,4,5]] print(twoDimList) twoDimArray = np.array(twoDimList) print(twoDimArray) for i in range(len(twoDimList)): print(twoDimList[i]) print(twoDimArray[i]) for j in range(len(twoDimList[i])): print(twoDimList[i][j]) print(twoDimArray[i][j])
#twoDimensionalListAndNumpyArray.py import numpy as np twoDimList = [[1,2,3,4],[2,3,4,5]] print(twoDimList) twoDimArray = np.array(twoDimList) print(twoDimArray) for i in range(len(twoDimList)): print(twoDimList[i]) print(twoDimArray[i]) for j in range(len(twoDimList[i])): print(twoDimList[i][j]) print(twoDimArray[i][j])
en
0.210205
#twoDimensionalListAndNumpyArray.py
3.662378
4
src/wizard/view/clsMain.py
UCHIC/ODMStreamingDataLoader
0
6623730
<reponame>UCHIC/ODMStreamingDataLoader import os import wx from ..media.images import blue_add, blue_remove, blue_edit, blue_run class MainView(wx.Frame): def __init__(self, parent, **kwargs): super(MainView, self).__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=(1080,700), style=wx.DEFAULT_FRAME_STYLE, **kwargs) self.tb = self.CreateToolBar() #tsize = (30, 30) # path = os.path.dirname(\ # os.path.dirname(os.path.realpath(__file__))) # new_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_add.png',\ # wx.BITMAP_TYPE_PNG), tsize) # del_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_remove.png',\ # wx.BITMAP_TYPE_PNG), tsize) # edit_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_edit.png',\ # wx.BITMAP_TYPE_PNG), tsize) # #ref_bmp = scaleBitmap(wx.Bitmap(\ # # path + '//media/ic_autorenew_black_24dp.png',\ # # wx.BITMAP_TYPE_PNG), tsize) # run_bmp = scaleBitmap(wx.Bitmap(\ # path + '//media/blue_run.png',\ # wx.BITMAP_TYPE_PNG), tsize) new_bmp= blue_add.GetImage().Rescale(30, 30).ConvertToBitmap()#.getBitmap() del_bmp=blue_remove.GetImage().Rescale(30, 30).ConvertToBitmap()#.getBitmap() edit_bmp= blue_edit.GetImage().Rescale(30, 30).ConvertToBitmap()#.getBitmap() run_bmp= blue_run.GetImage().Rescale(30, 30).ConvertToBitmap()#.getBitmap() self.tb.AddLabelTool(id=10, label="New", bitmap=new_bmp, longHelp='Create a new mapping.') self.tb.AddLabelTool(id=20, label='Delete', bitmap=del_bmp, longHelp='Delete selected mapping.') self.tb.AddLabelTool(id=30, label='Edit', bitmap=edit_bmp, longHelp='Edit selected mapping.') self.tb.AddLabelTool(id=40, label='Run', bitmap=run_bmp, longHelp='Run Data File Configuration.') self.tb.Bind(wx.EVT_TOOL, self.onNewButtonClick, id=10) self.tb.Bind(wx.EVT_TOOL, self.onDelButtonClick, id=20) self.tb.Bind(wx.EVT_TOOL, self.onEditButtonClick, id=30) self.tb.Bind(wx.EVT_TOOL, self.onRunButtonClick, id=40) self.tb.EnableTool(20, False) self.tb.EnableTool(30, False) self.tb.EnableTool(40, False) self.tb.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR)) self.tb.Realize() self.SetSizeHintsSz(wx.Size(1080, 700), wx.DefaultSize) self.Centre(wx.BOTH) self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR)) def __del__(self): pass def onFileOpenClick(self, event): event.Skip() def onFileNewClick(self, event): event.Skip() def onFileSaveAsClick(self, event): event.Skip() def onFileExitClick(self, event): event.Skip() def onHelpAboutClick(self, event): event.Skip() def onNewButtonClick(self, event): event.Skip() def onDelButtonClick(self, event): event.Skip() def onEditButtonClick(self, event): event.Skip() def onRefButtonClick(self, event): event.Skip() def onRunButtonClick(self, event): event.Skip() def onNewButtonOver(self, event): event.Skip() def onDelButtonOver(self, event): event.Skip() def onEditButtonOver(self, event): event.Skip() def scaleBitmap(bitmap, size): image = wx.ImageFromBitmap(bitmap) image = image.Scale(size[0], size[1], wx.IMAGE_QUALITY_HIGH) result = wx.BitmapFromImage(image) return result
import os import wx from ..media.images import blue_add, blue_remove, blue_edit, blue_run class MainView(wx.Frame): def __init__(self, parent, **kwargs): super(MainView, self).__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=(1080,700), style=wx.DEFAULT_FRAME_STYLE, **kwargs) self.tb = self.CreateToolBar() #tsize = (30, 30) # path = os.path.dirname(\ # os.path.dirname(os.path.realpath(__file__))) # new_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_add.png',\ # wx.BITMAP_TYPE_PNG), tsize) # del_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_remove.png',\ # wx.BITMAP_TYPE_PNG), tsize) # edit_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_edit.png',\ # wx.BITMAP_TYPE_PNG), tsize) # #ref_bmp = scaleBitmap(wx.Bitmap(\ # # path + '//media/ic_autorenew_black_24dp.png',\ # # wx.BITMAP_TYPE_PNG), tsize) # run_bmp = scaleBitmap(wx.Bitmap(\ # path + '//media/blue_run.png',\ # wx.BITMAP_TYPE_PNG), tsize) new_bmp= blue_add.GetImage().Rescale(30, 30).ConvertToBitmap()#.getBitmap() del_bmp=blue_remove.GetImage().Rescale(30, 30).ConvertToBitmap()#.getBitmap() edit_bmp= blue_edit.GetImage().Rescale(30, 30).ConvertToBitmap()#.getBitmap() run_bmp= blue_run.GetImage().Rescale(30, 30).ConvertToBitmap()#.getBitmap() self.tb.AddLabelTool(id=10, label="New", bitmap=new_bmp, longHelp='Create a new mapping.') self.tb.AddLabelTool(id=20, label='Delete', bitmap=del_bmp, longHelp='Delete selected mapping.') self.tb.AddLabelTool(id=30, label='Edit', bitmap=edit_bmp, longHelp='Edit selected mapping.') self.tb.AddLabelTool(id=40, label='Run', bitmap=run_bmp, longHelp='Run Data File Configuration.') self.tb.Bind(wx.EVT_TOOL, self.onNewButtonClick, id=10) self.tb.Bind(wx.EVT_TOOL, self.onDelButtonClick, id=20) self.tb.Bind(wx.EVT_TOOL, self.onEditButtonClick, id=30) self.tb.Bind(wx.EVT_TOOL, self.onRunButtonClick, id=40) self.tb.EnableTool(20, False) self.tb.EnableTool(30, False) self.tb.EnableTool(40, False) self.tb.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR)) self.tb.Realize() self.SetSizeHintsSz(wx.Size(1080, 700), wx.DefaultSize) self.Centre(wx.BOTH) self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR)) def __del__(self): pass def onFileOpenClick(self, event): event.Skip() def onFileNewClick(self, event): event.Skip() def onFileSaveAsClick(self, event): event.Skip() def onFileExitClick(self, event): event.Skip() def onHelpAboutClick(self, event): event.Skip() def onNewButtonClick(self, event): event.Skip() def onDelButtonClick(self, event): event.Skip() def onEditButtonClick(self, event): event.Skip() def onRefButtonClick(self, event): event.Skip() def onRunButtonClick(self, event): event.Skip() def onNewButtonOver(self, event): event.Skip() def onDelButtonOver(self, event): event.Skip() def onEditButtonOver(self, event): event.Skip() def scaleBitmap(bitmap, size): image = wx.ImageFromBitmap(bitmap) image = image.Scale(size[0], size[1], wx.IMAGE_QUALITY_HIGH) result = wx.BitmapFromImage(image) return result
en
0.156809
#tsize = (30, 30) # path = os.path.dirname(\ # os.path.dirname(os.path.realpath(__file__))) # new_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_add.png',\ # wx.BITMAP_TYPE_PNG), tsize) # del_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_remove.png',\ # wx.BITMAP_TYPE_PNG), tsize) # edit_bmp = scaleBitmap(wx.Bitmap(\ # path + '/media/blue_edit.png',\ # wx.BITMAP_TYPE_PNG), tsize) # #ref_bmp = scaleBitmap(wx.Bitmap(\ # # path + '//media/ic_autorenew_black_24dp.png',\ # # wx.BITMAP_TYPE_PNG), tsize) # run_bmp = scaleBitmap(wx.Bitmap(\ # path + '//media/blue_run.png',\ # wx.BITMAP_TYPE_PNG), tsize) #.getBitmap() #.getBitmap() #.getBitmap() #.getBitmap()
2.297593
2
profiling/output_profiling.py
ahamilton144/CALFEWS
3
6623731
import pstats import sys name = sys.argv[1] mode = sys.argv[2] p = pstats.Stats("profile_" + name + ".stats") p.sort_stats("cumulative") if mode == 'cumulative': p.print_stats() elif mode == 'caller': p.print_callers() elif mode == 'callee': p.print_callees()
import pstats import sys name = sys.argv[1] mode = sys.argv[2] p = pstats.Stats("profile_" + name + ".stats") p.sort_stats("cumulative") if mode == 'cumulative': p.print_stats() elif mode == 'caller': p.print_callers() elif mode == 'callee': p.print_callees()
none
1
2.40491
2
scripts/ITAC/parse-output.py
ahueck/MPI-Corrbench
2
6623732
# TODO documentation at different location # input: # input_dir: the directory where the tool was run and output was captured # is_error_expected: bool if an error is expected # error_specification: information read from error-classification.json # return values: # error_found count off errors found # -1 means could not tell (e.g. output is missing or not helpful) # -2 means warning only, no error # is_error_expected=True the output correct_error_found is ignored def parse_output(input_dir, is_error_expected, error_specification): error_found = -1 correct_error_found = -1 fname = input_dir + "/output.txt" try: with open(fname, mode='r') as file: data = file.read().replace('\n', '') if (data != "" and "ERROR:" in data): # found something # explicitly not include an ITAC segfault if not "ERROR: Signal 11 caught in ITC code section." in data: error_found = 1 elif (data != "" and "WARNING:" in data): # found warning opnly error_found =-2 elif ( data != "" and "INFO: Error checking completed without finding any problems." in data): # found nothing error_found = 0 except UnicodeDecodeError: print("Error: UnicodeDecodeError while reading file %s (ignoring case)" % (fname)) return error_found, correct_error_found
# TODO documentation at different location # input: # input_dir: the directory where the tool was run and output was captured # is_error_expected: bool if an error is expected # error_specification: information read from error-classification.json # return values: # error_found count off errors found # -1 means could not tell (e.g. output is missing or not helpful) # -2 means warning only, no error # is_error_expected=True the output correct_error_found is ignored def parse_output(input_dir, is_error_expected, error_specification): error_found = -1 correct_error_found = -1 fname = input_dir + "/output.txt" try: with open(fname, mode='r') as file: data = file.read().replace('\n', '') if (data != "" and "ERROR:" in data): # found something # explicitly not include an ITAC segfault if not "ERROR: Signal 11 caught in ITC code section." in data: error_found = 1 elif (data != "" and "WARNING:" in data): # found warning opnly error_found =-2 elif ( data != "" and "INFO: Error checking completed without finding any problems." in data): # found nothing error_found = 0 except UnicodeDecodeError: print("Error: UnicodeDecodeError while reading file %s (ignoring case)" % (fname)) return error_found, correct_error_found
en
0.839642
# TODO documentation at different location # input: # input_dir: the directory where the tool was run and output was captured # is_error_expected: bool if an error is expected # error_specification: information read from error-classification.json # return values: # error_found count off errors found # -1 means could not tell (e.g. output is missing or not helpful) # -2 means warning only, no error # is_error_expected=True the output correct_error_found is ignored # found something # explicitly not include an ITAC segfault # found warning opnly # found nothing
2.626733
3
examples/Test.py
Ellis0817/Introduction-to-Programming-Using-Python
0
6623733
<filename>examples/Test.py myList = [1, 2, 3, 4, 5, 6] for i in range(4, -1, -1): myList[i + 1] = myList[i] for i in range(0, 6): print(myList[i], end = " ")
<filename>examples/Test.py myList = [1, 2, 3, 4, 5, 6] for i in range(4, -1, -1): myList[i + 1] = myList[i] for i in range(0, 6): print(myList[i], end = " ")
none
1
3.804368
4
Chapter05/restful_python_2_05/Django01/games_service/games/serializers.py
PacktPublishing/Hands-On-RESTful-Python-Web-Services-Second-Edition
45
6623734
from rest_framework import serializers from games.models import Game class GameSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=200) release_date = serializers.DateTimeField() esrb_rating = serializers.CharField(max_length=150) played_once = serializers.BooleanField(required=False) played_times = serializers.IntegerField(required=False) def create(self, validated_data): return Game.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.release_date = validated_data.get('release_date', instance.release_date) instance.esrb_rating = validated_data.get('esrb_rating', instance.esrb_rating) instance.played_once = validated_data.get('played_once', instance.played_once) instance.played_times = validated_data.get('played_times', instance.played_times) instance.save() return instance
from rest_framework import serializers from games.models import Game class GameSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=200) release_date = serializers.DateTimeField() esrb_rating = serializers.CharField(max_length=150) played_once = serializers.BooleanField(required=False) played_times = serializers.IntegerField(required=False) def create(self, validated_data): return Game.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.release_date = validated_data.get('release_date', instance.release_date) instance.esrb_rating = validated_data.get('esrb_rating', instance.esrb_rating) instance.played_once = validated_data.get('played_once', instance.played_once) instance.played_times = validated_data.get('played_times', instance.played_times) instance.save() return instance
none
1
2.320117
2
pi_py/wdactions/cli.py
Bengreen/PiPowerMgt
0
6623735
#!/usr/bin/venv python import click from .watchdog import PiWatchDog from .wdsystemd import watchdogd @click.group() def cli(): pass @cli.command() @click.argument("id", type=int) @click.argument("state", type=click.Choice(["on", "off"])) @click.option("--address", "address", type=int, default=0x08) def power(address, id, state): watchdog = PiWatchDog(address) if state == "on": click.echo("ON") watchdog.powerOn(id) else: click.echo("OFF") watchdog.powerOff(id) click.echo(f"Turn {state} Fan {id}") @cli.command() @click.argument("id", type=int) @click.argument("state", type=click.Choice(["on", "off"])) @click.option("--address", "address", type=int, default=0x08) def fan(address, id, state): watchdog = PiWatchDog(address) if state == "on": click.echo("ON") watchdog.fanOn(id) else: click.echo("OFF") watchdog.fanOff(id) click.echo(f"Turn {state} Fan {id}") @cli.command() @click.argument("id", type=int) @click.option("--address", "address", type=int, default=0x08) @click.option("--on", "on", type=int, default=61) @click.option("--off", "off", type=int, default=53) @click.option("--sleep", "sleepinterval", type=int, default=5) def watch(address, id, on, off, sleepinterval): click.echo(f"Starting watchdog for id={id}") watchdogd(address, id, on, off, sleepinterval) if __name__ == "__main__": cli()
#!/usr/bin/venv python import click from .watchdog import PiWatchDog from .wdsystemd import watchdogd @click.group() def cli(): pass @cli.command() @click.argument("id", type=int) @click.argument("state", type=click.Choice(["on", "off"])) @click.option("--address", "address", type=int, default=0x08) def power(address, id, state): watchdog = PiWatchDog(address) if state == "on": click.echo("ON") watchdog.powerOn(id) else: click.echo("OFF") watchdog.powerOff(id) click.echo(f"Turn {state} Fan {id}") @cli.command() @click.argument("id", type=int) @click.argument("state", type=click.Choice(["on", "off"])) @click.option("--address", "address", type=int, default=0x08) def fan(address, id, state): watchdog = PiWatchDog(address) if state == "on": click.echo("ON") watchdog.fanOn(id) else: click.echo("OFF") watchdog.fanOff(id) click.echo(f"Turn {state} Fan {id}") @cli.command() @click.argument("id", type=int) @click.option("--address", "address", type=int, default=0x08) @click.option("--on", "on", type=int, default=61) @click.option("--off", "off", type=int, default=53) @click.option("--sleep", "sleepinterval", type=int, default=5) def watch(address, id, on, off, sleepinterval): click.echo(f"Starting watchdog for id={id}") watchdogd(address, id, on, off, sleepinterval) if __name__ == "__main__": cli()
ru
0.271363
#!/usr/bin/venv python
2.625278
3
ml/myscript/knn.py
miraclestatus/mllearning
1
6623736
<gh_stars>1-10 from sklearn.model_selection import train_test_split
from sklearn.model_selection import train_test_split
none
1
1.210468
1
api/src/application/rest_api/task_status/schemas.py
iliaskaras/housing-units
0
6623737
<gh_stars>0 from typing import Optional, Any from pydantic import BaseModel class TaskStatus(BaseModel): task_id: Optional[str] task_status: Optional[str] task_result: Optional[Any] class Config: schema_extra = { "example": { "task_id": "e3b3326c-617a-4836-8fe0-3c17390f0bd4", "task_status": "PENDING", "task_result": None, } }
from typing import Optional, Any from pydantic import BaseModel class TaskStatus(BaseModel): task_id: Optional[str] task_status: Optional[str] task_result: Optional[Any] class Config: schema_extra = { "example": { "task_id": "e3b3326c-617a-4836-8fe0-3c17390f0bd4", "task_status": "PENDING", "task_result": None, } }
none
1
2.654616
3
timebox/notify.py
DerFlob/timebox-home-assistant
0
6623738
from .const import DOMAIN import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_NAME, CONF_URL import voluptuous as vol import logging from homeassistant.components.notify import ATTR_TARGET, ATTR_DATA,PLATFORM_SCHEMA, BaseNotificationService import requests import io from os.path import join _LOGGER = logging.getLogger(__name__) CONF_MAC = "mac" CONF_IMAGE_DIR = "image_dir" TIMEOUT = 15 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_URL): cv.string, vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_IMAGE_DIR): cv.string }) PARAM_MODE = "mode" MODE_IMAGE = "image" PARAM_FILE_NAME = "file-name" PARAM_LINK = "link" MODE_TEXT = "text" PARAM_TEXT = "text" MODE_BRIGHTNESS = "brightness" PARAM_BRIGHTNESS = "brightness" MODE_TIME = "time" def is_valid_server_url(url): r = requests.get(f'{url}/hello', timeout=TIMEOUT) if r.status_code != 200: return False return True def get_service(hass, config, discovery_info=None): image_dir = None if (config[CONF_IMAGE_DIR]): image_dir = hass.config.path(config[CONF_IMAGE_DIR]) if not is_valid_server_url(config[CONF_URL]): _LOGGER.error(f'Invalid server url "{config[CONF_URL]}"') return None timebox = Timebox(config[CONF_URL], config[CONF_MAC]) if not timebox.isConnected(): return None return TimeboxService(timebox, image_dir) class TimeboxService(BaseNotificationService): def __init__(self, timebox, image_dir = None): self.timebox = timebox self.image_dir = image_dir def send_image_link(self, link): r = requests.get(link) if (r.status_code != 200): return False return self.timebox.send_image(io.BytesIO(r.content)) def send_image_file(self, filename): try: f = open(join(self.image_dir, filename), 'rb') return self.timebox.send_image(f) except Exception as e: _LOGGER.error(e) _LOGGER.error(f"Failed to read {filename}") return False def send_message(self, message="", **kwargs): if kwargs.get(ATTR_DATA) is not None: data = kwargs.get(ATTR_DATA) mode = data.get(PARAM_MODE, MODE_TEXT) elif message is not None: data = {} mode = MODE_TEXT else: _LOGGER.error("Service call needs a message type") return False if (mode == MODE_IMAGE): if (data.get(PARAM_LINK)): return self.send_image_link(data.get(PARAM_LINK)) elif (data.get(PARAM_FILE_NAME)): return self.send_image_file(data.get(PARAM_FILE_NAME)) else: _LOGGER.error(f'Invalid payload, {PARAM_LINK} or {PARAM_FILE_NAME} must be provided with {MODE_IMAGE} mode') return False elif (mode == MODE_TEXT): text = data.get(PARAM_TEXT, message) if (text): return self.timebox.send_text(text) else: _LOGGER.error(f"Invalid payload, {PARAM_TEXT} or message must be provided with {MODE_TEXT}") return False elif (mode == MODE_BRIGHTNESS): try: brightness = int(data.get(PARAM_BRIGHTNESS)) return self.timebox.set_brightness(brightness) except Exception: _LOGGER.error(f"Invalid payload, {PARAM_BRIGHTNESS}={data.get(PARAM_BRIGHTNESS)}") return False elif (mode == MODE_TIME): return self.timebox.set_time_channel() else: _LOGGER.error(f"Invalid mode {mode}") return False return True class Timebox(): def __init__(self, url, mac): self.url = url self.mac = mac def send_request(self, error_message, url, data, files = {}): r = requests.post(f'{self.url}{url}', data=data, files=files, timeout=TIMEOUT) if (r.status_code != 200): _LOGGER.error(r.content) _LOGGER.error(error_message) return False return True def send_image(self, image): return self.send_request('Failed to send image', '/image', data={"mac": self.mac}, files={"image": image}) def send_text(self, text): return self.send_request('Failed to send text', '/text', data={"text": text, "mac": self.mac}) def set_brightness(self, brightness): return self.send_request('Failed to set brightness', '/brightness', data={"brightness": brightness, "mac": self.mac}) def isConnected(self): return self.send_request('Failed to connect to the timebox', '/connect', data={"mac": self.mac}) def set_time_channel(self): return self.send_request('Failed to switch to time channel', '/time', data={"mac": self.mac})
from .const import DOMAIN import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_NAME, CONF_URL import voluptuous as vol import logging from homeassistant.components.notify import ATTR_TARGET, ATTR_DATA,PLATFORM_SCHEMA, BaseNotificationService import requests import io from os.path import join _LOGGER = logging.getLogger(__name__) CONF_MAC = "mac" CONF_IMAGE_DIR = "image_dir" TIMEOUT = 15 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_URL): cv.string, vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_IMAGE_DIR): cv.string }) PARAM_MODE = "mode" MODE_IMAGE = "image" PARAM_FILE_NAME = "file-name" PARAM_LINK = "link" MODE_TEXT = "text" PARAM_TEXT = "text" MODE_BRIGHTNESS = "brightness" PARAM_BRIGHTNESS = "brightness" MODE_TIME = "time" def is_valid_server_url(url): r = requests.get(f'{url}/hello', timeout=TIMEOUT) if r.status_code != 200: return False return True def get_service(hass, config, discovery_info=None): image_dir = None if (config[CONF_IMAGE_DIR]): image_dir = hass.config.path(config[CONF_IMAGE_DIR]) if not is_valid_server_url(config[CONF_URL]): _LOGGER.error(f'Invalid server url "{config[CONF_URL]}"') return None timebox = Timebox(config[CONF_URL], config[CONF_MAC]) if not timebox.isConnected(): return None return TimeboxService(timebox, image_dir) class TimeboxService(BaseNotificationService): def __init__(self, timebox, image_dir = None): self.timebox = timebox self.image_dir = image_dir def send_image_link(self, link): r = requests.get(link) if (r.status_code != 200): return False return self.timebox.send_image(io.BytesIO(r.content)) def send_image_file(self, filename): try: f = open(join(self.image_dir, filename), 'rb') return self.timebox.send_image(f) except Exception as e: _LOGGER.error(e) _LOGGER.error(f"Failed to read {filename}") return False def send_message(self, message="", **kwargs): if kwargs.get(ATTR_DATA) is not None: data = kwargs.get(ATTR_DATA) mode = data.get(PARAM_MODE, MODE_TEXT) elif message is not None: data = {} mode = MODE_TEXT else: _LOGGER.error("Service call needs a message type") return False if (mode == MODE_IMAGE): if (data.get(PARAM_LINK)): return self.send_image_link(data.get(PARAM_LINK)) elif (data.get(PARAM_FILE_NAME)): return self.send_image_file(data.get(PARAM_FILE_NAME)) else: _LOGGER.error(f'Invalid payload, {PARAM_LINK} or {PARAM_FILE_NAME} must be provided with {MODE_IMAGE} mode') return False elif (mode == MODE_TEXT): text = data.get(PARAM_TEXT, message) if (text): return self.timebox.send_text(text) else: _LOGGER.error(f"Invalid payload, {PARAM_TEXT} or message must be provided with {MODE_TEXT}") return False elif (mode == MODE_BRIGHTNESS): try: brightness = int(data.get(PARAM_BRIGHTNESS)) return self.timebox.set_brightness(brightness) except Exception: _LOGGER.error(f"Invalid payload, {PARAM_BRIGHTNESS}={data.get(PARAM_BRIGHTNESS)}") return False elif (mode == MODE_TIME): return self.timebox.set_time_channel() else: _LOGGER.error(f"Invalid mode {mode}") return False return True class Timebox(): def __init__(self, url, mac): self.url = url self.mac = mac def send_request(self, error_message, url, data, files = {}): r = requests.post(f'{self.url}{url}', data=data, files=files, timeout=TIMEOUT) if (r.status_code != 200): _LOGGER.error(r.content) _LOGGER.error(error_message) return False return True def send_image(self, image): return self.send_request('Failed to send image', '/image', data={"mac": self.mac}, files={"image": image}) def send_text(self, text): return self.send_request('Failed to send text', '/text', data={"text": text, "mac": self.mac}) def set_brightness(self, brightness): return self.send_request('Failed to set brightness', '/brightness', data={"brightness": brightness, "mac": self.mac}) def isConnected(self): return self.send_request('Failed to connect to the timebox', '/connect', data={"mac": self.mac}) def set_time_channel(self): return self.send_request('Failed to switch to time channel', '/time', data={"mac": self.mac})
none
1
2.239424
2
solution1.py
doriszd/http-github.com-yourusername-pands-problem-set
1
6623739
<gh_stars>1-10 # <NAME>, February, 2019 # Solution to problem 1 # User is asked to enter a positive integer x = int(input("Please enter a positive integer: ")) # a = range of all numbers from 1 to entered number a = range(1, x) # b = sum of all numbers in a range from 1 up to entered number b = sum(a) # Print the sum of all numbers up to entered number print (b) # If entered number is lower than 0 print "Please enter integer greater than 0" if x < 0: print ("Please enter integer greater than 0")
# <NAME>, February, 2019 # Solution to problem 1 # User is asked to enter a positive integer x = int(input("Please enter a positive integer: ")) # a = range of all numbers from 1 to entered number a = range(1, x) # b = sum of all numbers in a range from 1 up to entered number b = sum(a) # Print the sum of all numbers up to entered number print (b) # If entered number is lower than 0 print "Please enter integer greater than 0" if x < 0: print ("Please enter integer greater than 0")
en
0.907938
# <NAME>, February, 2019 # Solution to problem 1 # User is asked to enter a positive integer # a = range of all numbers from 1 to entered number # b = sum of all numbers in a range from 1 up to entered number # Print the sum of all numbers up to entered number # If entered number is lower than 0 print "Please enter integer greater than 0"
4.141045
4
wideryolo/file_utils/file_utils.py
fcakyon/wideryolo-1
0
6623740
<filename>wideryolo/file_utils/file_utils.py from zipfile import ZipFile import shutil import glob import os def create_dir(_dir): if not os.path.exists(_dir): os.makedirs(_dir) def zip_export(save_path): with ZipFile(save_path, 'r') as zip: zip.extractall() os.remove(save_path) def wider_create_dir(train_annotations, val_annotations): root_path = os.getcwd() folders = [train_annotations, val_annotations] for folder in folders: os.makedirs(os.path.join(root_path, folder)) def move(src, dst): if os.path.exists(dst): shutil.rmtree(dst) shutil.move(src, dst) def file_move(root_dir, move_dir): for file in glob.glob(root_dir + '/*'): for main_file in glob.glob(file + '/*'): print(main_file) shutil.move(main_file, move_dir) def train_path(old_train_dir, new_train_dir): create_dir(new_train_dir) file_move(old_train_dir, new_train_dir)
<filename>wideryolo/file_utils/file_utils.py from zipfile import ZipFile import shutil import glob import os def create_dir(_dir): if not os.path.exists(_dir): os.makedirs(_dir) def zip_export(save_path): with ZipFile(save_path, 'r') as zip: zip.extractall() os.remove(save_path) def wider_create_dir(train_annotations, val_annotations): root_path = os.getcwd() folders = [train_annotations, val_annotations] for folder in folders: os.makedirs(os.path.join(root_path, folder)) def move(src, dst): if os.path.exists(dst): shutil.rmtree(dst) shutil.move(src, dst) def file_move(root_dir, move_dir): for file in glob.glob(root_dir + '/*'): for main_file in glob.glob(file + '/*'): print(main_file) shutil.move(main_file, move_dir) def train_path(old_train_dir, new_train_dir): create_dir(new_train_dir) file_move(old_train_dir, new_train_dir)
none
1
2.768835
3
slack-api-delete-files.py
AntonioFeijaoUK/slack-api-delete-files.py
0
6623741
### credits go to @henry-p and @jackcarter ### copied code from here https://gist.github.com/jackcarter/d86808449f0d95060a40#gistcomment-2272461 ### initial gist from here https://gist.github.com/jackcarter/d86808449f0d95060a40 ### minor changes to my preference, file size grater than 0 mb, so deletes all files more than 30 days. # Last update # 2019-11-01 - file size grater than 0 mb, so deletes all files more than 30 days from urllib.parse import urlencode from urllib.request import urlopen import time import json import codecs import datetime from collections import OrderedDict reader = codecs.getreader("utf-8") # Obtain here: https://api.slack.com/custom-integrations/legacy-tokens token = '' # Params for file listing. More info here: https://api.slack.com/methods/files.list # Delete files older than this: days = 30 ts_to = int(time.time()) - days * 24 * 60 * 60 # How many? (Maximum is 1000, otherwise it defaults to 100) count = 1000 # Types? types = 'all' # types = 'spaces,snippets,images,gdocs,zips,pdfs' # types = 'zips' def list_files(): params = { 'token': token, 'ts_to': ts_to, 'count': count, 'types': types } uri = 'https://slack.com/api/files.list' response = reader(urlopen(uri + '?' + urlencode(params))) return json.load(response)['files'] def filter_by_size(files, mb, greater_or_smaller): if greater_or_smaller == 'greater': return [file for file in files if (file['size'] / 1000000) > mb] elif greater_or_smaller == 'smaller': return [file for file in files if (file['size'] / 1000000) < mb] else: return None def info(file): order = ['Title', 'Name', 'Created', 'Size', 'Filetype', 'Comment', 'Permalink', 'Download', 'User', 'Channels'] info = { 'Title': file['title'], 'Name': file['name'], 'Created': datetime.datetime.utcfromtimestamp(file['created']).strftime('%B %d, %Y %H:%M:%S'), 'Size': str(file['size'] / 1000000) + ' MB', 'Filetype': file['filetype'], 'Comment': file['initial_comment'] if 'initial_comment' in file else '', 'Permalink': file['permalink'], 'Download': file['url_private'], 'User': file['user'], 'Channels': file['channels'] } return OrderedDict((key, info[key]) for key in order) def file_ids(files): return [f['id'] for f in files] def delete_files(file_ids): num_files = len(file_ids) for index, file_id in enumerate(file_ids): params = { 'token': token, 'file': file_id } uri = 'https://slack.com/api/files.delete' response = reader(urlopen(uri + '?' + urlencode(params))) print((index + 1, "of", num_files, "-", file_id, json.load(response)['ok'])) files = list_files() # change to your file size 'mb' of your choice files_by_size = filter_by_size(files, 0, 'greater') print(len(files_by_size)) [info(file) for file in files_by_size] file_ids = file_ids(files_by_size) #delete_files(file_ids) # Commented out, so you don't accidentally run this.
### credits go to @henry-p and @jackcarter ### copied code from here https://gist.github.com/jackcarter/d86808449f0d95060a40#gistcomment-2272461 ### initial gist from here https://gist.github.com/jackcarter/d86808449f0d95060a40 ### minor changes to my preference, file size grater than 0 mb, so deletes all files more than 30 days. # Last update # 2019-11-01 - file size grater than 0 mb, so deletes all files more than 30 days from urllib.parse import urlencode from urllib.request import urlopen import time import json import codecs import datetime from collections import OrderedDict reader = codecs.getreader("utf-8") # Obtain here: https://api.slack.com/custom-integrations/legacy-tokens token = '' # Params for file listing. More info here: https://api.slack.com/methods/files.list # Delete files older than this: days = 30 ts_to = int(time.time()) - days * 24 * 60 * 60 # How many? (Maximum is 1000, otherwise it defaults to 100) count = 1000 # Types? types = 'all' # types = 'spaces,snippets,images,gdocs,zips,pdfs' # types = 'zips' def list_files(): params = { 'token': token, 'ts_to': ts_to, 'count': count, 'types': types } uri = 'https://slack.com/api/files.list' response = reader(urlopen(uri + '?' + urlencode(params))) return json.load(response)['files'] def filter_by_size(files, mb, greater_or_smaller): if greater_or_smaller == 'greater': return [file for file in files if (file['size'] / 1000000) > mb] elif greater_or_smaller == 'smaller': return [file for file in files if (file['size'] / 1000000) < mb] else: return None def info(file): order = ['Title', 'Name', 'Created', 'Size', 'Filetype', 'Comment', 'Permalink', 'Download', 'User', 'Channels'] info = { 'Title': file['title'], 'Name': file['name'], 'Created': datetime.datetime.utcfromtimestamp(file['created']).strftime('%B %d, %Y %H:%M:%S'), 'Size': str(file['size'] / 1000000) + ' MB', 'Filetype': file['filetype'], 'Comment': file['initial_comment'] if 'initial_comment' in file else '', 'Permalink': file['permalink'], 'Download': file['url_private'], 'User': file['user'], 'Channels': file['channels'] } return OrderedDict((key, info[key]) for key in order) def file_ids(files): return [f['id'] for f in files] def delete_files(file_ids): num_files = len(file_ids) for index, file_id in enumerate(file_ids): params = { 'token': token, 'file': file_id } uri = 'https://slack.com/api/files.delete' response = reader(urlopen(uri + '?' + urlencode(params))) print((index + 1, "of", num_files, "-", file_id, json.load(response)['ok'])) files = list_files() # change to your file size 'mb' of your choice files_by_size = filter_by_size(files, 0, 'greater') print(len(files_by_size)) [info(file) for file in files_by_size] file_ids = file_ids(files_by_size) #delete_files(file_ids) # Commented out, so you don't accidentally run this.
en
0.793957
### credits go to @henry-p and @jackcarter ### copied code from here https://gist.github.com/jackcarter/d86808449f0d95060a40#gistcomment-2272461 ### initial gist from here https://gist.github.com/jackcarter/d86808449f0d95060a40 ### minor changes to my preference, file size grater than 0 mb, so deletes all files more than 30 days. # Last update # 2019-11-01 - file size grater than 0 mb, so deletes all files more than 30 days # Obtain here: https://api.slack.com/custom-integrations/legacy-tokens # Params for file listing. More info here: https://api.slack.com/methods/files.list # Delete files older than this: # How many? (Maximum is 1000, otherwise it defaults to 100) # Types? # types = 'spaces,snippets,images,gdocs,zips,pdfs' # types = 'zips' # change to your file size 'mb' of your choice #delete_files(file_ids) # Commented out, so you don't accidentally run this.
2.609827
3
common/common.py
developer-foundry/diminish
14
6623742
<gh_stars>10-100 """ This script shares common functions and variables needed by the CLI and TUI scripts. """ import os from pathlib import Path import logging from dotenv import load_dotenv env_path = Path('./environment') / '.env' load_dotenv(dotenv_path=env_path) mu = 0.00001 """ Utilized by the CRLS algorithm to determine the step of gradient descent algorithm """ guiRefreshTimer = 1.0 """ This timer is used by the tui application to determine how long in between a screen refresh """ def get_project_root() -> Path: """ Used to determine the root folder when the tui application spawns the cli process. Parameters ---------- None Returns ------- path : Path The path of the root module of diminish Raises ------ None """ return Path(__file__).parent.parent def getEnvironmentVariables(): """ Returns all environment variables needed by the cli and tui Parameters ---------- None Returns ------- envVars : dictionary A dictionary of all the environment variables needed Raises ------ None """ return { 'mode': getEnvVar("MODE"), 'algorithm': getEnvVar("ALGORITHM"), 'inputFile': getEnvVar("INPUT_FILE"), 'targetFile': getEnvVar("TARGET_FILE"), 'device': getEnvVar("DEVICE"), 'size': getEnvVar("SIZE", True), 'role': getEnvVar("ROLE"), 'waitSize': getEnvVar("WAIT_SIZE", True), 'stepSize': getEnvVar("STEP_SIZE", True), 'tuiConnection': getEnvVar("TUI_CONNECTION") == "True" } def getEnvVar(varName, isInteger=False): """ Returns a single environment variable Parameters ---------- varName : str The name of the environment variable to retrieve isInteger : boolean Is the environment variable an integer and needs to be cast to an int Returns ------- val : str Returns the value of the env var requested Raises ------ None """ if isInteger: return getInt(os.getenv(varName)) else: return os.getenv(varName) def getInt(val): """ Converts a string to an integer with a null check Parameters ---------- val : str The value to convert to an integer Returns ------- val : int Returns converted str value to an int Raises ------ None """ if(val is None): val = 0 else: val = int(val) return val
""" This script shares common functions and variables needed by the CLI and TUI scripts. """ import os from pathlib import Path import logging from dotenv import load_dotenv env_path = Path('./environment') / '.env' load_dotenv(dotenv_path=env_path) mu = 0.00001 """ Utilized by the CRLS algorithm to determine the step of gradient descent algorithm """ guiRefreshTimer = 1.0 """ This timer is used by the tui application to determine how long in between a screen refresh """ def get_project_root() -> Path: """ Used to determine the root folder when the tui application spawns the cli process. Parameters ---------- None Returns ------- path : Path The path of the root module of diminish Raises ------ None """ return Path(__file__).parent.parent def getEnvironmentVariables(): """ Returns all environment variables needed by the cli and tui Parameters ---------- None Returns ------- envVars : dictionary A dictionary of all the environment variables needed Raises ------ None """ return { 'mode': getEnvVar("MODE"), 'algorithm': getEnvVar("ALGORITHM"), 'inputFile': getEnvVar("INPUT_FILE"), 'targetFile': getEnvVar("TARGET_FILE"), 'device': getEnvVar("DEVICE"), 'size': getEnvVar("SIZE", True), 'role': getEnvVar("ROLE"), 'waitSize': getEnvVar("WAIT_SIZE", True), 'stepSize': getEnvVar("STEP_SIZE", True), 'tuiConnection': getEnvVar("TUI_CONNECTION") == "True" } def getEnvVar(varName, isInteger=False): """ Returns a single environment variable Parameters ---------- varName : str The name of the environment variable to retrieve isInteger : boolean Is the environment variable an integer and needs to be cast to an int Returns ------- val : str Returns the value of the env var requested Raises ------ None """ if isInteger: return getInt(os.getenv(varName)) else: return os.getenv(varName) def getInt(val): """ Converts a string to an integer with a null check Parameters ---------- val : str The value to convert to an integer Returns ------- val : int Returns converted str value to an int Raises ------ None """ if(val is None): val = 0 else: val = int(val) return val
en
0.678958
This script shares common functions and variables needed by the CLI and TUI scripts. Utilized by the CRLS algorithm to determine the step of gradient descent algorithm This timer is used by the tui application to determine how long in between a screen refresh Used to determine the root folder when the tui application spawns the cli process. Parameters ---------- None Returns ------- path : Path The path of the root module of diminish Raises ------ None Returns all environment variables needed by the cli and tui Parameters ---------- None Returns ------- envVars : dictionary A dictionary of all the environment variables needed Raises ------ None Returns a single environment variable Parameters ---------- varName : str The name of the environment variable to retrieve isInteger : boolean Is the environment variable an integer and needs to be cast to an int Returns ------- val : str Returns the value of the env var requested Raises ------ None Converts a string to an integer with a null check Parameters ---------- val : str The value to convert to an integer Returns ------- val : int Returns converted str value to an int Raises ------ None
2.79041
3
bin/Python27/Lib/site-packages/tables/tests/create_backcompat_indexes.py
lefevre-fraser/openmeta-mms
0
6623743
<filename>bin/Python27/Lib/site-packages/tables/tests/create_backcompat_indexes.py<gh_stars>0 # -*- coding: utf-8 -*- # Script for creating different kind of indexes in a small space as possible. # This is intended for testing purposes. import tables class Descr(tables.IsDescription): var1 = tables.StringCol(itemsize=4, shape=(), dflt='', pos=0) var2 = tables.BoolCol(shape=(), dflt=False, pos=1) var3 = tables.Int32Col(shape=(), dflt=0, pos=2) var4 = tables.Float64Col(shape=(), dflt=0.0, pos=3) # Parameters for the table and index creation small_chunkshape = (2,) small_blocksizes = (64, 32, 16, 8) nrows = 43 # Create the new file h5fname = 'indexes_2_1.h5' h5file = tables.open_file(h5fname, 'w') t1 = h5file.create_table(h5file.root, 'table1', Descr) row = t1.row for i in range(nrows): row['var1'] = i row['var2'] = i row['var3'] = i row['var4'] = i row.append() t1.flush() # Do a copy of table1 t1.copy(h5file.root, 'table2') # Create indexes of all kinds t1.cols.var1.create_index(0, 'ultralight', _blocksizes=small_blocksizes) t1.cols.var2.create_index(3, 'light', _blocksizes=small_blocksizes) t1.cols.var3.create_index(6, 'medium', _blocksizes=small_blocksizes) t1.cols.var4.create_index(9, 'full', _blocksizes=small_blocksizes) h5file.close()
<filename>bin/Python27/Lib/site-packages/tables/tests/create_backcompat_indexes.py<gh_stars>0 # -*- coding: utf-8 -*- # Script for creating different kind of indexes in a small space as possible. # This is intended for testing purposes. import tables class Descr(tables.IsDescription): var1 = tables.StringCol(itemsize=4, shape=(), dflt='', pos=0) var2 = tables.BoolCol(shape=(), dflt=False, pos=1) var3 = tables.Int32Col(shape=(), dflt=0, pos=2) var4 = tables.Float64Col(shape=(), dflt=0.0, pos=3) # Parameters for the table and index creation small_chunkshape = (2,) small_blocksizes = (64, 32, 16, 8) nrows = 43 # Create the new file h5fname = 'indexes_2_1.h5' h5file = tables.open_file(h5fname, 'w') t1 = h5file.create_table(h5file.root, 'table1', Descr) row = t1.row for i in range(nrows): row['var1'] = i row['var2'] = i row['var3'] = i row['var4'] = i row.append() t1.flush() # Do a copy of table1 t1.copy(h5file.root, 'table2') # Create indexes of all kinds t1.cols.var1.create_index(0, 'ultralight', _blocksizes=small_blocksizes) t1.cols.var2.create_index(3, 'light', _blocksizes=small_blocksizes) t1.cols.var3.create_index(6, 'medium', _blocksizes=small_blocksizes) t1.cols.var4.create_index(9, 'full', _blocksizes=small_blocksizes) h5file.close()
en
0.82293
# -*- coding: utf-8 -*- # Script for creating different kind of indexes in a small space as possible. # This is intended for testing purposes. # Parameters for the table and index creation # Create the new file # Do a copy of table1 # Create indexes of all kinds
2.332006
2
qrgui.py
wooihaw/qrgui
0
6623744
<reponame>wooihaw/qrgui import PySimpleGUI as sg import pyqrcode # Convert from color code to tuple of RGB values plus alpha def color_code_to_tuple(color_code): c = (eval("0x" + color_code[i : i + 2]) for i in (1, 3, 5)) return tuple(c) + (255,) input_layout = sg.Frame( "Input text", [[sg.InputText(key="-IN-", expand_x=True)]], expand_x=True ) slider_layout = sg.Frame( "Size Setting", [ [ sg.Frame( "Scale", [ [ sg.Slider( range=(1, 10), default_value=5, orientation="h", key="-SCALE-", expand_x=True, tooltip="Scale of the QR code", ) ] ], element_justification="center", expand_x=True, expand_y=True, ), sg.Frame( "Quiet Zone", [ [ sg.Slider( range=(0, 5), default_value=4, orientation="h", key="-QUIETZONE-", expand_x=True, tooltip="Quiet zone around the QR code", ) ] ], element_justification="center", expand_x=True, expand_y=True, ), ] ], element_justification="center", expand_x=True, expand_y=True, ) color_layout = sg.Frame( "Color", [ [ sg.In(key="-FGCOLOR-", visible=False), sg.In(key="-BGCOLOR-", visible=False), sg.ColorChooserButton("Foreground", target="-FGCOLOR-", tooltip="Foreground color"), sg.ColorChooserButton("Background", target="-BGCOLOR-", tooltip="Background color"), ] ], element_justification="center", expand_x=True, ) button_layout = sg.Column( [ [ sg.Button("Generate", size=(8,), tooltip="Generate QR code"), sg.Button("Save", size=(8,), disabled=True, tooltip="Save QR code"), sg.Button("Exit", size=(8,), tooltip="Exit application"), ] ], justification="center", ) image_layout = sg.Frame( "Preview", [[sg.Image(filename="", key="-IMAGE-")]], element_justification="center", expand_x=True, expand_y=True, ) layout = [ [input_layout], [slider_layout], [color_layout], [button_layout], [image_layout], ] # Create the window window = sg.Window("QR Code Generator", layout) # Set default colors fgcolor = (0, 0, 0, 255) bgcolor = (255, 255, 255, 255) # Create an event loop while True: event, values = window.read() # End program if user closes window or # presses the Exit button if event in ["Exit", None]: break # Generate QR Code if event == "Generate": try: data = values["-IN-"] scale = int(values["-SCALE-"]) quietzone = int(values["-QUIETZONE-"]) if data: print(data) qr = pyqrcode.create(data) if values["-FGCOLOR-"]: fgcolor = color_code_to_tuple(values["-FGCOLOR-"]) if values["-BGCOLOR-"]: bgcolor = color_code_to_tuple(values["-BGCOLOR-"]) window["-IMAGE-"].update( data=qr.png_as_base64_str( scale=scale, module_color=fgcolor, background=bgcolor, quiet_zone=quietzone, ) ) window["Save"].update(disabled=False) else: sg.popup("Please enter text to encode") except: window["Save"].update(disabled=True) sg.popup_error("Error", "Invalid input") # Save QR Code if event == "Save": try: scale = int(values["-SCALE-"]) quietzone = int(values["-QUIETZONE-"]) filename = sg.popup_get_file( "Save As", save_as=True, file_types=(("PNG", "*.png"),), default_extension=".png", no_window=True, ) if filename: qr.png( filename, scale=scale, module_color=fgcolor, background=bgcolor, quiet_zone=quietzone, ) sg.popup("Saved", filename) print(filename) except: sg.popup_error("Error", "Invalid input") window.close()
import PySimpleGUI as sg import pyqrcode # Convert from color code to tuple of RGB values plus alpha def color_code_to_tuple(color_code): c = (eval("0x" + color_code[i : i + 2]) for i in (1, 3, 5)) return tuple(c) + (255,) input_layout = sg.Frame( "Input text", [[sg.InputText(key="-IN-", expand_x=True)]], expand_x=True ) slider_layout = sg.Frame( "Size Setting", [ [ sg.Frame( "Scale", [ [ sg.Slider( range=(1, 10), default_value=5, orientation="h", key="-SCALE-", expand_x=True, tooltip="Scale of the QR code", ) ] ], element_justification="center", expand_x=True, expand_y=True, ), sg.Frame( "Quiet Zone", [ [ sg.Slider( range=(0, 5), default_value=4, orientation="h", key="-QUIETZONE-", expand_x=True, tooltip="Quiet zone around the QR code", ) ] ], element_justification="center", expand_x=True, expand_y=True, ), ] ], element_justification="center", expand_x=True, expand_y=True, ) color_layout = sg.Frame( "Color", [ [ sg.In(key="-FGCOLOR-", visible=False), sg.In(key="-BGCOLOR-", visible=False), sg.ColorChooserButton("Foreground", target="-FGCOLOR-", tooltip="Foreground color"), sg.ColorChooserButton("Background", target="-BGCOLOR-", tooltip="Background color"), ] ], element_justification="center", expand_x=True, ) button_layout = sg.Column( [ [ sg.Button("Generate", size=(8,), tooltip="Generate QR code"), sg.Button("Save", size=(8,), disabled=True, tooltip="Save QR code"), sg.Button("Exit", size=(8,), tooltip="Exit application"), ] ], justification="center", ) image_layout = sg.Frame( "Preview", [[sg.Image(filename="", key="-IMAGE-")]], element_justification="center", expand_x=True, expand_y=True, ) layout = [ [input_layout], [slider_layout], [color_layout], [button_layout], [image_layout], ] # Create the window window = sg.Window("QR Code Generator", layout) # Set default colors fgcolor = (0, 0, 0, 255) bgcolor = (255, 255, 255, 255) # Create an event loop while True: event, values = window.read() # End program if user closes window or # presses the Exit button if event in ["Exit", None]: break # Generate QR Code if event == "Generate": try: data = values["-IN-"] scale = int(values["-SCALE-"]) quietzone = int(values["-QUIETZONE-"]) if data: print(data) qr = pyqrcode.create(data) if values["-FGCOLOR-"]: fgcolor = color_code_to_tuple(values["-FGCOLOR-"]) if values["-BGCOLOR-"]: bgcolor = color_code_to_tuple(values["-BGCOLOR-"]) window["-IMAGE-"].update( data=qr.png_as_base64_str( scale=scale, module_color=fgcolor, background=bgcolor, quiet_zone=quietzone, ) ) window["Save"].update(disabled=False) else: sg.popup("Please enter text to encode") except: window["Save"].update(disabled=True) sg.popup_error("Error", "Invalid input") # Save QR Code if event == "Save": try: scale = int(values["-SCALE-"]) quietzone = int(values["-QUIETZONE-"]) filename = sg.popup_get_file( "Save As", save_as=True, file_types=(("PNG", "*.png"),), default_extension=".png", no_window=True, ) if filename: qr.png( filename, scale=scale, module_color=fgcolor, background=bgcolor, quiet_zone=quietzone, ) sg.popup("Saved", filename) print(filename) except: sg.popup_error("Error", "Invalid input") window.close()
en
0.56707
# Convert from color code to tuple of RGB values plus alpha # Create the window # Set default colors # Create an event loop # End program if user closes window or # presses the Exit button # Generate QR Code # Save QR Code
2.862779
3
stylelens/dataset/df/extract_object.py
williamcameron/bl-magi
0
6623745
<gh_stars>0 import os from bson.objectid import ObjectId from stylelens_dataset.images import Images from stylelens_dataset.objects import Objects from util import s3 import urllib.request from PIL import Image AWS_BUCKET = 'stylelens-dataset' AWS_ACCESS_KEY = os.environ['AWS_ACCESS_KEY'].replace('"', '') AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'].replace('"', '') storage = s3.S3(AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY) def upload_image_to_storage(file): print("upload_image_to_storage") key = os.path.join('deepfashion', 'obj', file) is_public = True file_url = storage.upload_file_to_bucket(AWS_BUCKET, file, key, is_public=is_public) return file_url def get_image_size(img_file): with Image.open(img_file) as img: return img.size def crop(image): file = image['url'] new_file_name = str(image['_id']) + '.jpg' bbox = image['bbox'] left = bbox['x1'] top = bbox['y1'] right = bbox['x2'] bottom = bbox['y2'] try: f = urllib.request.urlopen(file) im = Image.open(f) area = (left, top, left + abs(left-right), top + abs(bottom-top)) cropped = im.crop(area) cropped.save(new_file_name) uploaded_path = upload_image_to_storage(new_file_name) os.remove(new_file_name) except Exception as e: print(e) return uploaded_path if __name__ == '__main__': print('start') image_api = Images() object_api = Objects() offset = 0 limit = 100 while True: try: res = image_api.get_images_by_source(source='deepfashion', offset=offset, limit=limit) for image in res: cropped_file = crop(image) image['url'] = cropped_file image['image_id'] = str(image['_id']) image['bbox'] = None image['width'] = None image['height'] = None object_api.add_object(image) if limit > len(res): break else: offset = offset + limit except Exception as e: print(e)
import os from bson.objectid import ObjectId from stylelens_dataset.images import Images from stylelens_dataset.objects import Objects from util import s3 import urllib.request from PIL import Image AWS_BUCKET = 'stylelens-dataset' AWS_ACCESS_KEY = os.environ['AWS_ACCESS_KEY'].replace('"', '') AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'].replace('"', '') storage = s3.S3(AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY) def upload_image_to_storage(file): print("upload_image_to_storage") key = os.path.join('deepfashion', 'obj', file) is_public = True file_url = storage.upload_file_to_bucket(AWS_BUCKET, file, key, is_public=is_public) return file_url def get_image_size(img_file): with Image.open(img_file) as img: return img.size def crop(image): file = image['url'] new_file_name = str(image['_id']) + '.jpg' bbox = image['bbox'] left = bbox['x1'] top = bbox['y1'] right = bbox['x2'] bottom = bbox['y2'] try: f = urllib.request.urlopen(file) im = Image.open(f) area = (left, top, left + abs(left-right), top + abs(bottom-top)) cropped = im.crop(area) cropped.save(new_file_name) uploaded_path = upload_image_to_storage(new_file_name) os.remove(new_file_name) except Exception as e: print(e) return uploaded_path if __name__ == '__main__': print('start') image_api = Images() object_api = Objects() offset = 0 limit = 100 while True: try: res = image_api.get_images_by_source(source='deepfashion', offset=offset, limit=limit) for image in res: cropped_file = crop(image) image['url'] = cropped_file image['image_id'] = str(image['_id']) image['bbox'] = None image['width'] = None image['height'] = None object_api.add_object(image) if limit > len(res): break else: offset = offset + limit except Exception as e: print(e)
none
1
2.474064
2
src/crumhorn/configuration/environment/environment.py
jelford/crumhorn
0
6623746
# coding=utf-8 import os from crumhorn.configuration.environment import machinespec_repository class CrumhornEnvironment: def __init__(self, machinespec_repository, cloud_config): self.cloud_config = cloud_config self.machinespec_repository = machinespec_repository def build_environment(): machinespec_repo = machinespec_repository.MachineSpecRepository( {'repository.searchpath': ':'.join([os.getcwd(), os.environ.get('crumhorn.repository.searchpath', '')])}) cloud_config = {'digitaloceantoken': os.environ['digitaloceantoken']} return CrumhornEnvironment(machinespec_repo, cloud_config)
# coding=utf-8 import os from crumhorn.configuration.environment import machinespec_repository class CrumhornEnvironment: def __init__(self, machinespec_repository, cloud_config): self.cloud_config = cloud_config self.machinespec_repository = machinespec_repository def build_environment(): machinespec_repo = machinespec_repository.MachineSpecRepository( {'repository.searchpath': ':'.join([os.getcwd(), os.environ.get('crumhorn.repository.searchpath', '')])}) cloud_config = {'digitaloceantoken': os.environ['digitaloceantoken']} return CrumhornEnvironment(machinespec_repo, cloud_config)
en
0.644078
# coding=utf-8
2.147379
2
packages/swapi_matches.py
palaciodaniel/lambda-swapi
0
6623747
import requests import time from fuzzywuzzy import fuzz from typing import List, Optional def get_swapi_matches(name_one: str, name_two: str) -> List[Optional[List]]: """ Looks for the inputted characters on the SWAPI database and returns the raw URL for every movie they appear. """ if (len(name_one) == 0) \ or (len(name_two) == 0): raise SystemExit("|ERROR| -> Please write some characters to search.") url = "http://swapi.dev/api/people/?page=1" character_films = [] threshold = 0 while True: # If both names were found, the loop will be aborted. if threshold == 2: character_films.sort(key=len) # If nested lists are not sorted, Unit Tests will fail. print("Both names were found. Finishing search.") return character_films # Requesting information to database print("Inspecting", url) r = requests.get(url) time.sleep(0.5) # Analyzing the results for matches json_results = r.json()["results"] for element in json_results: # If both names were found, the loop will be aborted. if threshold == 2: break if (fuzz.WRatio(element["name"], name_one) >= 75) \ or (fuzz.WRatio(element["name"], name_two) >= 75): print("- " + element["name"] + " <--- MATCH DETECTED!") character_films.append(element["films"]) threshold += 1 # If there are no more pages to check, this ends the loop if r.json()["next"] is None: break else: # Updating with the next page URL... url = r.json()["next"] return character_films
import requests import time from fuzzywuzzy import fuzz from typing import List, Optional def get_swapi_matches(name_one: str, name_two: str) -> List[Optional[List]]: """ Looks for the inputted characters on the SWAPI database and returns the raw URL for every movie they appear. """ if (len(name_one) == 0) \ or (len(name_two) == 0): raise SystemExit("|ERROR| -> Please write some characters to search.") url = "http://swapi.dev/api/people/?page=1" character_films = [] threshold = 0 while True: # If both names were found, the loop will be aborted. if threshold == 2: character_films.sort(key=len) # If nested lists are not sorted, Unit Tests will fail. print("Both names were found. Finishing search.") return character_films # Requesting information to database print("Inspecting", url) r = requests.get(url) time.sleep(0.5) # Analyzing the results for matches json_results = r.json()["results"] for element in json_results: # If both names were found, the loop will be aborted. if threshold == 2: break if (fuzz.WRatio(element["name"], name_one) >= 75) \ or (fuzz.WRatio(element["name"], name_two) >= 75): print("- " + element["name"] + " <--- MATCH DETECTED!") character_films.append(element["films"]) threshold += 1 # If there are no more pages to check, this ends the loop if r.json()["next"] is None: break else: # Updating with the next page URL... url = r.json()["next"] return character_films
en
0.900592
Looks for the inputted characters on the SWAPI database and returns the raw URL for every movie they appear. # If both names were found, the loop will be aborted. # If nested lists are not sorted, Unit Tests will fail. # Requesting information to database # Analyzing the results for matches # If both names were found, the loop will be aborted. # If there are no more pages to check, this ends the loop # Updating with the next page URL...
3.22409
3
tools/gyp/test/mac/xcode-env-order/test.gyp
FloeDesignTechnologies/node
17
6623748
<gh_stars>10-100 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'test_app', 'product_name': 'Test', 'type': 'executable', 'mac_bundle': 1, 'sources': [ 'main.c', ], # Env vars in copies. 'copies': [ { 'destination': '<(PRODUCT_DIR)/${PRODUCT_NAME}-copy-brace', 'files': [ 'main.c', ], # ${SOURCE_ROOT} doesn't work with xcode }, { 'destination': '<(PRODUCT_DIR)/$(PRODUCT_NAME)-copy-paren', 'files': [ '$(SOURCE_ROOT)/main.c', ], }, { 'destination': '<(PRODUCT_DIR)/$PRODUCT_NAME-copy-bare', 'files': [ 'main.c', ], # $SOURCE_ROOT doesn't work with xcode }, ], # Env vars in actions. 'actions': [ { 'action_name': 'Action copy braces ${PRODUCT_NAME}', 'description': 'Action copy braces ${PRODUCT_NAME}', 'inputs': [ '${SOURCE_ROOT}/main.c' ], # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). 'outputs': [ '<(PRODUCT_DIR)/action-copy-brace.txt' ], 'action': [ 'cp', '${SOURCE_ROOT}/main.c', '<(PRODUCT_DIR)/action-copy-brace.txt' ], }, { 'action_name': 'Action copy parens ${PRODUCT_NAME}', 'description': 'Action copy parens ${PRODUCT_NAME}', 'inputs': [ '${SOURCE_ROOT}/main.c' ], # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). 'outputs': [ '<(PRODUCT_DIR)/action-copy-paren.txt' ], 'action': [ 'cp', '${SOURCE_ROOT}/main.c', '<(PRODUCT_DIR)/action-copy-paren.txt' ], }, { 'action_name': 'Action copy bare ${PRODUCT_NAME}', 'description': 'Action copy bare ${PRODUCT_NAME}', 'inputs': [ '${SOURCE_ROOT}/main.c' ], # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). 'outputs': [ '<(PRODUCT_DIR)/action-copy-bare.txt' ], 'action': [ 'cp', '${SOURCE_ROOT}/main.c', '<(PRODUCT_DIR)/action-copy-bare.txt' ], }, ], # Env vars in copies. 'xcode_settings': { 'INFOPLIST_FILE': 'Info.plist', 'STRING_KEY': '/Source/Project', 'BRACE_DEPENDENT_KEY2': '${STRING_KEY}/${PRODUCT_NAME}', 'BRACE_DEPENDENT_KEY1': 'D:${BRACE_DEPENDENT_KEY2}', 'BRACE_DEPENDENT_KEY3': '${PRODUCT_TYPE}:${BRACE_DEPENDENT_KEY1}', 'PAREN_DEPENDENT_KEY2': '$(STRING_KEY)/$(PRODUCT_NAME)', 'PAREN_DEPENDENT_KEY1': 'D:$(PAREN_DEPENDENT_KEY2)', 'PAREN_DEPENDENT_KEY3': '$(PRODUCT_TYPE):$(PAREN_DEPENDENT_KEY1)', 'BARE_DEPENDENT_KEY2': '$STRING_KEY/$PRODUCT_NAME', 'BARE_DEPENDENT_KEY1': 'D:$BARE_DEPENDENT_KEY2', 'BARE_DEPENDENT_KEY3': '$PRODUCT_TYPE:$BARE_DEPENDENT_KEY1', 'MIXED_DEPENDENT_KEY': '${STRING_KEY}:$(PRODUCT_NAME):$MACH_O_TYPE', }, }, ], }
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'test_app', 'product_name': 'Test', 'type': 'executable', 'mac_bundle': 1, 'sources': [ 'main.c', ], # Env vars in copies. 'copies': [ { 'destination': '<(PRODUCT_DIR)/${PRODUCT_NAME}-copy-brace', 'files': [ 'main.c', ], # ${SOURCE_ROOT} doesn't work with xcode }, { 'destination': '<(PRODUCT_DIR)/$(PRODUCT_NAME)-copy-paren', 'files': [ '$(SOURCE_ROOT)/main.c', ], }, { 'destination': '<(PRODUCT_DIR)/$PRODUCT_NAME-copy-bare', 'files': [ 'main.c', ], # $SOURCE_ROOT doesn't work with xcode }, ], # Env vars in actions. 'actions': [ { 'action_name': 'Action copy braces ${PRODUCT_NAME}', 'description': 'Action copy braces ${PRODUCT_NAME}', 'inputs': [ '${SOURCE_ROOT}/main.c' ], # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). 'outputs': [ '<(PRODUCT_DIR)/action-copy-brace.txt' ], 'action': [ 'cp', '${SOURCE_ROOT}/main.c', '<(PRODUCT_DIR)/action-copy-brace.txt' ], }, { 'action_name': 'Action copy parens ${PRODUCT_NAME}', 'description': 'Action copy parens ${PRODUCT_NAME}', 'inputs': [ '${SOURCE_ROOT}/main.c' ], # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). 'outputs': [ '<(PRODUCT_DIR)/action-copy-paren.txt' ], 'action': [ 'cp', '${SOURCE_ROOT}/main.c', '<(PRODUCT_DIR)/action-copy-paren.txt' ], }, { 'action_name': 'Action copy bare ${PRODUCT_NAME}', 'description': 'Action copy bare ${PRODUCT_NAME}', 'inputs': [ '${SOURCE_ROOT}/main.c' ], # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). 'outputs': [ '<(PRODUCT_DIR)/action-copy-bare.txt' ], 'action': [ 'cp', '${SOURCE_ROOT}/main.c', '<(PRODUCT_DIR)/action-copy-bare.txt' ], }, ], # Env vars in copies. 'xcode_settings': { 'INFOPLIST_FILE': 'Info.plist', 'STRING_KEY': '/Source/Project', 'BRACE_DEPENDENT_KEY2': '${STRING_KEY}/${PRODUCT_NAME}', 'BRACE_DEPENDENT_KEY1': 'D:${BRACE_DEPENDENT_KEY2}', 'BRACE_DEPENDENT_KEY3': '${PRODUCT_TYPE}:${BRACE_DEPENDENT_KEY1}', 'PAREN_DEPENDENT_KEY2': '$(STRING_KEY)/$(PRODUCT_NAME)', 'PAREN_DEPENDENT_KEY1': 'D:$(PAREN_DEPENDENT_KEY2)', 'PAREN_DEPENDENT_KEY3': '$(PRODUCT_TYPE):$(PAREN_DEPENDENT_KEY1)', 'BARE_DEPENDENT_KEY2': '$STRING_KEY/$PRODUCT_NAME', 'BARE_DEPENDENT_KEY1': 'D:$BARE_DEPENDENT_KEY2', 'BARE_DEPENDENT_KEY3': '$PRODUCT_TYPE:$BARE_DEPENDENT_KEY1', 'MIXED_DEPENDENT_KEY': '${STRING_KEY}:$(PRODUCT_NAME):$MACH_O_TYPE', }, }, ], }
en
0.922327
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Env vars in copies. # ${SOURCE_ROOT} doesn't work with xcode # $SOURCE_ROOT doesn't work with xcode # Env vars in actions. # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). # Referencing ${PRODUCT_NAME} in action outputs doesn't work with # the Xcode generator (PRODUCT_NAME expands to "Test Support"). # Env vars in copies.
1.550014
2
utils/pascal_voc_loader.py
lejeunel/glia
0
6623749
<reponame>lejeunel/glia<gh_stars>0 import os from os.path import join as pjoin import collections import json import torch import numpy as np import scipy.misc as m import scipy.io as io import matplotlib.pyplot as plt import glob from PIL import Image from tqdm import tqdm from skimage import transform from skimage import measure import imgaug as ia import pandas as pd class pascalVOCLoader: """Data loader for the Pascal VOC semantic segmentation dataset. Annotations from both the original VOC data (which consist of RGB images in which colours map to specific classes) and the SBD (Berkely) dataset (where annotations are stored as .mat files) are converted into a common `label_mask` format. Under this format, each mask is an (M,N) array of integer values from 0 to 21, where 0 represents the background class. The label masks are stored in a new folder, called `pre_encoded`, which is added as a subdirectory of the `SegmentationClass` folder in the original Pascal VOC data layout. A total of five data splits are provided for working with the VOC data: train: The original VOC 2012 training data - 1464 images val: The original VOC 2012 validation data - 1449 images trainval: The combination of `train` and `val` - 2913 images train_aug: The unique images present in both the train split and training images from SBD: - 8829 images (the unique members of the result of combining lists of length 1464 and 8498) train_aug_val: The original VOC 2012 validation data minus the images present in `train_aug` (This is done with the same logic as the validation set used in FCN PAMI paper, but with VOC 2012 rather than VOC 2011) - 904 images """ def __init__( self, root): self.sbd_path = os.path.join(root, 'VOC2012', 'benchmark_RELEASE') self.root = os.path.join(root, 'VOC2012', 'VOCdevkit', 'VOC2012') self.n_classes = 21 self.files = collections.defaultdict(list) # get all image file names path = pjoin(self.root, "SegmentationClass/pre_encoded", "*.png") self.all_files = sorted(glob.glob(path)) self.setup_annotations() # Find label (category) self.files_categories = sorted(glob.glob(pjoin(self.root, 'ImageSets/Main/*_trainval.txt'))) self.categories = [ 'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ] self.file_to_cat = dict() for f, c in zip(self.files_categories, self.categories): df = pd.read_csv( f, delim_whitespace=True, header=None, names=['filename', 'true']) self.file_to_cat.update({f_: c for f_ in df[df['true'] == 1]['filename']}) # get all files for semantic segmentation with segmentation maps def __len__(self): return len(self.all_files) def __getitem__(self, index): truth_path = self.all_files[index] im_name = os.path.splitext(os.path.split(truth_path)[-1])[0] im_path = pjoin(self.root, "JPEGImages", im_name + ".jpg") im = np.asarray(Image.open(im_path)) segm = np.asarray(Image.open(truth_path)) # identify connex labels lbls_idx = np.array([l for l in np.unique(segm) if l != 0]) labels_names = [self.categories[l] for l in lbls_idx] # decompose truth truth = [(segm == l).astype(np.uint8) for l in np.unique(segm)[1:]] # check if some objects have left the frame... # idx_ok = [i for i in range(len(truth)) if(np.sum(truth[i])/truth[i].size>0.005)] idx_ok = [i for i in range(len(truth)) if(np.sum(truth[i])>0)] truth = [t for i,t in enumerate(truth) if(i in idx_ok)] lbls_idx = [t for i,t in enumerate(lbls_idx) if(i in idx_ok)] labels_names = [t for i,t in enumerate(labels_names) if(i in idx_ok)] return { 'image': im, 'label/segmentations': truth, 'label/idxs': lbls_idx, 'label/names': labels_names } def sample_uniform(self, n=1): ids = np.random.choice(np.arange(0, len(self), size=n, replace=False)) out = [self.__getitem__(i) for i in ids] if(n == 1): return out[0] else: return out def get_pascal_labels(self): """Load the mapping that associates pascal classes with label colors Returns: np.ndarray with dimensions (21, 3) """ return np.asarray([ [0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128], ]) def encode_segmap(self, mask): """Encode segmentation label images as pascal classes Args: mask (np.ndarray): raw segmentation label image of dimension (M, N, 3), in which the Pascal classes are encoded as colours. Returns: (np.ndarray): class map with dimensions (M,N), where the value at a given location is the integer denoting the class index. """ mask = mask.astype(int) label_mask = np.zeros((mask.shape[0], mask.shape[1]), dtype=np.int16) for ii, label in enumerate(self.get_pascal_labels()): label_mask[np.where(np.all(mask == label, axis=-1))[:2]] = ii label_mask = label_mask.astype(int) return label_mask def decode_segmap(self, label_mask, plot=False): """Decode segmentation class labels into a color image Args: label_mask (np.ndarray): an (M,N) array of integer values denoting the class label at each spatial location. plot (bool, optional): whether to show the resulting color image in a figure. Returns: (np.ndarray, optional): the resulting decoded color image. """ label_colours = self.get_pascal_labels() r = label_mask.copy() g = label_mask.copy() b = label_mask.copy() for ll in range(0, self.n_classes): r[label_mask == ll] = label_colours[ll, 0] g[label_mask == ll] = label_colours[ll, 1] b[label_mask == ll] = label_colours[ll, 2] rgb = np.zeros((label_mask.shape[0], label_mask.shape[1], 3)) rgb[:, :, 0] = r / 255.0 rgb[:, :, 1] = g / 255.0 rgb[:, :, 2] = b / 255.0 if plot: plt.imshow(rgb) plt.show() else: return rgb def setup_annotations(self): """Sets up Berkley annotations by adding image indices to the `train_aug` split and pre-encode all segmentation labels into the common label_mask format (if this has not already been done). This function also defines the `train_aug` and `train_aug_val` data splits according to the description in the class docstring """ sbd_path = self.sbd_path target_path = pjoin(self.root, "SegmentationClass/pre_encoded") if not os.path.exists(target_path): os.makedirs(target_path) path = pjoin(sbd_path, "dataset/train.txt") sbd_train_list = tuple(open(path, "r")) sbd_train_list = [id_.rstrip() for id_ in sbd_train_list] train_aug = self.files["train"] + sbd_train_list pre_encoded = glob.glob(pjoin(target_path, "*.png")) if len(pre_encoded) != 9733: print("Pre-encoding segmentation masks...") for ii in tqdm(sbd_train_list): lbl_path = pjoin(sbd_path, "dataset/cls", ii + ".mat") data = io.loadmat(lbl_path) lbl = data["GTcls"][0]["Segmentation"][0].astype(np.int32) lbl = m.toimage(lbl, high=lbl.max(), low=lbl.min()) m.imsave(pjoin(target_path, ii + ".png"), lbl)
import os from os.path import join as pjoin import collections import json import torch import numpy as np import scipy.misc as m import scipy.io as io import matplotlib.pyplot as plt import glob from PIL import Image from tqdm import tqdm from skimage import transform from skimage import measure import imgaug as ia import pandas as pd class pascalVOCLoader: """Data loader for the Pascal VOC semantic segmentation dataset. Annotations from both the original VOC data (which consist of RGB images in which colours map to specific classes) and the SBD (Berkely) dataset (where annotations are stored as .mat files) are converted into a common `label_mask` format. Under this format, each mask is an (M,N) array of integer values from 0 to 21, where 0 represents the background class. The label masks are stored in a new folder, called `pre_encoded`, which is added as a subdirectory of the `SegmentationClass` folder in the original Pascal VOC data layout. A total of five data splits are provided for working with the VOC data: train: The original VOC 2012 training data - 1464 images val: The original VOC 2012 validation data - 1449 images trainval: The combination of `train` and `val` - 2913 images train_aug: The unique images present in both the train split and training images from SBD: - 8829 images (the unique members of the result of combining lists of length 1464 and 8498) train_aug_val: The original VOC 2012 validation data minus the images present in `train_aug` (This is done with the same logic as the validation set used in FCN PAMI paper, but with VOC 2012 rather than VOC 2011) - 904 images """ def __init__( self, root): self.sbd_path = os.path.join(root, 'VOC2012', 'benchmark_RELEASE') self.root = os.path.join(root, 'VOC2012', 'VOCdevkit', 'VOC2012') self.n_classes = 21 self.files = collections.defaultdict(list) # get all image file names path = pjoin(self.root, "SegmentationClass/pre_encoded", "*.png") self.all_files = sorted(glob.glob(path)) self.setup_annotations() # Find label (category) self.files_categories = sorted(glob.glob(pjoin(self.root, 'ImageSets/Main/*_trainval.txt'))) self.categories = [ 'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ] self.file_to_cat = dict() for f, c in zip(self.files_categories, self.categories): df = pd.read_csv( f, delim_whitespace=True, header=None, names=['filename', 'true']) self.file_to_cat.update({f_: c for f_ in df[df['true'] == 1]['filename']}) # get all files for semantic segmentation with segmentation maps def __len__(self): return len(self.all_files) def __getitem__(self, index): truth_path = self.all_files[index] im_name = os.path.splitext(os.path.split(truth_path)[-1])[0] im_path = pjoin(self.root, "JPEGImages", im_name + ".jpg") im = np.asarray(Image.open(im_path)) segm = np.asarray(Image.open(truth_path)) # identify connex labels lbls_idx = np.array([l for l in np.unique(segm) if l != 0]) labels_names = [self.categories[l] for l in lbls_idx] # decompose truth truth = [(segm == l).astype(np.uint8) for l in np.unique(segm)[1:]] # check if some objects have left the frame... # idx_ok = [i for i in range(len(truth)) if(np.sum(truth[i])/truth[i].size>0.005)] idx_ok = [i for i in range(len(truth)) if(np.sum(truth[i])>0)] truth = [t for i,t in enumerate(truth) if(i in idx_ok)] lbls_idx = [t for i,t in enumerate(lbls_idx) if(i in idx_ok)] labels_names = [t for i,t in enumerate(labels_names) if(i in idx_ok)] return { 'image': im, 'label/segmentations': truth, 'label/idxs': lbls_idx, 'label/names': labels_names } def sample_uniform(self, n=1): ids = np.random.choice(np.arange(0, len(self), size=n, replace=False)) out = [self.__getitem__(i) for i in ids] if(n == 1): return out[0] else: return out def get_pascal_labels(self): """Load the mapping that associates pascal classes with label colors Returns: np.ndarray with dimensions (21, 3) """ return np.asarray([ [0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128], ]) def encode_segmap(self, mask): """Encode segmentation label images as pascal classes Args: mask (np.ndarray): raw segmentation label image of dimension (M, N, 3), in which the Pascal classes are encoded as colours. Returns: (np.ndarray): class map with dimensions (M,N), where the value at a given location is the integer denoting the class index. """ mask = mask.astype(int) label_mask = np.zeros((mask.shape[0], mask.shape[1]), dtype=np.int16) for ii, label in enumerate(self.get_pascal_labels()): label_mask[np.where(np.all(mask == label, axis=-1))[:2]] = ii label_mask = label_mask.astype(int) return label_mask def decode_segmap(self, label_mask, plot=False): """Decode segmentation class labels into a color image Args: label_mask (np.ndarray): an (M,N) array of integer values denoting the class label at each spatial location. plot (bool, optional): whether to show the resulting color image in a figure. Returns: (np.ndarray, optional): the resulting decoded color image. """ label_colours = self.get_pascal_labels() r = label_mask.copy() g = label_mask.copy() b = label_mask.copy() for ll in range(0, self.n_classes): r[label_mask == ll] = label_colours[ll, 0] g[label_mask == ll] = label_colours[ll, 1] b[label_mask == ll] = label_colours[ll, 2] rgb = np.zeros((label_mask.shape[0], label_mask.shape[1], 3)) rgb[:, :, 0] = r / 255.0 rgb[:, :, 1] = g / 255.0 rgb[:, :, 2] = b / 255.0 if plot: plt.imshow(rgb) plt.show() else: return rgb def setup_annotations(self): """Sets up Berkley annotations by adding image indices to the `train_aug` split and pre-encode all segmentation labels into the common label_mask format (if this has not already been done). This function also defines the `train_aug` and `train_aug_val` data splits according to the description in the class docstring """ sbd_path = self.sbd_path target_path = pjoin(self.root, "SegmentationClass/pre_encoded") if not os.path.exists(target_path): os.makedirs(target_path) path = pjoin(sbd_path, "dataset/train.txt") sbd_train_list = tuple(open(path, "r")) sbd_train_list = [id_.rstrip() for id_ in sbd_train_list] train_aug = self.files["train"] + sbd_train_list pre_encoded = glob.glob(pjoin(target_path, "*.png")) if len(pre_encoded) != 9733: print("Pre-encoding segmentation masks...") for ii in tqdm(sbd_train_list): lbl_path = pjoin(sbd_path, "dataset/cls", ii + ".mat") data = io.loadmat(lbl_path) lbl = data["GTcls"][0]["Segmentation"][0].astype(np.int32) lbl = m.toimage(lbl, high=lbl.max(), low=lbl.min()) m.imsave(pjoin(target_path, ii + ".png"), lbl)
en
0.802822
Data loader for the Pascal VOC semantic segmentation dataset. Annotations from both the original VOC data (which consist of RGB images in which colours map to specific classes) and the SBD (Berkely) dataset (where annotations are stored as .mat files) are converted into a common `label_mask` format. Under this format, each mask is an (M,N) array of integer values from 0 to 21, where 0 represents the background class. The label masks are stored in a new folder, called `pre_encoded`, which is added as a subdirectory of the `SegmentationClass` folder in the original Pascal VOC data layout. A total of five data splits are provided for working with the VOC data: train: The original VOC 2012 training data - 1464 images val: The original VOC 2012 validation data - 1449 images trainval: The combination of `train` and `val` - 2913 images train_aug: The unique images present in both the train split and training images from SBD: - 8829 images (the unique members of the result of combining lists of length 1464 and 8498) train_aug_val: The original VOC 2012 validation data minus the images present in `train_aug` (This is done with the same logic as the validation set used in FCN PAMI paper, but with VOC 2012 rather than VOC 2011) - 904 images # get all image file names # Find label (category) # get all files for semantic segmentation with segmentation maps # identify connex labels # decompose truth # check if some objects have left the frame... # idx_ok = [i for i in range(len(truth)) if(np.sum(truth[i])/truth[i].size>0.005)] Load the mapping that associates pascal classes with label colors Returns: np.ndarray with dimensions (21, 3) Encode segmentation label images as pascal classes Args: mask (np.ndarray): raw segmentation label image of dimension (M, N, 3), in which the Pascal classes are encoded as colours. Returns: (np.ndarray): class map with dimensions (M,N), where the value at a given location is the integer denoting the class index. Decode segmentation class labels into a color image Args: label_mask (np.ndarray): an (M,N) array of integer values denoting the class label at each spatial location. plot (bool, optional): whether to show the resulting color image in a figure. Returns: (np.ndarray, optional): the resulting decoded color image. Sets up Berkley annotations by adding image indices to the `train_aug` split and pre-encode all segmentation labels into the common label_mask format (if this has not already been done). This function also defines the `train_aug` and `train_aug_val` data splits according to the description in the class docstring
2.3028
2
basicts/archs/D2STGNN_arch/DynamicGraphConv/Utils/distance.py
zezhishao/GuanCang_BasicTS
3
6623750
<filename>basicts/archs/D2STGNN_arch/DynamicGraphConv/Utils/distance.py import math import torch import torch.nn as nn import torch.nn.functional as F class DistanceFunction(nn.Module): def __init__(self, **model_args): super().__init__() # attributes self.hidden_dim = model_args['num_hidden'] # hidden dimension of self.node_dim = model_args['node_hidden'] self.time_slot_emb_dim = self.hidden_dim self.input_seq_len = model_args['seq_length'] # Time Series Feature Extraction self.dropout = nn.Dropout(model_args['dropout']) self.fc_ts_emb1 = nn.Linear(self.input_seq_len, self.hidden_dim * 2) self.fc_ts_emb2 = nn.Linear(self.hidden_dim * 2, self.hidden_dim) self.ts_feat_dim= self.hidden_dim # Time Slot Embedding Extraction self.time_slot_embedding = nn.Linear(model_args['time_emb_dim'], self.time_slot_emb_dim) # Distance Score self.all_feat_dim = self.ts_feat_dim + self.node_dim + model_args['time_emb_dim']*2 self.WQ = nn.Linear(self.all_feat_dim, self.hidden_dim, bias=False) # TODO more output dimension self.WK = nn.Linear(self.all_feat_dim, self.hidden_dim, bias=False) self.bn = nn.BatchNorm1d(self.hidden_dim*2) def reset_parameters(self): for q_vec in self.q_vecs: nn.init.xavier_normal_(q_vec.data) for bias in self.biases: nn.init.zeros_(bias.data) def forward(self, X, E_d, E_u, T_D, D_W): # last pooling T_D = T_D[:, -1, :, :] D_W = D_W[:, -1, :, :] # dynamic information X = X[:, :, :, 0].transpose(1, 2).contiguous() # X->[batch_size, seq_len, num_nodes]->[batch_size, num_nodes, seq_len] [batch_size, num_nodes, seq_len] = X.shape X = X.view(batch_size * num_nodes, seq_len) dy_feat = self.fc_ts_emb2(self.dropout(self.bn(F.relu(self.fc_ts_emb1(X))))) # [batchsize, num_nodes, hidden_dim] dy_feat = dy_feat.view(batch_size, num_nodes, -1) # node embedding emb1 = E_d.unsqueeze(0).expand(batch_size, -1, -1) emb2 = E_u.unsqueeze(0).expand(batch_size, -1, -1) # distance calculation X1 = torch.cat([dy_feat, T_D, D_W, emb1], dim=-1) # hidden state for calculating distance X2 = torch.cat([dy_feat, T_D, D_W, emb2], dim=-1) # hidden state for calculating distance X = [X1, X2] adjacent_list = [] for _ in X: Q = self.WQ(_) K = self.WK(_) QKT = torch.bmm(Q, K.transpose(-1, -2)) / math.sqrt(self.hidden_dim) W = torch.softmax(QKT, dim=-1) adjacent_list.append(W) return adjacent_list
<filename>basicts/archs/D2STGNN_arch/DynamicGraphConv/Utils/distance.py import math import torch import torch.nn as nn import torch.nn.functional as F class DistanceFunction(nn.Module): def __init__(self, **model_args): super().__init__() # attributes self.hidden_dim = model_args['num_hidden'] # hidden dimension of self.node_dim = model_args['node_hidden'] self.time_slot_emb_dim = self.hidden_dim self.input_seq_len = model_args['seq_length'] # Time Series Feature Extraction self.dropout = nn.Dropout(model_args['dropout']) self.fc_ts_emb1 = nn.Linear(self.input_seq_len, self.hidden_dim * 2) self.fc_ts_emb2 = nn.Linear(self.hidden_dim * 2, self.hidden_dim) self.ts_feat_dim= self.hidden_dim # Time Slot Embedding Extraction self.time_slot_embedding = nn.Linear(model_args['time_emb_dim'], self.time_slot_emb_dim) # Distance Score self.all_feat_dim = self.ts_feat_dim + self.node_dim + model_args['time_emb_dim']*2 self.WQ = nn.Linear(self.all_feat_dim, self.hidden_dim, bias=False) # TODO more output dimension self.WK = nn.Linear(self.all_feat_dim, self.hidden_dim, bias=False) self.bn = nn.BatchNorm1d(self.hidden_dim*2) def reset_parameters(self): for q_vec in self.q_vecs: nn.init.xavier_normal_(q_vec.data) for bias in self.biases: nn.init.zeros_(bias.data) def forward(self, X, E_d, E_u, T_D, D_W): # last pooling T_D = T_D[:, -1, :, :] D_W = D_W[:, -1, :, :] # dynamic information X = X[:, :, :, 0].transpose(1, 2).contiguous() # X->[batch_size, seq_len, num_nodes]->[batch_size, num_nodes, seq_len] [batch_size, num_nodes, seq_len] = X.shape X = X.view(batch_size * num_nodes, seq_len) dy_feat = self.fc_ts_emb2(self.dropout(self.bn(F.relu(self.fc_ts_emb1(X))))) # [batchsize, num_nodes, hidden_dim] dy_feat = dy_feat.view(batch_size, num_nodes, -1) # node embedding emb1 = E_d.unsqueeze(0).expand(batch_size, -1, -1) emb2 = E_u.unsqueeze(0).expand(batch_size, -1, -1) # distance calculation X1 = torch.cat([dy_feat, T_D, D_W, emb1], dim=-1) # hidden state for calculating distance X2 = torch.cat([dy_feat, T_D, D_W, emb2], dim=-1) # hidden state for calculating distance X = [X1, X2] adjacent_list = [] for _ in X: Q = self.WQ(_) K = self.WK(_) QKT = torch.bmm(Q, K.transpose(-1, -2)) / math.sqrt(self.hidden_dim) W = torch.softmax(QKT, dim=-1) adjacent_list.append(W) return adjacent_list
en
0.570157
# attributes # hidden dimension of # Time Series Feature Extraction # Time Slot Embedding Extraction # Distance Score # TODO more output dimension # last pooling # dynamic information # X->[batch_size, seq_len, num_nodes]->[batch_size, num_nodes, seq_len] # [batchsize, num_nodes, hidden_dim] # node embedding # distance calculation # hidden state for calculating distance # hidden state for calculating distance
2.464534
2