prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): <|fim_middle|> logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
pool.wait() sys.exit(0)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: <|fim_middle|> else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads)
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: <|fim_middle|> return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
logger.debug("Running serial...") pool = SerialPool()
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: <|fim_middle|> mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
raise ValueError("Invalid shape: {}".format(y.shape))
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: <|fim_middle|> return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): <|fim_middle|> return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
func.__doc__ = parfunc.__doc__ break
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: <|fim_middle|> return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
self._hash = hash(frozenset(self._dict.items()))
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def <|fim_middle|>(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
close
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def <|fim_middle|>(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
map
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def <|fim_middle|>(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
get_pool
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def <|fim_middle|>(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
gram_schmidt
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def <|fim_middle|>(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
__init__
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def <|fim_middle|>(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
__enter__
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def <|fim_middle|>(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
__exit__
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def <|fim_middle|>(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
inherit_docs
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def <|fim_middle|>(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
__init__
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def <|fim_middle|>(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
__getitem__
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def <|fim_middle|>(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
__len__
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def <|fim_middle|>(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
__iter__
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def <|fim_middle|>(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def __eq__(self, other): return self._dict == other._dict <|fim▁end|>
__hash__
<|file_name|>util.py<|end_file_name|><|fim▁begin|># coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging.getLogger(__name__) class SerialPool(object): def close(self): return def map(self, *args, **kwargs): return map(*args, **kwargs) def get_pool(mpi=False, threads=None): """ Get a pool object to pass to emcee for parallel processing. If mpi is False and threads is None, pool is None. Parameters ---------- mpi : bool Use MPI or not. If specified, ignores the threads kwarg. threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """ if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads > 1: logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads) else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n) # Main loop for i in range(n): # Remove component in direction i for j in range(i): esc = np.sum(y[j]*y[i]) y[i] -= y[j]*esc # Normalization mo[i] = np.linalg.norm(y[i]) y[i] /= mo[i] return mo class use_backend(object): def __init__(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = backend def __enter__(self): gui, backend = self.shell.enable_matplotlib(self.new_backend) def __exit__(self, type, value, tb): gui, backend = self.shell.enable_matplotlib(self.old_backend) def inherit_docs(cls): for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfunc, '__doc__', None): func.__doc__ = parfunc.__doc__ break return cls class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(self._dict) def __hash__(self): if self._hash is None: self._hash = hash(frozenset(self._dict.items())) return self._hash def <|fim_middle|>(self, other): return self._dict == other._dict <|fim▁end|>
__eq__
<|file_name|>profile_core.py<|end_file_name|><|fim▁begin|>import cProfile from pathlib import Path def main(args, results_dir: Path, scenario_dir: Path): try: scenario_dir.mkdir(parents=True) except FileExistsError: pass<|fim▁hole|> cProfile.runctx( 'from dmprsim.scenarios.python_profile import main;' 'main(args, results_dir, scenario_dir)', globals=globals(), locals=locals(), filename=str(results_dir / 'profile.pstats'), )<|fim▁end|>
<|file_name|>profile_core.py<|end_file_name|><|fim▁begin|>import cProfile from pathlib import Path def main(args, results_dir: Path, scenario_dir: Path): <|fim_middle|> <|fim▁end|>
try: scenario_dir.mkdir(parents=True) except FileExistsError: pass cProfile.runctx( 'from dmprsim.scenarios.python_profile import main;' 'main(args, results_dir, scenario_dir)', globals=globals(), locals=locals(), filename=str(results_dir / 'profile.pstats'), )
<|file_name|>profile_core.py<|end_file_name|><|fim▁begin|>import cProfile from pathlib import Path def <|fim_middle|>(args, results_dir: Path, scenario_dir: Path): try: scenario_dir.mkdir(parents=True) except FileExistsError: pass cProfile.runctx( 'from dmprsim.scenarios.python_profile import main;' 'main(args, results_dir, scenario_dir)', globals=globals(), locals=locals(), filename=str(results_dir / 'profile.pstats'), ) <|fim▁end|>
main
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException <|fim▁hole|> def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id)<|fim▁end|>
from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase):
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): <|fim_middle|> <|fim▁end|>
def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id)
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): <|fim_middle|> def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity)
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): <|fim_middle|> def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities)
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): <|fim_middle|> def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4])
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): <|fim_middle|> def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1)
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): <|fim_middle|> <|fim▁end|>
missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id)
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def <|fim_middle|>(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
setUp
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def <|fim_middle|>(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
test_lists_charities
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def <|fim_middle|>(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
test_gets_single_charity
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def <|fim_middle|>(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def test_getting_missing_charity_by_id_throws(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
test_gets_charity_by_id
<|file_name|>charity_repository_test.py<|end_file_name|><|fim▁begin|>from givabit.backend.charity import Charity from givabit.backend.errors import MissingValueException, MultipleValueException from givabit.test_common import test_data from givabit.test_common import test_utils class CharityRepositoryTest(test_utils.TestCase): def setUp(self): super(CharityRepositoryTest, self).setUp() self.all_charities = [test_data.c1, test_data.c2, test_data.c3, test_data.c4] for charity in self.all_charities: self.charity_repo.add_or_update_charity(charity) def test_lists_charities(self): self.assertSequenceEqual(self.charity_repo.list_charities(), self.all_charities) def test_gets_single_charity(self): self.assertEqual(self.charity_repo.get_charity('Shelter'), test_data.c1) self.assertEqual(self.charity_repo.get_charity('Oxfam'), test_data.c2) with self.assertRaises(MissingValueException): self.charity_repo.get_charity('Does not exist') try: self.charity_repo.get_charity('BHF') except MultipleValueException, e: self.assertSequenceEqual(e.values, [test_data.c3, test_data.c4]) def test_gets_charity_by_id(self): self.assertEquals(self.charity_repo.get_charity(id=test_data.c1.key().id()), test_data.c1) def <|fim_middle|>(self): missing_id = 0 while missing_id in map(lambda charity: charity.key().id(), self.all_charities): missing_id += 1 with self.assertRaises(MissingValueException): self.charity_repo.get_charity(id=missing_id) <|fim▁end|>
test_getting_missing_charity_by_id_throws
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method()<|fim▁hole|> # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1)<|fim▁end|>
self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること"""
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: <|fim_middle|> fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] <|fim_middle|> lf): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(se
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetc<|fim_middle|> ffset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
h_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, o
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += s<|fim_middle|> f len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
elf.limit return items def __iter__(self): return self def __next__(self): i
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: r<|fim_middle|> eration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
aise StopIt
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.po<|fim_middle|> fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
p() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.f<|fim_middle|> define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
etch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): <|fim_middle|> define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
u"""List of SoftLayer_Virtual_Guest""" def
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.f<|fim_middle|> unt = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
etch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_acco
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # ----------------------------<|fim_middle|> unt = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
---------------------------------- try: master_acco
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: <|fim_middle|> t self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
# prefetch for nex
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""Lis <|fim_middle|> r""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
t of SoftLayer_User_Custome
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): <|fim_middle|>aster_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
self.m
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継<|fim_middle|> # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
承側クラスで実装すること"""
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) <|fim_middle|>self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fet<|fim_middle|>1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
ched) <
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration <|fim_middle|> self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
item =
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers cla<|fim_middle|>erableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGuests # -------------------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
ss VirtualGuests(It
<|file_name|>sl-ls.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # sl-ls.py: get information utility # Created by NAKAJIMA Takaaki # Last modified: Apr 16, 2014. # # Require: Python v3 # # See also https://softlayer-api-python-client.readthedocs.org # # You should set env variables # SL_USERNAME = YOUR_USERNAME # SL_API_KEY = YOUR_API_KEY import logging import SoftLayer client = SoftLayer.Client() class IterableItems: u"""Pagenate されているリストを全体を回せるようにする""" def __init__(self, client, limit=10): self.master_account = client['Account'] self.offset = 0 self.limit = limit self.define_fetch_method() self.fetched = self.fetch() def define_fetch_method(self): u"""継承側クラスで実装すること""" # self.fetch_method に適切な pagenate メソッドを設定 raise NotImpementedError("Not implemented yet.") def fetch(self): items = self.fetch_method(limit=self.limit, offset=self.offset) self.offset += self.limit return items def __iter__(self): return self def __next__(self): if len(self.fetched) < 1: raise StopIteration item = self.fetched.pop() if len(self.fetched) < 1: # prefetch for next self.fetched = self.fetch() return item class Users(IterableItems): u"""List of SoftLayer_User_Customer""" def define_fetch_method(self): self.fetch_method = self.master_account.getUsers class VirtualGuests(IterableItems): u"""List of SoftLayer_Virtual_Guest""" def define_fetch_method(self): self.fetch_method = self.master_account.getVirtualGue<|fim_middle|>-------------------------------------------------- try: master_account = client['Account'] print("## Account information ##") user_mask="id, firstName, lastName, email" account_info = master_account.getObject(mask=user_mask) print(account_info) # all child users #for user in master_account.getUsers(limit=10, offset=0): print("## Users ##"); for user in Users(client): print("id:%d, %s" % (user['id'], user['username'])) # Virtual guest OSes # for vg in client['Account'].getVirtualGuests(limit=10, offset=0): print("## Virtual guests ##"); for vg in VirtualGuests(client): print("AccountId=%s, ID=%d, hostname=%s" % (vg['accountId'], vg['id'], vg['hostname'])) print("## Instances ##"); cci_manager = SoftLayer.CCIManager(client) for cci in cci_manager.list_instances(): print("FQDN=%s, IP_addrs=%s, %s" % (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress'])) print("## Billing items ##") billing_mask = "id, parentId, description, currentHourlyCharge" print(master_account.getAllBillingItems(mask=billing_mask)) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve account information faultCode%s, faultString=%s" % (e.faultCode, e.faultString)) exit(1) <|fim▁end|>
sts # ------------
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&")<|fim▁hole|>class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws<|fim▁end|>
return s
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): <|fim_middle|> class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: <|fim_middle|> class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): <|fim_middle|> def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): <|fim_middle|> def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): <|fim_middle|> def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): <|fim_middle|> def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
os.mkdir(path)
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): <|fim_middle|> def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
os.rmdir(path)
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): <|fim_middle|> def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
open(path,'w').close()
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): <|fim_middle|> pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
os.unlink(path)
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): <|fim_middle|> <|fim▁end|>
def __init__(_,ws):_.ws=ws
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):<|fim_middle|> <|fim▁end|>
_.ws=ws
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def <|fim_middle|>(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
unescape
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def <|fim_middle|>(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
h_fs_get
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def <|fim_middle|>(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
h_fs_put
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def <|fim_middle|>(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
h_fs_system
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def <|fim_middle|> (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
h_fs_mkdir
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def <|fim_middle|> (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
h_fs_rmdir
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def <|fim_middle|> (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
h_fs_touch
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def <|fim_middle|>(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws <|fim▁end|>
h_fs_unlink
<|file_name|>fs.py<|end_file_name|><|fim▁begin|>import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def <|fim_middle|>(_,ws):_.ws=ws <|fim▁end|>
__init__
<|file_name|>connect.py<|end_file_name|><|fim▁begin|>import pymongo def connect (): ''' Create the connection to the MongoDB and create 3 collections needed ''' try: # Create the connection to the local host <|fim▁hole|> return False # This is the name of the database -'GtownTwitter' db = conn['GtownTwitter_PROD'] return db<|fim▁end|>
conn = pymongo.MongoClient() print 'MongoDB Connection Successful' except pymongo.errors.ConnectionFailure, err: print 'MongoDB Connection Unsuccessful'
<|file_name|>connect.py<|end_file_name|><|fim▁begin|>import pymongo def connect (): <|fim_middle|> <|fim▁end|>
''' Create the connection to the MongoDB and create 3 collections needed ''' try: # Create the connection to the local host conn = pymongo.MongoClient() print 'MongoDB Connection Successful' except pymongo.errors.ConnectionFailure, err: print 'MongoDB Connection Unsuccessful' return False # This is the name of the database -'GtownTwitter' db = conn['GtownTwitter_PROD'] return db
<|file_name|>connect.py<|end_file_name|><|fim▁begin|>import pymongo def <|fim_middle|> (): ''' Create the connection to the MongoDB and create 3 collections needed ''' try: # Create the connection to the local host conn = pymongo.MongoClient() print 'MongoDB Connection Successful' except pymongo.errors.ConnectionFailure, err: print 'MongoDB Connection Unsuccessful' return False # This is the name of the database -'GtownTwitter' db = conn['GtownTwitter_PROD'] return db<|fim▁end|>
connect
<|file_name|>subscribe.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Simple script to test sending UTF8 text with the GrowlNotifier class import logging logging.basicConfig(level=logging.DEBUG)<|fim▁hole|>import platform growl = GrowlNotifier(notifications=['Testing'],password='password',hostname='ayu') growl.subscribe(platform.node(),platform.node(),12345)<|fim▁end|>
from gntp.notifier import GrowlNotifier
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower()<|fim▁hole|> else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current}<|fim▁end|>
multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path)
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): <|fim_middle|> <|fim▁end|>
template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current}
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): <|fim_middle|> @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current} <|fim▁end|>
pass
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def content(self): <|fim_middle|> <|fim▁end|>
configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current}
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): <|fim_middle|> else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current} <|fim▁end|>
content_multi = load(multi_path)
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: <|fim_middle|> dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current} <|fim▁end|>
content_multi = self.template
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): <|fim_middle|> else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current} <|fim▁end|>
break
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: <|fim_middle|> content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current} <|fim▁end|>
import_group.appendChild(import_node)
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def <|fim_middle|>(self): pass @property def content(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current} <|fim▁end|>
filename
<|file_name|>visualstudio_multi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ImportGroup Label="PropertySheets" > </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup /> <ItemGroup /> </Project> """ @property def filename(self): pass @property def <|fim_middle|>(self): configuration = str(self.conanfile.settings.build_type) platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch)) vsversion = str(self.settings.compiler.version) # there is also ClCompile.RuntimeLibrary, but it's handling is a bit complicated, so skipping for now condition = " '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() multi_path = os.path.join(self.output_path, name_multi) if os.path.isfile(multi_path): content_multi = load(multi_path) else: content_multi = self.template dom = minidom.parseString(content_multi) import_node = dom.createElement('Import') import_node.setAttribute('Condition', condition) import_node.setAttribute('Project', name_current) import_group = dom.getElementsByTagName('ImportGroup')[0] children = import_group.getElementsByTagName("Import") for node in children: if name_current == node.getAttribute("Project") and condition == node.getAttribute("Condition"): break else: import_group.appendChild(import_node) content_multi = dom.toprettyxml() content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip()) vs_generator = VisualStudioGenerator(self.conanfile) content_current = vs_generator.content return {name_multi: content_multi, name_current: content_current} <|fim▁end|>
content
<|file_name|>test_passthrough.py<|end_file_name|><|fim▁begin|># #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <[email protected]> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import requests from unittest import skip from sure import expect from httpretty import HTTPretty @skip def test_http_passthrough(): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) @skip<|fim▁hole|> response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content)<|fim▁end|>
def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING'
<|file_name|>test_passthrough.py<|end_file_name|><|fim▁begin|># #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <[email protected]> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import requests from unittest import skip from sure import expect from httpretty import HTTPretty @skip def test_http_passthrough(): u<|fim_middle|> @skip def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) <|fim▁end|>
rl = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content)
<|file_name|>test_passthrough.py<|end_file_name|><|fim▁begin|># #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <[email protected]> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import requests from unittest import skip from sure import expect from httpretty import HTTPretty @skip def test_http_passthrough(): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) @skip def test_https_passthrough(): u<|fim_middle|> <|fim▁end|>
rl = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content)
<|file_name|>test_passthrough.py<|end_file_name|><|fim▁begin|># #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <[email protected]> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import requests from unittest import skip from sure import expect from httpretty import HTTPretty @skip def t<|fim_middle|>): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) @skip def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) <|fim▁end|>
est_http_passthrough(
<|file_name|>test_passthrough.py<|end_file_name|><|fim▁begin|># #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <[email protected]> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import requests from unittest import skip from sure import expect from httpretty import HTTPretty @skip def test_http_passthrough(): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) @skip def t<|fim_middle|>): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) <|fim▁end|>
est_https_passthrough(
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from constituencies.models import Constituency from uk_political_parties.models import Party from elections.models import Election class Person(models.Model): name = models.CharField(blank=False, max_length=255) remote_id = models.CharField(blank=True, max_length=255, null=True) source_url = models.URLField(blank=True, null=True) source_name = models.CharField(blank=True, max_length=100) image_url = models.URLField(blank=True, null=True) elections = models.ManyToManyField(Election) parties = models.ManyToManyField(Party, through='PartyMemberships') constituencies = models.ManyToManyField(Constituency, through='PersonConstituencies') @property<|fim▁hole|> def current_party(self): parties = self.partymemberships_set.filter(membership_end=None) if parties: return parties[0] @property def current_election(self): return self.elections.filter(active=True)[0] @property def current_constituency(self): return self.constituencies.filter( personconstituencies__election=self.current_election)[0] def __unicode__(self): return "%s (%s)" % (self.name, self.remote_id) class PartyMemberships(models.Model): person = models.ForeignKey(Person) party = models.ForeignKey(Party) membership_start = models.DateField() membership_end = models.DateField(null=True) class PersonConstituencies(models.Model): person = models.ForeignKey(Person) constituency = models.ForeignKey(Constituency) election = models.ForeignKey(Election)<|fim▁end|>
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from constituencies.models import Constituency from uk_political_parties.models import Party from elections.models import Election class Person(models.Model): <|fim_middle|> class PartyMemberships(models.Model): person = models.ForeignKey(Person) party = models.ForeignKey(Party) membership_start = models.DateField() membership_end = models.DateField(null=True) class PersonConstituencies(models.Model): person = models.ForeignKey(Person) constituency = models.ForeignKey(Constituency) election = models.ForeignKey(Election) <|fim▁end|>
name = models.CharField(blank=False, max_length=255) remote_id = models.CharField(blank=True, max_length=255, null=True) source_url = models.URLField(blank=True, null=True) source_name = models.CharField(blank=True, max_length=100) image_url = models.URLField(blank=True, null=True) elections = models.ManyToManyField(Election) parties = models.ManyToManyField(Party, through='PartyMemberships') constituencies = models.ManyToManyField(Constituency, through='PersonConstituencies') @property def current_party(self): parties = self.partymemberships_set.filter(membership_end=None) if parties: return parties[0] @property def current_election(self): return self.elections.filter(active=True)[0] @property def current_constituency(self): return self.constituencies.filter( personconstituencies__election=self.current_election)[0] def __unicode__(self): return "%s (%s)" % (self.name, self.remote_id)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from constituencies.models import Constituency from uk_political_parties.models import Party from elections.models import Election class Person(models.Model): name = models.CharField(blank=False, max_length=255) remote_id = models.CharField(blank=True, max_length=255, null=True) source_url = models.URLField(blank=True, null=True) source_name = models.CharField(blank=True, max_length=100) image_url = models.URLField(blank=True, null=True) elections = models.ManyToManyField(Election) parties = models.ManyToManyField(Party, through='PartyMemberships') constituencies = models.ManyToManyField(Constituency, through='PersonConstituencies') @property def current_party(self): <|fim_middle|> @property def current_election(self): return self.elections.filter(active=True)[0] @property def current_constituency(self): return self.constituencies.filter( personconstituencies__election=self.current_election)[0] def __unicode__(self): return "%s (%s)" % (self.name, self.remote_id) class PartyMemberships(models.Model): person = models.ForeignKey(Person) party = models.ForeignKey(Party) membership_start = models.DateField() membership_end = models.DateField(null=True) class PersonConstituencies(models.Model): person = models.ForeignKey(Person) constituency = models.ForeignKey(Constituency) election = models.ForeignKey(Election) <|fim▁end|>
parties = self.partymemberships_set.filter(membership_end=None) if parties: return parties[0]
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from constituencies.models import Constituency from uk_political_parties.models import Party from elections.models import Election class Person(models.Model): name = models.CharField(blank=False, max_length=255) remote_id = models.CharField(blank=True, max_length=255, null=True) source_url = models.URLField(blank=True, null=True) source_name = models.CharField(blank=True, max_length=100) image_url = models.URLField(blank=True, null=True) elections = models.ManyToManyField(Election) parties = models.ManyToManyField(Party, through='PartyMemberships') constituencies = models.ManyToManyField(Constituency, through='PersonConstituencies') @property def current_party(self): parties = self.partymemberships_set.filter(membership_end=None) if parties: return parties[0] @property def current_election(self): <|fim_middle|> @property def current_constituency(self): return self.constituencies.filter( personconstituencies__election=self.current_election)[0] def __unicode__(self): return "%s (%s)" % (self.name, self.remote_id) class PartyMemberships(models.Model): person = models.ForeignKey(Person) party = models.ForeignKey(Party) membership_start = models.DateField() membership_end = models.DateField(null=True) class PersonConstituencies(models.Model): person = models.ForeignKey(Person) constituency = models.ForeignKey(Constituency) election = models.ForeignKey(Election) <|fim▁end|>
return self.elections.filter(active=True)[0]