hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
1c370da239c348eda2837ba54cbbd7e8c8216542
2,135
py
Python
cirq/_doc.py
satw1knandala/Cirq
ca307cd7ffdd2e8659c84c484788c8b5d15cc09d
[ "Apache-2.0" ]
null
null
null
cirq/_doc.py
satw1knandala/Cirq
ca307cd7ffdd2e8659c84c484788c8b5d15cc09d
[ "Apache-2.0" ]
null
null
null
cirq/_doc.py
satw1knandala/Cirq
ca307cd7ffdd2e8659c84c484788c8b5d15cc09d
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Workaround for associating docstrings with public constants.""" from typing import Any, Dict RECORDED_CONST_DOCS: Dict[int, str] = {} def document(value: Any, doc_string: str = ''): """Stores documentation details about the given value. This method is used to associate a docstring with global constants. It is also used to indicate that a private method should be included in the public documentation (e.g. when documenting protocols or arithmetic operations). The given documentation information is filed under `id(value)` in `cirq._doc.RECORDED_CONST_DOCS`. Args: value: The value to associate with documentation information. doc_string: The doc string to associate with the value. Defaults to the value's __doc__ attribute. Returns: The given value. """ RECORDED_CONST_DOCS[id(value)] = doc_string ## this is how the devsite API generator picks up ## docstrings for type aliases try: value.__doc__ = doc_string except AttributeError: # we have a couple (~ 7) global constants of type list, tuple, dict, # that fail here as their __doc__ attribute is read-only. # For the time being these are not going to be part of the generated # API docs. See https://github.com/quantumlib/Cirq/issues/3276 for # more info. # to list them, uncomment these lines and run `import cirq`: # print(f"WARNING: {e}") # print(traceback.format_stack(limit=2)[0]) pass return value
37.45614
80
0.703981
from typing import Any, Dict RECORDED_CONST_DOCS: Dict[int, str] = {} def document(value: Any, doc_string: str = ''): RECORDED_CONST_DOCS[id(value)] = doc_string pass return value
true
true
1c370f1e01d6fa55e58a5d7090684e96c216762b
19,528
py
Python
scrapli/channel/base_channel.py
carlmontanari/nssh
fa2277ea0b8fdb81de3064e1d48bad9264f0cd64
[ "MIT" ]
1
2020-02-09T17:43:43.000Z
2020-02-09T17:43:43.000Z
scrapli/channel/base_channel.py
carlmontanari/nssh
fa2277ea0b8fdb81de3064e1d48bad9264f0cd64
[ "MIT" ]
null
null
null
scrapli/channel/base_channel.py
carlmontanari/nssh
fa2277ea0b8fdb81de3064e1d48bad9264f0cd64
[ "MIT" ]
null
null
null
"""scrapli.channel.base_channel""" import re from dataclasses import dataclass from datetime import datetime from functools import lru_cache from io import SEEK_END, BytesIO from typing import BinaryIO, List, Optional, Pattern, Tuple, Union from scrapli.exceptions import ScrapliAuthenticationFailed, ScrapliTypeError, ScrapliValueError from scrapli.logging import get_instance_logger from scrapli.transport.base import AsyncTransport, Transport ANSI_ESCAPE_PATTERN = re.compile(rb"\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))") @dataclass() class BaseChannelArgs: """ Dataclass for all base Channel arguments Args: comms_prompt_pattern: comms_prompt_pattern to assign to the channel; should generally be created/passed from the driver class comms_return_char: comms_return_char to assign to the channel, see above comms_prompt_search_depth: depth of the buffer to search in for searching for the prompt in "read_until_prompt"; smaller number here will generally be faster, though may be less reliable; default value is 1000 timeout_ops: timeout_ops to assign to the channel, see above channel_log: log "channel" output -- this would be the output you would normally see on a terminal. If `True` logs to `scrapli_channel.log`, if a string is provided, logs to wherever that string points channel_log_mode: "write"|"append", all other values will raise ValueError, does what it sounds like it should by setting the channel log to the provided mode channel_lock: bool indicated if channel lock should be used for all read/write operations Returns: None Raises: N/A """ comms_prompt_pattern: str = r"^[a-z0-9.\-@()/:]{1,32}[#>$]$" comms_return_char: str = "\n" comms_prompt_search_depth: int = 1000 timeout_ops: float = 30.0 channel_log: Union[str, bool, BytesIO] = False channel_log_mode: str = "write" channel_lock: bool = False def __post_init__(self) -> None: """ Validate dataclass arguments at end of initialization Args: N/A Returns: None Raises: ScrapliValueError: if invalid channel_log_mode provided """ if self.channel_log_mode.lower() not in ( "write", "append", ): raise ScrapliValueError( f"provided channel_log_mode '{self.channel_log_mode}' is not valid, mode must be " f"one of: 'write', 'append'" ) if self.channel_log_mode.lower() == "write": self.channel_log_mode = "w" else: self.channel_log_mode = "a" class BaseChannel: def __init__( self, transport: Union[AsyncTransport, Transport], base_channel_args: BaseChannelArgs, ): """ BaseChannel Object -- provides convenience methods to both sync and async Channels Args: transport: initialized scrapli Transport/AsyncTransport object base_channel_args: BaseChannelArgs object Returns: None Raises: N/A """ self.transport = transport self._base_channel_args = base_channel_args self.logger = get_instance_logger( instance_name="scrapli.channel", host=self.transport._base_transport_args.host, port=self.transport._base_transport_args.port, uid=self.transport._base_transport_args.logging_uid, ) self.channel_log: Optional[BinaryIO] = None self._auth_telnet_login_pattern = r"^(.*username:)|(.*login:)\s?$" self._auth_password_pattern = r"(.*@.*)?password:\s?$" self._auth_passphrase_pattern = r"enter passphrase for key" @property def auth_telnet_login_pattern(self) -> Pattern[bytes]: """ Getter for `auth_telnet_login_pattern` attribute Args: N/A Returns: Pattern: compiled pattern of the set auth_telnet_login_pattern value Raises: N/A """ return re.compile(self._auth_telnet_login_pattern.encode(), flags=re.I | re.M) @auth_telnet_login_pattern.setter def auth_telnet_login_pattern(self, value: str) -> None: """ Setter for `auth_telnet_login_pattern` attribute Args: value: str value for auth_telnet_login_pattern; this value will be compiled withe re.I and re.M flags when the getter is called. Returns: None Raises: ScrapliTypeError: if value is not of type str """ self.logger.debug(f"setting 'auth_telnet_login_pattern' value to '{value}'") if not isinstance(value, str): raise ScrapliTypeError self._auth_telnet_login_pattern = value @property def auth_password_pattern(self) -> Pattern[bytes]: """ Getter for `auth_password_pattern` attribute Args: N/A Returns: Pattern: compiled pattern of the set auth_password_pattern value Raises: N/A """ return re.compile(self._auth_password_pattern.encode(), flags=re.I | re.M) @auth_password_pattern.setter def auth_password_pattern(self, value: str) -> None: """ Setter for `auth_password_pattern` attribute Args: value: str value for auth_password_pattern; this value will be compiled withe re.I and re.M flags when the getter is called. Returns: None Raises: ScrapliTypeError: if value is not of type str """ self.logger.debug(f"setting 'auth_password_pattern' value to '{value}'") if not isinstance(value, str): raise ScrapliTypeError self._auth_password_pattern = value @property def auth_passphrase_pattern(self) -> Pattern[bytes]: """ Getter for `auth_passphrase_pattern` attribute Args: N/A Returns: Pattern: compiled pattern of the set auth_passphrase_pattern value Raises: N/A """ return re.compile(self._auth_passphrase_pattern.encode(), flags=re.I | re.M) @auth_passphrase_pattern.setter def auth_passphrase_pattern(self, value: str) -> None: """ Setter for `auth_passphrase_pattern` attribute Args: value: str value for auth_passphrase_pattern; this value will be compiled withe re.I and re.M flags when the getter is called. Returns: None Raises: ScrapliTypeError: if value is not of type str """ self.logger.debug(f"setting '_auth_passphrase_pattern' value to '{value}'") if not isinstance(value, str): raise ScrapliTypeError self._auth_passphrase_pattern = value def open(self) -> None: """ Channel open method Args: N/A Returns: None Raises: N/A """ if self._base_channel_args.channel_log: if isinstance(self._base_channel_args.channel_log, BytesIO): self.channel_log = self._base_channel_args.channel_log else: channel_log_destination = "scrapli_channel.log" if isinstance(self._base_channel_args.channel_log, str): channel_log_destination = self._base_channel_args.channel_log self.logger.info( f"channel log enabled, logging channel output to '{channel_log_destination}'" ) # have to ignore type due to mypy not wanting to read the mode from formatted string # if you change the mode --> "wb" or "ab" it works as you would hope/expect; those # are the only values it can possibly be at this point though so we can safely # ignore here # note that this will *always* be binary mode, so there doesn't need to be any # encoding, hence ignoring that pylint message! self.channel_log = open( # pylint: disable=W1514,R1732 channel_log_destination, mode=f"{self._base_channel_args.channel_log_mode}b", # type: ignore ) def close(self) -> None: """ Channel close method Args: N/A Returns: None Raises: N/A """ if self.channel_log: self.channel_log.close() def _process_read_buf(self, read_buf: BytesIO) -> bytes: """ Process the read buffer Seeks backwards up to search depth then partitions on newlines. Partition is to ensure that the resulting search_buf does not end up with partial lines in the output which can cause prompt patterns to match places they should not match! Args: read_buf: bytesio object read from the transport Returns: bytes: cleaned up search buffer Raises: N/A """ read_buf.seek(-self._base_channel_args.comms_prompt_search_depth, SEEK_END) search_buf = read_buf.read() before, _, search_buf = search_buf.partition(b"\n") if not search_buf: # didn't split on anything or nothing after partition search_buf = before return search_buf def write(self, channel_input: str, redacted: bool = False) -> None: """ Write input to the underlying Transport session Args: channel_input: string of input to send redacted: redact channel input from log or not Returns: None Raises: N/A """ log_output = "REDACTED" if redacted else repr(channel_input) self.logger.debug(f"write: {log_output}") self.transport.write(channel_input=channel_input.encode()) def send_return(self) -> None: """ Convenience method to send return char Args: N/A Returns: None Raises: N/A """ self.write(channel_input=self._base_channel_args.comms_return_char) @staticmethod def _join_and_compile(channel_outputs: Optional[List[bytes]]) -> Pattern[bytes]: """ Convenience method for read_until_prompt_or_time to join channel inputs into a regex pattern Args: channel_outputs: list of bytes channel inputs to join into a regex pattern Returns: Pattern: joined regex pattern or an empty pattern (empty bytes) Raises: N/A """ regex_channel_outputs = b"" if channel_outputs: regex_channel_outputs = b"|".join( [b"(" + channel_output + b")" for channel_output in channel_outputs] ) regex_channel_outputs_pattern = re.compile(pattern=regex_channel_outputs, flags=re.I | re.M) return regex_channel_outputs_pattern def _ssh_message_handler(self, output: bytes) -> None: # noqa: C901 """ Parse EOF messages from _pty_authenticate and create log/stack exception message Args: output: bytes output from _pty_authenticate Returns: N/A # noqa: DAR202 Raises: ScrapliAuthenticationFailed: if any errors are read in the output """ msg = "" if b"host key verification failed" in output.lower(): msg = "Host key verification failed" elif b"operation timed out" in output.lower() or b"connection timed out" in output.lower(): msg = "Timed out connecting to host" elif b"no route to host" in output.lower(): msg = "No route to host" elif b"no matching key exchange" in output.lower(): msg = "No matching key exchange found for host" key_exchange_pattern = re.compile( pattern=rb"their offer: ([a-z0-9\-,]*)", flags=re.M | re.I ) offered_key_exchanges_match = re.search(pattern=key_exchange_pattern, string=output) if offered_key_exchanges_match: offered_key_exchanges = offered_key_exchanges_match.group(1).decode() msg += f", their offer: {offered_key_exchanges}" elif b"no matching cipher" in output.lower(): msg = "No matching cipher found for host" ciphers_pattern = re.compile(pattern=rb"their offer: ([a-z0-9\-,]*)", flags=re.M | re.I) offered_ciphers_match = re.search(pattern=ciphers_pattern, string=output) if offered_ciphers_match: offered_ciphers = offered_ciphers_match.group(1).decode() msg += f", their offer: {offered_ciphers}" elif b"bad configuration" in output.lower(): msg = "Bad SSH configuration option(s) for host" configuration_pattern = re.compile( pattern=rb"bad configuration option: ([a-z0-9\+\=,]*)", flags=re.M | re.I ) configuration_issue_match = re.search(pattern=configuration_pattern, string=output) if configuration_issue_match: configuration_issues = configuration_issue_match.group(1).decode() msg += f", bad option(s): {configuration_issues}" elif b"WARNING: UNPROTECTED PRIVATE KEY FILE!" in output: msg = "Permissions for private key are too open, authentication failed!" elif b"could not resolve hostname" in output.lower(): msg = "Could not resolve address for host" elif b"permission denied" in output.lower(): msg = str(output) if msg: self.logger.critical(msg) raise ScrapliAuthenticationFailed(msg) @staticmethod @lru_cache() def _get_prompt_pattern(class_pattern: str, pattern: Optional[str] = None) -> Pattern[bytes]: """ Return compiled prompt pattern Given a potential prompt and the Channel class' prompt, return compiled prompt pattern Args: class_pattern: comms_prompt_pattern from the class itself; must be passed so that the arguments are recognized in lru cache; this way if a user changes the pattern during normal scrapli operations the lru cache can "notice" the pattern changed! pattern: optional regex pattern to compile, if not provided we use the class' pattern Returns: pattern: compiled regex pattern to use to search for a prompt in output data Raises: N/A """ if not pattern: return re.compile(class_pattern.encode(), flags=re.M | re.I) bytes_pattern = pattern.encode() if bytes_pattern.startswith(b"^") and bytes_pattern.endswith(b"$"): return re.compile(bytes_pattern, flags=re.M | re.I) return re.compile(re.escape(bytes_pattern)) def _pre_channel_authenticate_ssh( self, ) -> Tuple[Pattern[bytes], Pattern[bytes], Pattern[bytes]]: """ Handle pre ssh authentication work for parity between sync and sync versions. Args: N/A Returns: tuple: tuple of pass/passphrase/prompt patterns Raises: N/A """ prompt_pattern = self._get_prompt_pattern( class_pattern=self._base_channel_args.comms_prompt_pattern ) return self.auth_password_pattern, self.auth_passphrase_pattern, prompt_pattern def _pre_channel_authenticate_telnet( self, ) -> Tuple[Pattern[bytes], Pattern[bytes], Pattern[bytes], float, float]: """ Handle pre telnet authentication work for parity between sync and sync versions. Args: N/A Returns: tuple: tuple of user/pass/prompt patterns, start timestamp and return interval Raises: N/A """ prompt_pattern = self._get_prompt_pattern( class_pattern=self._base_channel_args.comms_prompt_pattern ) # capture the start time of the authentication event; we also set a "return_interval" which # is 1/10 the timout_ops value, we will send a return character at roughly this interval if # there is no output on the channel. we do this because sometimes telnet needs a kick to get # it to prompt for auth -- particularity when connecting to terminal server/console port auth_start_time = datetime.now().timestamp() return_interval = self._base_channel_args.timeout_ops / 10 return ( self.auth_telnet_login_pattern, self.auth_password_pattern, prompt_pattern, auth_start_time, return_interval, ) def _process_output(self, buf: bytes, strip_prompt: bool) -> bytes: """ Process output received form the device Remove inputs and prompts if desired Args: buf: bytes output from the device strip_prompt: True/False strip the prompt from the device output Returns: bytes: cleaned up byte string Raises: N/A """ buf = b"\n".join([line.rstrip() for line in buf.splitlines()]) if strip_prompt: prompt_pattern = self._get_prompt_pattern( class_pattern=self._base_channel_args.comms_prompt_pattern ) buf = re.sub(pattern=prompt_pattern, repl=b"", string=buf) buf = buf.lstrip(self._base_channel_args.comms_return_char.encode()).rstrip() return buf @staticmethod def _strip_ansi(buf: bytes) -> bytes: """ Strip ansi characters from output Args: buf: bytes from previous reads if needed Returns: bytes: bytes output read from channel with ansi characters removed Raises: N/A """ buf = re.sub(pattern=ANSI_ESCAPE_PATTERN, repl=b"", string=buf) return buf @staticmethod def _pre_send_input(channel_input: str) -> None: """ Handle pre "send_input" tasks for consistency between sync/async versions Args: channel_input: string input to send to channel Returns: bytes: current channel buffer Raises: ScrapliTypeError: if input is anything but a string """ if not isinstance(channel_input, str): raise ScrapliTypeError( f"`send_input` expects a single string, got {type(channel_input)}." ) @staticmethod def _pre_send_inputs_interact(interact_events: List[Tuple[str, str, Optional[bool]]]) -> None: """ Handle pre "send_inputs_interact" tasks for consistency between sync/async versions Args: interact_events: interact events passed to `send_inputs_interact` Returns: None Raises: ScrapliTypeError: if input is anything but a string """ if not isinstance(interact_events, list): raise ScrapliTypeError(f"`interact_events` expects a List, got {type(interact_events)}")
32.384743
100
0.612659
import re from dataclasses import dataclass from datetime import datetime from functools import lru_cache from io import SEEK_END, BytesIO from typing import BinaryIO, List, Optional, Pattern, Tuple, Union from scrapli.exceptions import ScrapliAuthenticationFailed, ScrapliTypeError, ScrapliValueError from scrapli.logging import get_instance_logger from scrapli.transport.base import AsyncTransport, Transport ANSI_ESCAPE_PATTERN = re.compile(rb"\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))") @dataclass() class BaseChannelArgs: comms_prompt_pattern: str = r"^[a-z0-9.\-@()/:]{1,32}[#>$]$" comms_return_char: str = "\n" comms_prompt_search_depth: int = 1000 timeout_ops: float = 30.0 channel_log: Union[str, bool, BytesIO] = False channel_log_mode: str = "write" channel_lock: bool = False def __post_init__(self) -> None: if self.channel_log_mode.lower() not in ( "write", "append", ): raise ScrapliValueError( f"provided channel_log_mode '{self.channel_log_mode}' is not valid, mode must be " f"one of: 'write', 'append'" ) if self.channel_log_mode.lower() == "write": self.channel_log_mode = "w" else: self.channel_log_mode = "a" class BaseChannel: def __init__( self, transport: Union[AsyncTransport, Transport], base_channel_args: BaseChannelArgs, ): self.transport = transport self._base_channel_args = base_channel_args self.logger = get_instance_logger( instance_name="scrapli.channel", host=self.transport._base_transport_args.host, port=self.transport._base_transport_args.port, uid=self.transport._base_transport_args.logging_uid, ) self.channel_log: Optional[BinaryIO] = None self._auth_telnet_login_pattern = r"^(.*username:)|(.*login:)\s?$" self._auth_password_pattern = r"(.*@.*)?password:\s?$" self._auth_passphrase_pattern = r"enter passphrase for key" @property def auth_telnet_login_pattern(self) -> Pattern[bytes]: return re.compile(self._auth_telnet_login_pattern.encode(), flags=re.I | re.M) @auth_telnet_login_pattern.setter def auth_telnet_login_pattern(self, value: str) -> None: self.logger.debug(f"setting 'auth_telnet_login_pattern' value to '{value}'") if not isinstance(value, str): raise ScrapliTypeError self._auth_telnet_login_pattern = value @property def auth_password_pattern(self) -> Pattern[bytes]: return re.compile(self._auth_password_pattern.encode(), flags=re.I | re.M) @auth_password_pattern.setter def auth_password_pattern(self, value: str) -> None: self.logger.debug(f"setting 'auth_password_pattern' value to '{value}'") if not isinstance(value, str): raise ScrapliTypeError self._auth_password_pattern = value @property def auth_passphrase_pattern(self) -> Pattern[bytes]: return re.compile(self._auth_passphrase_pattern.encode(), flags=re.I | re.M) @auth_passphrase_pattern.setter def auth_passphrase_pattern(self, value: str) -> None: self.logger.debug(f"setting '_auth_passphrase_pattern' value to '{value}'") if not isinstance(value, str): raise ScrapliTypeError self._auth_passphrase_pattern = value def open(self) -> None: if self._base_channel_args.channel_log: if isinstance(self._base_channel_args.channel_log, BytesIO): self.channel_log = self._base_channel_args.channel_log else: channel_log_destination = "scrapli_channel.log" if isinstance(self._base_channel_args.channel_log, str): channel_log_destination = self._base_channel_args.channel_log self.logger.info( f"channel log enabled, logging channel output to '{channel_log_destination}'" ) # encoding, hence ignoring that pylint message! self.channel_log = open( # pylint: disable=W1514,R1732 channel_log_destination, mode=f"{self._base_channel_args.channel_log_mode}b", # type: ignore ) def close(self) -> None: if self.channel_log: self.channel_log.close() def _process_read_buf(self, read_buf: BytesIO) -> bytes: read_buf.seek(-self._base_channel_args.comms_prompt_search_depth, SEEK_END) search_buf = read_buf.read() before, _, search_buf = search_buf.partition(b"\n") if not search_buf: # didn't split on anything or nothing after partition search_buf = before return search_buf def write(self, channel_input: str, redacted: bool = False) -> None: log_output = "REDACTED" if redacted else repr(channel_input) self.logger.debug(f"write: {log_output}") self.transport.write(channel_input=channel_input.encode()) def send_return(self) -> None: self.write(channel_input=self._base_channel_args.comms_return_char) @staticmethod def _join_and_compile(channel_outputs: Optional[List[bytes]]) -> Pattern[bytes]: regex_channel_outputs = b"" if channel_outputs: regex_channel_outputs = b"|".join( [b"(" + channel_output + b")" for channel_output in channel_outputs] ) regex_channel_outputs_pattern = re.compile(pattern=regex_channel_outputs, flags=re.I | re.M) return regex_channel_outputs_pattern def _ssh_message_handler(self, output: bytes) -> None: msg = "" if b"host key verification failed" in output.lower(): msg = "Host key verification failed" elif b"operation timed out" in output.lower() or b"connection timed out" in output.lower(): msg = "Timed out connecting to host" elif b"no route to host" in output.lower(): msg = "No route to host" elif b"no matching key exchange" in output.lower(): msg = "No matching key exchange found for host" key_exchange_pattern = re.compile( pattern=rb"their offer: ([a-z0-9\-,]*)", flags=re.M | re.I ) offered_key_exchanges_match = re.search(pattern=key_exchange_pattern, string=output) if offered_key_exchanges_match: offered_key_exchanges = offered_key_exchanges_match.group(1).decode() msg += f", their offer: {offered_key_exchanges}" elif b"no matching cipher" in output.lower(): msg = "No matching cipher found for host" ciphers_pattern = re.compile(pattern=rb"their offer: ([a-z0-9\-,]*)", flags=re.M | re.I) offered_ciphers_match = re.search(pattern=ciphers_pattern, string=output) if offered_ciphers_match: offered_ciphers = offered_ciphers_match.group(1).decode() msg += f", their offer: {offered_ciphers}" elif b"bad configuration" in output.lower(): msg = "Bad SSH configuration option(s) for host" configuration_pattern = re.compile( pattern=rb"bad configuration option: ([a-z0-9\+\=,]*)", flags=re.M | re.I ) configuration_issue_match = re.search(pattern=configuration_pattern, string=output) if configuration_issue_match: configuration_issues = configuration_issue_match.group(1).decode() msg += f", bad option(s): {configuration_issues}" elif b"WARNING: UNPROTECTED PRIVATE KEY FILE!" in output: msg = "Permissions for private key are too open, authentication failed!" elif b"could not resolve hostname" in output.lower(): msg = "Could not resolve address for host" elif b"permission denied" in output.lower(): msg = str(output) if msg: self.logger.critical(msg) raise ScrapliAuthenticationFailed(msg) @staticmethod @lru_cache() def _get_prompt_pattern(class_pattern: str, pattern: Optional[str] = None) -> Pattern[bytes]: if not pattern: return re.compile(class_pattern.encode(), flags=re.M | re.I) bytes_pattern = pattern.encode() if bytes_pattern.startswith(b"^") and bytes_pattern.endswith(b"$"): return re.compile(bytes_pattern, flags=re.M | re.I) return re.compile(re.escape(bytes_pattern)) def _pre_channel_authenticate_ssh( self, ) -> Tuple[Pattern[bytes], Pattern[bytes], Pattern[bytes]]: prompt_pattern = self._get_prompt_pattern( class_pattern=self._base_channel_args.comms_prompt_pattern ) return self.auth_password_pattern, self.auth_passphrase_pattern, prompt_pattern def _pre_channel_authenticate_telnet( self, ) -> Tuple[Pattern[bytes], Pattern[bytes], Pattern[bytes], float, float]: prompt_pattern = self._get_prompt_pattern( class_pattern=self._base_channel_args.comms_prompt_pattern ) auth_start_time = datetime.now().timestamp() return_interval = self._base_channel_args.timeout_ops / 10 return ( self.auth_telnet_login_pattern, self.auth_password_pattern, prompt_pattern, auth_start_time, return_interval, ) def _process_output(self, buf: bytes, strip_prompt: bool) -> bytes: buf = b"\n".join([line.rstrip() for line in buf.splitlines()]) if strip_prompt: prompt_pattern = self._get_prompt_pattern( class_pattern=self._base_channel_args.comms_prompt_pattern ) buf = re.sub(pattern=prompt_pattern, repl=b"", string=buf) buf = buf.lstrip(self._base_channel_args.comms_return_char.encode()).rstrip() return buf @staticmethod def _strip_ansi(buf: bytes) -> bytes: buf = re.sub(pattern=ANSI_ESCAPE_PATTERN, repl=b"", string=buf) return buf @staticmethod def _pre_send_input(channel_input: str) -> None: if not isinstance(channel_input, str): raise ScrapliTypeError( f"`send_input` expects a single string, got {type(channel_input)}." ) @staticmethod def _pre_send_inputs_interact(interact_events: List[Tuple[str, str, Optional[bool]]]) -> None: if not isinstance(interact_events, list): raise ScrapliTypeError(f"`interact_events` expects a List, got {type(interact_events)}")
true
true
1c370f6140eb0cb74ae1838d3926f731766d19f4
3,756
py
Python
code/lib/LoadFileFromHTTPClass.py
kassi/water-meter-system-complete
e020e38e4243425c7ab6fcd12f3fb0ccb8323471
[ "MIT" ]
135
2019-07-27T21:02:13.000Z
2022-03-27T05:43:32.000Z
code/lib/LoadFileFromHTTPClass.py
kassi/water-meter-system-complete
e020e38e4243425c7ab6fcd12f3fb0ccb8323471
[ "MIT" ]
24
2019-09-24T06:56:04.000Z
2021-12-07T23:18:17.000Z
code/lib/LoadFileFromHTTPClass.py
kassi/water-meter-system-complete
e020e38e4243425c7ab6fcd12f3fb0ccb8323471
[ "MIT" ]
41
2019-09-23T10:22:39.000Z
2022-02-01T14:59:47.000Z
import configparser import urllib.request from multiprocessing import Process, Event from PIL import Image from shutil import copyfile import time import os class LoadFileFromHttp: def __init__(self): config = configparser.ConfigParser() config.read('./config/config.ini') self.TimeoutLoadImage = 30 # default Timeout = 30s if config.has_option('Imagesource', 'TimeoutLoadImage'): self.TimeoutLoadImage = int(config['Imagesource']['TimeoutLoadImage']) self.URLImageSource = '' if config.has_option('Imagesource', 'URLImageSource'): self.URLImageSource = config['Imagesource']['URLImageSource'] self.MinImageSize = 10000 if config.has_option('Imagesource', 'MinImageSize'): self.MinImageSize = int(config['Imagesource']['MinImageSize']) self.log_Image = '' if config.has_option('Imagesource', 'LogImageLocation'): self.log_Image = config['Imagesource']['LogImageLocation'] self.LogOnlyFalsePictures = False if config.has_option('Imagesource', 'LogOnlyFalsePictures'): self.LogOnlyFalsePictures = bool(config['Imagesource']['LogOnlyFalsePictures']) self.CheckAndLoadDefaultConfig() self.LastImageSafed = '' def CheckAndLoadDefaultConfig(self): defaultdir = "./config_default/" targetdir = './config/' if len(self.log_Image) > 0: if not os.path.exists(self.log_Image): zerlegt = self.log_Image.split('/') pfad = zerlegt[0] for i in range(1, len(zerlegt)): pfad = pfad + '/' + zerlegt[i] if not os.path.exists(pfad): os.makedirs(pfad) def ReadURL(self, event, url, target): urllib.request.urlretrieve(url, target) event.set() def LoadImageFromURL(self, url, target): self.LastImageSafed = '' if url == '': url = self.URLImageSource event = Event() action_process = Process(target=self.ReadURL, args=(event, url, target)) action_process.start() action_process.join(timeout=self.TimeoutLoadImage) action_process.terminate() # action_process.close() logtime = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime()) if event.is_set(): self.saveLogImage(target, logtime) if self.VerifyImage(target) == True: image_size = os.stat(target).st_size if image_size > self.MinImageSize: result = '' else: result = 'Error - Imagefile too small. Size ' + str(image_size) + ', min size is ' + str(self.MinImageSize)+ '. Source: ' + str(url) else: result = 'Error - Imagefile is corrupted - Source: ' + str(url) else: result = 'Error - Problem during HTTP-request - URL: ' + str(url) return (result, logtime) def PostProcessLogImageProcedure(self, everythingsuccessfull): if (len(self.log_Image) > 0) and self.LogOnlyFalsePictures and (len(self.LastImageSafed) > 0) and everythingsuccessfull: os.remove(self.LastImageSafed) self.LastImageSafed = '' def VerifyImage(self, img_file): try: v_image = Image.open(img_file) v_image.verify() return True except OSError: return False def saveLogImage(self, img_file, logtime): if len(self.log_Image) > 0: speichername = self.log_Image + '/SourceImage_' + logtime + '.jpg' copyfile(img_file, speichername) self.LastImageSafed = speichername
37.939394
152
0.59984
import configparser import urllib.request from multiprocessing import Process, Event from PIL import Image from shutil import copyfile import time import os class LoadFileFromHttp: def __init__(self): config = configparser.ConfigParser() config.read('./config/config.ini') self.TimeoutLoadImage = 30 if config.has_option('Imagesource', 'TimeoutLoadImage'): self.TimeoutLoadImage = int(config['Imagesource']['TimeoutLoadImage']) self.URLImageSource = '' if config.has_option('Imagesource', 'URLImageSource'): self.URLImageSource = config['Imagesource']['URLImageSource'] self.MinImageSize = 10000 if config.has_option('Imagesource', 'MinImageSize'): self.MinImageSize = int(config['Imagesource']['MinImageSize']) self.log_Image = '' if config.has_option('Imagesource', 'LogImageLocation'): self.log_Image = config['Imagesource']['LogImageLocation'] self.LogOnlyFalsePictures = False if config.has_option('Imagesource', 'LogOnlyFalsePictures'): self.LogOnlyFalsePictures = bool(config['Imagesource']['LogOnlyFalsePictures']) self.CheckAndLoadDefaultConfig() self.LastImageSafed = '' def CheckAndLoadDefaultConfig(self): defaultdir = "./config_default/" targetdir = './config/' if len(self.log_Image) > 0: if not os.path.exists(self.log_Image): zerlegt = self.log_Image.split('/') pfad = zerlegt[0] for i in range(1, len(zerlegt)): pfad = pfad + '/' + zerlegt[i] if not os.path.exists(pfad): os.makedirs(pfad) def ReadURL(self, event, url, target): urllib.request.urlretrieve(url, target) event.set() def LoadImageFromURL(self, url, target): self.LastImageSafed = '' if url == '': url = self.URLImageSource event = Event() action_process = Process(target=self.ReadURL, args=(event, url, target)) action_process.start() action_process.join(timeout=self.TimeoutLoadImage) action_process.terminate() logtime = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime()) if event.is_set(): self.saveLogImage(target, logtime) if self.VerifyImage(target) == True: image_size = os.stat(target).st_size if image_size > self.MinImageSize: result = '' else: result = 'Error - Imagefile too small. Size ' + str(image_size) + ', min size is ' + str(self.MinImageSize)+ '. Source: ' + str(url) else: result = 'Error - Imagefile is corrupted - Source: ' + str(url) else: result = 'Error - Problem during HTTP-request - URL: ' + str(url) return (result, logtime) def PostProcessLogImageProcedure(self, everythingsuccessfull): if (len(self.log_Image) > 0) and self.LogOnlyFalsePictures and (len(self.LastImageSafed) > 0) and everythingsuccessfull: os.remove(self.LastImageSafed) self.LastImageSafed = '' def VerifyImage(self, img_file): try: v_image = Image.open(img_file) v_image.verify() return True except OSError: return False def saveLogImage(self, img_file, logtime): if len(self.log_Image) > 0: speichername = self.log_Image + '/SourceImage_' + logtime + '.jpg' copyfile(img_file, speichername) self.LastImageSafed = speichername
true
true
1c370fe1858ce8a4bff2b92caed2da2987120927
5,444
py
Python
lib/galaxy/job_metrics/collectl/cli.py
beatrizserrano/galaxy
e149d9d32e1bca6c07c38b1a9cdabfee60323610
[ "CC-BY-3.0" ]
null
null
null
lib/galaxy/job_metrics/collectl/cli.py
beatrizserrano/galaxy
e149d9d32e1bca6c07c38b1a9cdabfee60323610
[ "CC-BY-3.0" ]
2
2017-05-18T16:12:55.000Z
2022-03-08T12:08:43.000Z
lib/galaxy/job_metrics/collectl/cli.py
beatrizserrano/galaxy
e149d9d32e1bca6c07c38b1a9cdabfee60323610
[ "CC-BY-3.0" ]
null
null
null
"""This module describes :class:`CollectlCli` - an abstraction for building collectl command lines.""" import logging import subprocess from string import Template log = logging.getLogger(__name__) COMMAND_LINE_TEMPLATE = Template( "$collectl_path $destination_arg $mode_arg $subsystems_arg $interval_arg $procfilt_arg $flush_arg $sep_arg" ) MODE_RECORD = "record" MODE_PLAYBACK = "playback" class CollectlCli: """ Abstraction over (some of) the command-line arguments of collectl. Ideally this will be useful for building up command line arguments for remote execution as well as runnning directly on local host. This is meant to be a fairly generic utility - for interfacing with collectl CLI - logic more directly related to the Galaxy job metric plugin plugin should be placed in other modules. **Keyword Arguments:** ``collectl_path`` Path to collectl executable (defaults to collectl - i.e. search the PATH). ``playback_path`` (defaults to ``None``) If this is ``None``, collectl will run in record mode, else it will playback specified file. **Playback Mode Options:** ``sep`` Separator used in playback mode (set to 9 to produce tsv) (defaults to None). **Record Mode Options** (some of these may work in playback mode also) ``destination_path`` Location of path files to write to (defaults to None and collectl will just use cwd). Really this is just to prefix - collectl will append hostname and datetime to file. ``interval`` Setup polling interval (secs) for most subsystems (defaults to None and when unspecified collectl will use default of 1 second). ``interval2`` Setup polling interval (secs) for process information (defaults to None and when unspecified collectl will use default to 60 seconds). ``interval3`` Setup polling interval (secs) for environment information (defaults to None and when unspecified collectl will use default to 300 seconds). ``procfilt`` Optional argument to procfilt. (defaults to None). ``flush`` Optional flush interval (defaults to None). """ def __init__(self, **kwargs): command_args = {} command_args["collectl_path"] = kwargs.get("collectl_path", "collectl") playback_path = kwargs.get("playback_path", None) self.mode = MODE_RECORD if not playback_path else MODE_PLAYBACK if self.mode == MODE_RECORD: mode_arg = "" elif self.mode == MODE_PLAYBACK: mode_arg = f"-P -p '{playback_path}'" else: raise Exception(f"Invalid mode supplied to CollectlCli - {self.mode}") command_args["mode_arg"] = mode_arg command_args["interval_arg"] = self.__interval_arg(kwargs) destination = kwargs.get("destination_path", None) if destination: destination_arg = f"-f '{destination}'" else: destination_arg = "" command_args["destination_arg"] = destination_arg procfilt = kwargs.get("procfilt", None) command_args["procfilt_arg"] = "" if not procfilt else f"--procfilt {procfilt}" command_args["subsystems_arg"] = self.__subsystems_arg(kwargs.get("subsystems", [])) flush = kwargs.get("flush", None) command_args["flush_arg"] = f"--flush {flush}" if flush else "" sep = kwargs.get("sep", None) command_args["sep_arg"] = f"--sep={sep}" if sep else "" self.command_args = command_args def __subsystems_arg(self, subsystems): if subsystems: return f"-s{''.join(s.command_line_arg for s in subsystems)}" else: return "" def __interval_arg(self, kwargs): if self.mode != MODE_RECORD: return "" interval = kwargs.get("interval", None) if not interval: return "" self.__validate_interval_arg(interval) interval_arg = f"-i {interval}" interval2 = kwargs.get("interval2", None) if not interval2: return interval_arg self.__validate_interval_arg(interval2, multiple_of=int(interval)) interval_arg = f"{interval_arg}:{interval2}" interval3 = kwargs.get("interval3", None) if not interval3: return interval_arg self.__validate_interval_arg(interval3, multiple_of=int(interval)) interval_arg = f"{interval_arg}:{interval3}" return interval_arg def __validate_interval_arg(self, value, multiple_of=None): if value and not str(value).isdigit(): raise Exception(f"Invalid interval argument supplied, must be integer {value}") if multiple_of: if int(value) % multiple_of != 0: raise Exception(f"Invalid interval argument supplied, must multiple of {multiple_of}") def build_command_line(self): return COMMAND_LINE_TEMPLATE.substitute(**self.command_args) def run(self, stdout=subprocess.PIPE, stderr=subprocess.PIPE): command_line = self.build_command_line() log.info(f"Executing {command_line}") proc = subprocess.Popen(command_line, shell=True, stdout=stdout, stderr=stderr) return_code = proc.wait() if return_code: raise Exception("Problem running collectl command.") __all__ = ("CollectlCli",)
38.338028
111
0.656319
import logging import subprocess from string import Template log = logging.getLogger(__name__) COMMAND_LINE_TEMPLATE = Template( "$collectl_path $destination_arg $mode_arg $subsystems_arg $interval_arg $procfilt_arg $flush_arg $sep_arg" ) MODE_RECORD = "record" MODE_PLAYBACK = "playback" class CollectlCli: def __init__(self, **kwargs): command_args = {} command_args["collectl_path"] = kwargs.get("collectl_path", "collectl") playback_path = kwargs.get("playback_path", None) self.mode = MODE_RECORD if not playback_path else MODE_PLAYBACK if self.mode == MODE_RECORD: mode_arg = "" elif self.mode == MODE_PLAYBACK: mode_arg = f"-P -p '{playback_path}'" else: raise Exception(f"Invalid mode supplied to CollectlCli - {self.mode}") command_args["mode_arg"] = mode_arg command_args["interval_arg"] = self.__interval_arg(kwargs) destination = kwargs.get("destination_path", None) if destination: destination_arg = f"-f '{destination}'" else: destination_arg = "" command_args["destination_arg"] = destination_arg procfilt = kwargs.get("procfilt", None) command_args["procfilt_arg"] = "" if not procfilt else f"--procfilt {procfilt}" command_args["subsystems_arg"] = self.__subsystems_arg(kwargs.get("subsystems", [])) flush = kwargs.get("flush", None) command_args["flush_arg"] = f"--flush {flush}" if flush else "" sep = kwargs.get("sep", None) command_args["sep_arg"] = f"--sep={sep}" if sep else "" self.command_args = command_args def __subsystems_arg(self, subsystems): if subsystems: return f"-s{''.join(s.command_line_arg for s in subsystems)}" else: return "" def __interval_arg(self, kwargs): if self.mode != MODE_RECORD: return "" interval = kwargs.get("interval", None) if not interval: return "" self.__validate_interval_arg(interval) interval_arg = f"-i {interval}" interval2 = kwargs.get("interval2", None) if not interval2: return interval_arg self.__validate_interval_arg(interval2, multiple_of=int(interval)) interval_arg = f"{interval_arg}:{interval2}" interval3 = kwargs.get("interval3", None) if not interval3: return interval_arg self.__validate_interval_arg(interval3, multiple_of=int(interval)) interval_arg = f"{interval_arg}:{interval3}" return interval_arg def __validate_interval_arg(self, value, multiple_of=None): if value and not str(value).isdigit(): raise Exception(f"Invalid interval argument supplied, must be integer {value}") if multiple_of: if int(value) % multiple_of != 0: raise Exception(f"Invalid interval argument supplied, must multiple of {multiple_of}") def build_command_line(self): return COMMAND_LINE_TEMPLATE.substitute(**self.command_args) def run(self, stdout=subprocess.PIPE, stderr=subprocess.PIPE): command_line = self.build_command_line() log.info(f"Executing {command_line}") proc = subprocess.Popen(command_line, shell=True, stdout=stdout, stderr=stderr) return_code = proc.wait() if return_code: raise Exception("Problem running collectl command.") __all__ = ("CollectlCli",)
true
true
1c3710ae5d49fac1641726e712798402f792d830
702
py
Python
decode_one.py
vmindru/ambp3client
072b0084cdb8989258be9e78e01961d7c1c602fa
[ "Apache-2.0" ]
7
2019-10-05T11:45:55.000Z
2022-03-15T06:00:32.000Z
decode_one.py
vmindru/ambp3client
072b0084cdb8989258be9e78e01961d7c1c602fa
[ "Apache-2.0" ]
1
2021-04-19T19:53:00.000Z
2021-04-19T19:53:00.000Z
decode_one.py
vmindru/ambp3client
072b0084cdb8989258be9e78e01961d7c1c602fa
[ "Apache-2.0" ]
4
2019-11-06T18:03:08.000Z
2020-05-05T19:36:24.000Z
#!/usr/bin/env python from argparse import ArgumentParser from AmbP3.decoder import p3decode as decode from AmbP3.decoder import bin_dict_to_ascii as dict_to_ascii from AmbP3.decoder import hex_to_binary DEFAULT_DATA = "8e023300c922000001000104a468020003042f79340004087802cd052083050005\ 02990006021c00080200008104131804008f" def get_args(): args = ArgumentParser() args.add_argument("data", default=DEFAULT_DATA, nargs="?") return args.parse_args() def main(): args = get_args() data = args.data.rstrip() result = decode(hex_to_binary(data)) header = dict_to_ascii(result[0]) body = result[1] return header, body if __name__ == "__main__": print(main())
25.071429
83
0.750712
from argparse import ArgumentParser from AmbP3.decoder import p3decode as decode from AmbP3.decoder import bin_dict_to_ascii as dict_to_ascii from AmbP3.decoder import hex_to_binary DEFAULT_DATA = "8e023300c922000001000104a468020003042f79340004087802cd052083050005\ 02990006021c00080200008104131804008f" def get_args(): args = ArgumentParser() args.add_argument("data", default=DEFAULT_DATA, nargs="?") return args.parse_args() def main(): args = get_args() data = args.data.rstrip() result = decode(hex_to_binary(data)) header = dict_to_ascii(result[0]) body = result[1] return header, body if __name__ == "__main__": print(main())
true
true
1c3711a3cc54160b9893027fe68fddc73ee0735e
2,482
py
Python
aliyun-python-sdk-acms-open/setup.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
1,001
2015-07-24T01:32:41.000Z
2022-03-25T01:28:18.000Z
aliyun-python-sdk-acms-open/setup.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
363
2015-10-20T03:15:00.000Z
2022-03-08T12:26:19.000Z
aliyun-python-sdk-acms-open/setup.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
682
2015-09-22T07:19:02.000Z
2022-03-22T09:51:46.000Z
#!/usr/bin/python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from setuptools import setup, find_packages import os import sys """ setup module for acms-open. Created on 7/3/2015 @author: alex """ PACKAGE = "aliyunsdkacms_open" NAME = "aliyun-python-sdk-acms-open" DESCRIPTION = "The acms-open module of Aliyun Python sdk." AUTHOR = "Aliyun" AUTHOR_EMAIL = "aliyun-developers-efficiency@list.alibaba-inc.com" URL = "http://develop.aliyun.com/sdk/python" TOPDIR = os.path.dirname(__file__) or "." VERSION = __import__(PACKAGE).__version__ desc_file = open("README.rst") try: LONG_DESCRIPTION = desc_file.read() finally: desc_file.close() setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, license="Apache", url=URL, keywords=["aliyun","sdk","acms-open"], packages=find_packages(exclude=["tests*"]), include_package_data=True, platforms="any", install_requires=["aliyun-python-sdk-core>=2.11.5",], classifiers=( "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Software Development", ) )
31.820513
69
0.668815
from setuptools import setup, find_packages import os import sys PACKAGE = "aliyunsdkacms_open" NAME = "aliyun-python-sdk-acms-open" DESCRIPTION = "The acms-open module of Aliyun Python sdk." AUTHOR = "Aliyun" AUTHOR_EMAIL = "aliyun-developers-efficiency@list.alibaba-inc.com" URL = "http://develop.aliyun.com/sdk/python" TOPDIR = os.path.dirname(__file__) or "." VERSION = __import__(PACKAGE).__version__ desc_file = open("README.rst") try: LONG_DESCRIPTION = desc_file.read() finally: desc_file.close() setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, license="Apache", url=URL, keywords=["aliyun","sdk","acms-open"], packages=find_packages(exclude=["tests*"]), include_package_data=True, platforms="any", install_requires=["aliyun-python-sdk-core>=2.11.5",], classifiers=( "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Software Development", ) )
true
true
1c3713c02a2b658f10fb321502b0988a765cc791
12,784
py
Python
tests/integration/test_s3_zero_copy_replication/test.py
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
4
2020-01-02T01:52:17.000Z
2020-06-15T13:10:37.000Z
tests/integration/test_s3_zero_copy_replication/test.py
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
3
2021-12-13T14:45:52.000Z
2021-12-20T21:01:10.000Z
tests/integration/test_s3_zero_copy_replication/test.py
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
1
2022-03-19T17:31:29.000Z
2022-03-19T17:31:29.000Z
import datetime import logging import time import pytest from helpers.cluster import ClickHouseCluster logging.getLogger().setLevel(logging.INFO) logging.getLogger().addHandler(logging.StreamHandler()) @pytest.fixture(scope="module") def cluster(): try: cluster = ClickHouseCluster(__file__) cluster.add_instance("node1", main_configs=["configs/config.d/s3.xml"], macros={'replica': '1'}, with_minio=True, with_zookeeper=True) cluster.add_instance("node2", main_configs=["configs/config.d/s3.xml"], macros={'replica': '2'}, with_minio=True, with_zookeeper=True) logging.info("Starting cluster...") cluster.start() logging.info("Cluster started") yield cluster finally: cluster.shutdown() def get_large_objects_count(cluster, size=100, folder='data'): minio = cluster.minio_client counter = 0 for obj in minio.list_objects(cluster.minio_bucket, '{}/'.format(folder)): if obj.size >= size: counter = counter + 1 return counter def wait_for_large_objects_count(cluster, expected, size=100, timeout=30): while timeout > 0: if get_large_objects_count(cluster, size=size) == expected: return timeout -= 1 time.sleep(1) assert get_large_objects_count(cluster, size=size) == expected def wait_for_active_parts(node, num_expected_parts, table_name, timeout=30): deadline = time.monotonic() + timeout num_parts = 0 while time.monotonic() < deadline: num_parts_str = node.query("select count() from system.parts where table = '{}' and active".format(table_name)) num_parts = int(num_parts_str.strip()) if num_parts == num_expected_parts: return time.sleep(0.2) assert num_parts == num_expected_parts # Result of `get_large_objects_count` can be changed in other tests, so run this case at the beginning @pytest.mark.order(0) @pytest.mark.parametrize( "policy", ["s3"] ) def test_s3_zero_copy_replication(cluster, policy): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query( """ CREATE TABLE s3_test ON CLUSTER test_cluster (id UInt32, value String) ENGINE=ReplicatedMergeTree('/clickhouse/tables/s3_test', '{}') ORDER BY id SETTINGS storage_policy='{}' """ .format('{replica}', policy) ) node1.query("INSERT INTO s3_test VALUES (0,'data'),(1,'data')") node2.query("SYSTEM SYNC REPLICA s3_test") assert node1.query("SELECT * FROM s3_test order by id FORMAT Values") == "(0,'data'),(1,'data')" assert node2.query("SELECT * FROM s3_test order by id FORMAT Values") == "(0,'data'),(1,'data')" # Based on version 21.x - should be only 1 file with size 100+ (checksums.txt), used by both nodes assert get_large_objects_count(cluster) == 1 node2.query("INSERT INTO s3_test VALUES (2,'data'),(3,'data')") node1.query("SYSTEM SYNC REPLICA s3_test") assert node2.query("SELECT * FROM s3_test order by id FORMAT Values") == "(0,'data'),(1,'data'),(2,'data'),(3,'data')" assert node1.query("SELECT * FROM s3_test order by id FORMAT Values") == "(0,'data'),(1,'data'),(2,'data'),(3,'data')" # Based on version 21.x - two parts wait_for_large_objects_count(cluster, 2) node1.query("OPTIMIZE TABLE s3_test FINAL") # Based on version 21.x - after merge, two old parts and one merged wait_for_large_objects_count(cluster, 3) # Based on version 21.x - after cleanup - only one merged part wait_for_large_objects_count(cluster, 1, timeout=60) node1.query("DROP TABLE IF EXISTS s3_test NO DELAY") node2.query("DROP TABLE IF EXISTS s3_test NO DELAY") def test_s3_zero_copy_on_hybrid_storage(cluster): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query( """ CREATE TABLE hybrid_test ON CLUSTER test_cluster (id UInt32, value String) ENGINE=ReplicatedMergeTree('/clickhouse/tables/hybrid_test', '{}') ORDER BY id SETTINGS storage_policy='hybrid' """ .format('{replica}') ) node1.query("INSERT INTO hybrid_test VALUES (0,'data'),(1,'data')") node2.query("SYSTEM SYNC REPLICA hybrid_test") assert node1.query("SELECT * FROM hybrid_test ORDER BY id FORMAT Values") == "(0,'data'),(1,'data')" assert node2.query("SELECT * FROM hybrid_test ORDER BY id FORMAT Values") == "(0,'data'),(1,'data')" assert node1.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','default')" assert node2.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','default')" node1.query("ALTER TABLE hybrid_test MOVE PARTITION ID 'all' TO DISK 's31'") assert node1.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','s31')" assert node2.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','default')" # Total objects in S3 s3_objects = get_large_objects_count(cluster, size=0) node2.query("ALTER TABLE hybrid_test MOVE PARTITION ID 'all' TO DISK 's31'") assert node1.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','s31')" assert node2.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','s31')" # Check that after moving partition on node2 no new obects on s3 wait_for_large_objects_count(cluster, s3_objects, size=0) assert node1.query("SELECT * FROM hybrid_test ORDER BY id FORMAT Values") == "(0,'data'),(1,'data')" assert node2.query("SELECT * FROM hybrid_test ORDER BY id FORMAT Values") == "(0,'data'),(1,'data')" node1.query("DROP TABLE IF EXISTS hybrid_test NO DELAY") node2.query("DROP TABLE IF EXISTS hybrid_test NO DELAY") def insert_data_time(node, table, number_of_mb, time, start=0): values = ','.join(f"({x},{time})" for x in range(start, int((1024 * 1024 * number_of_mb) / 8) + start + 1)) node.query(f"INSERT INTO {table} VALUES {values}") def insert_large_data(node, table): tm = time.mktime((datetime.date.today() - datetime.timedelta(days=7)).timetuple()) insert_data_time(node, table, 1, tm, 0) tm = time.mktime((datetime.date.today() - datetime.timedelta(days=3)).timetuple()) insert_data_time(node, table, 1, tm, 1024*1024) tm = time.mktime(datetime.date.today().timetuple()) insert_data_time(node, table, 10, tm, 1024*1024*2) @pytest.mark.parametrize( ("storage_policy", "large_data", "iterations"), [ ("tiered", False, 10), ("tiered_copy", False, 10), ("tiered", True, 3), ("tiered_copy", True, 3), ] ) def test_s3_zero_copy_with_ttl_move(cluster, storage_policy, large_data, iterations): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query("DROP TABLE IF EXISTS ttl_move_test NO DELAY") node2.query("DROP TABLE IF EXISTS ttl_move_test NO DELAY") for i in range(iterations): node1.query( """ CREATE TABLE ttl_move_test ON CLUSTER test_cluster (d UInt64, d1 DateTime) ENGINE=ReplicatedMergeTree('/clickhouse/tables/ttl_move_test', '{}') ORDER BY d TTL d1 + INTERVAL 2 DAY TO VOLUME 'external' SETTINGS storage_policy='{}' """ .format('{replica}', storage_policy) ) if large_data: insert_large_data(node1, 'ttl_move_test') else: node1.query("INSERT INTO ttl_move_test VALUES (10, now() - INTERVAL 3 DAY)") node1.query("INSERT INTO ttl_move_test VALUES (11, now() - INTERVAL 1 DAY)") node1.query("OPTIMIZE TABLE ttl_move_test FINAL") node2.query("SYSTEM SYNC REPLICA ttl_move_test") if large_data: assert node1.query("SELECT count() FROM ttl_move_test FORMAT Values") == "(1572867)" assert node2.query("SELECT count() FROM ttl_move_test FORMAT Values") == "(1572867)" else: assert node1.query("SELECT count() FROM ttl_move_test FORMAT Values") == "(2)" assert node2.query("SELECT count() FROM ttl_move_test FORMAT Values") == "(2)" assert node1.query("SELECT d FROM ttl_move_test ORDER BY d FORMAT Values") == "(10),(11)" assert node2.query("SELECT d FROM ttl_move_test ORDER BY d FORMAT Values") == "(10),(11)" node1.query("DROP TABLE IF EXISTS ttl_move_test NO DELAY") node2.query("DROP TABLE IF EXISTS ttl_move_test NO DELAY") @pytest.mark.parametrize( ("large_data", "iterations"), [ (False, 10), (True, 3), ] ) def test_s3_zero_copy_with_ttl_delete(cluster, large_data, iterations): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query("DROP TABLE IF EXISTS ttl_delete_test NO DELAY") node2.query("DROP TABLE IF EXISTS ttl_delete_test NO DELAY") for i in range(iterations): node1.query( """ CREATE TABLE ttl_delete_test ON CLUSTER test_cluster (d UInt64, d1 DateTime) ENGINE=ReplicatedMergeTree('/clickhouse/tables/ttl_delete_test', '{}') ORDER BY d TTL d1 + INTERVAL 2 DAY SETTINGS storage_policy='tiered' """ .format('{replica}') ) if large_data: insert_large_data(node1, 'ttl_delete_test') else: node1.query("INSERT INTO ttl_delete_test VALUES (10, now() - INTERVAL 3 DAY)") node1.query("INSERT INTO ttl_delete_test VALUES (11, now() - INTERVAL 1 DAY)") node1.query("OPTIMIZE TABLE ttl_delete_test FINAL") node2.query("SYSTEM SYNC REPLICA ttl_delete_test") if large_data: assert node1.query("SELECT count() FROM ttl_delete_test FORMAT Values") == "(1310721)" assert node2.query("SELECT count() FROM ttl_delete_test FORMAT Values") == "(1310721)" else: assert node1.query("SELECT count() FROM ttl_delete_test FORMAT Values") == "(1)" assert node2.query("SELECT count() FROM ttl_delete_test FORMAT Values") == "(1)" assert node1.query("SELECT d FROM ttl_delete_test ORDER BY d FORMAT Values") == "(11)" assert node2.query("SELECT d FROM ttl_delete_test ORDER BY d FORMAT Values") == "(11)" node1.query("DROP TABLE IF EXISTS ttl_delete_test NO DELAY") node2.query("DROP TABLE IF EXISTS ttl_delete_test NO DELAY") def test_s3_zero_copy_concurrent_merge(cluster): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query("DROP TABLE IF EXISTS concurrent_merge NO DELAY") node2.query("DROP TABLE IF EXISTS concurrent_merge NO DELAY") for node in (node1, node2): node.query( """ CREATE TABLE concurrent_merge (id UInt64) ENGINE=ReplicatedMergeTree('/clickhouse/tables/concurrent_merge', '{replica}') ORDER BY id SETTINGS index_granularity=2, storage_policy='s3', remote_fs_execute_merges_on_single_replica_time_threshold=1 """ ) node1.query("system stop merges") node2.query("system stop merges") # This will generate two parts with 20 granules each node1.query("insert into concurrent_merge select number from numbers(40)") node1.query("insert into concurrent_merge select number + 1 from numbers(40)") wait_for_active_parts(node2, 2, 'concurrent_merge') # Merge will materialize default column, it should sleep every granule and take 20 * 2 * 0.1 = 4 sec. node1.query("alter table concurrent_merge add column x UInt32 default sleep(0.1)") node1.query("system start merges") node2.query("system start merges") # Now, the merge should start. # Because of remote_fs_execute_merges_on_single_replica_time_threshold=1, # only one replica will start merge instantly. # The other replica should wait for 1 sec and also start it. # That should probably cause a data race at s3 storage. # For now, it does not happen (every blob has a random name, and we just have a duplicating data) node1.query("optimize table concurrent_merge final") wait_for_active_parts(node1, 1, 'concurrent_merge') wait_for_active_parts(node2, 1, 'concurrent_merge') for node in (node1, node2): assert node.query('select sum(id) from concurrent_merge').strip() == '1600'
40.713376
136
0.660904
import datetime import logging import time import pytest from helpers.cluster import ClickHouseCluster logging.getLogger().setLevel(logging.INFO) logging.getLogger().addHandler(logging.StreamHandler()) @pytest.fixture(scope="module") def cluster(): try: cluster = ClickHouseCluster(__file__) cluster.add_instance("node1", main_configs=["configs/config.d/s3.xml"], macros={'replica': '1'}, with_minio=True, with_zookeeper=True) cluster.add_instance("node2", main_configs=["configs/config.d/s3.xml"], macros={'replica': '2'}, with_minio=True, with_zookeeper=True) logging.info("Starting cluster...") cluster.start() logging.info("Cluster started") yield cluster finally: cluster.shutdown() def get_large_objects_count(cluster, size=100, folder='data'): minio = cluster.minio_client counter = 0 for obj in minio.list_objects(cluster.minio_bucket, '{}/'.format(folder)): if obj.size >= size: counter = counter + 1 return counter def wait_for_large_objects_count(cluster, expected, size=100, timeout=30): while timeout > 0: if get_large_objects_count(cluster, size=size) == expected: return timeout -= 1 time.sleep(1) assert get_large_objects_count(cluster, size=size) == expected def wait_for_active_parts(node, num_expected_parts, table_name, timeout=30): deadline = time.monotonic() + timeout num_parts = 0 while time.monotonic() < deadline: num_parts_str = node.query("select count() from system.parts where table = '{}' and active".format(table_name)) num_parts = int(num_parts_str.strip()) if num_parts == num_expected_parts: return time.sleep(0.2) assert num_parts == num_expected_parts @pytest.mark.order(0) @pytest.mark.parametrize( "policy", ["s3"] ) def test_s3_zero_copy_replication(cluster, policy): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query( """ CREATE TABLE s3_test ON CLUSTER test_cluster (id UInt32, value String) ENGINE=ReplicatedMergeTree('/clickhouse/tables/s3_test', '{}') ORDER BY id SETTINGS storage_policy='{}' """ .format('{replica}', policy) ) node1.query("INSERT INTO s3_test VALUES (0,'data'),(1,'data')") node2.query("SYSTEM SYNC REPLICA s3_test") assert node1.query("SELECT * FROM s3_test order by id FORMAT Values") == "(0,'data'),(1,'data')" assert node2.query("SELECT * FROM s3_test order by id FORMAT Values") == "(0,'data'),(1,'data')" assert get_large_objects_count(cluster) == 1 node2.query("INSERT INTO s3_test VALUES (2,'data'),(3,'data')") node1.query("SYSTEM SYNC REPLICA s3_test") assert node2.query("SELECT * FROM s3_test order by id FORMAT Values") == "(0,'data'),(1,'data'),(2,'data'),(3,'data')" assert node1.query("SELECT * FROM s3_test order by id FORMAT Values") == "(0,'data'),(1,'data'),(2,'data'),(3,'data')" wait_for_large_objects_count(cluster, 2) node1.query("OPTIMIZE TABLE s3_test FINAL") wait_for_large_objects_count(cluster, 3) wait_for_large_objects_count(cluster, 1, timeout=60) node1.query("DROP TABLE IF EXISTS s3_test NO DELAY") node2.query("DROP TABLE IF EXISTS s3_test NO DELAY") def test_s3_zero_copy_on_hybrid_storage(cluster): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query( """ CREATE TABLE hybrid_test ON CLUSTER test_cluster (id UInt32, value String) ENGINE=ReplicatedMergeTree('/clickhouse/tables/hybrid_test', '{}') ORDER BY id SETTINGS storage_policy='hybrid' """ .format('{replica}') ) node1.query("INSERT INTO hybrid_test VALUES (0,'data'),(1,'data')") node2.query("SYSTEM SYNC REPLICA hybrid_test") assert node1.query("SELECT * FROM hybrid_test ORDER BY id FORMAT Values") == "(0,'data'),(1,'data')" assert node2.query("SELECT * FROM hybrid_test ORDER BY id FORMAT Values") == "(0,'data'),(1,'data')" assert node1.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','default')" assert node2.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','default')" node1.query("ALTER TABLE hybrid_test MOVE PARTITION ID 'all' TO DISK 's31'") assert node1.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','s31')" assert node2.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','default')" s3_objects = get_large_objects_count(cluster, size=0) node2.query("ALTER TABLE hybrid_test MOVE PARTITION ID 'all' TO DISK 's31'") assert node1.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','s31')" assert node2.query("SELECT partition_id,disk_name FROM system.parts WHERE table='hybrid_test' FORMAT Values") == "('all','s31')" wait_for_large_objects_count(cluster, s3_objects, size=0) assert node1.query("SELECT * FROM hybrid_test ORDER BY id FORMAT Values") == "(0,'data'),(1,'data')" assert node2.query("SELECT * FROM hybrid_test ORDER BY id FORMAT Values") == "(0,'data'),(1,'data')" node1.query("DROP TABLE IF EXISTS hybrid_test NO DELAY") node2.query("DROP TABLE IF EXISTS hybrid_test NO DELAY") def insert_data_time(node, table, number_of_mb, time, start=0): values = ','.join(f"({x},{time})" for x in range(start, int((1024 * 1024 * number_of_mb) / 8) + start + 1)) node.query(f"INSERT INTO {table} VALUES {values}") def insert_large_data(node, table): tm = time.mktime((datetime.date.today() - datetime.timedelta(days=7)).timetuple()) insert_data_time(node, table, 1, tm, 0) tm = time.mktime((datetime.date.today() - datetime.timedelta(days=3)).timetuple()) insert_data_time(node, table, 1, tm, 1024*1024) tm = time.mktime(datetime.date.today().timetuple()) insert_data_time(node, table, 10, tm, 1024*1024*2) @pytest.mark.parametrize( ("storage_policy", "large_data", "iterations"), [ ("tiered", False, 10), ("tiered_copy", False, 10), ("tiered", True, 3), ("tiered_copy", True, 3), ] ) def test_s3_zero_copy_with_ttl_move(cluster, storage_policy, large_data, iterations): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query("DROP TABLE IF EXISTS ttl_move_test NO DELAY") node2.query("DROP TABLE IF EXISTS ttl_move_test NO DELAY") for i in range(iterations): node1.query( """ CREATE TABLE ttl_move_test ON CLUSTER test_cluster (d UInt64, d1 DateTime) ENGINE=ReplicatedMergeTree('/clickhouse/tables/ttl_move_test', '{}') ORDER BY d TTL d1 + INTERVAL 2 DAY TO VOLUME 'external' SETTINGS storage_policy='{}' """ .format('{replica}', storage_policy) ) if large_data: insert_large_data(node1, 'ttl_move_test') else: node1.query("INSERT INTO ttl_move_test VALUES (10, now() - INTERVAL 3 DAY)") node1.query("INSERT INTO ttl_move_test VALUES (11, now() - INTERVAL 1 DAY)") node1.query("OPTIMIZE TABLE ttl_move_test FINAL") node2.query("SYSTEM SYNC REPLICA ttl_move_test") if large_data: assert node1.query("SELECT count() FROM ttl_move_test FORMAT Values") == "(1572867)" assert node2.query("SELECT count() FROM ttl_move_test FORMAT Values") == "(1572867)" else: assert node1.query("SELECT count() FROM ttl_move_test FORMAT Values") == "(2)" assert node2.query("SELECT count() FROM ttl_move_test FORMAT Values") == "(2)" assert node1.query("SELECT d FROM ttl_move_test ORDER BY d FORMAT Values") == "(10),(11)" assert node2.query("SELECT d FROM ttl_move_test ORDER BY d FORMAT Values") == "(10),(11)" node1.query("DROP TABLE IF EXISTS ttl_move_test NO DELAY") node2.query("DROP TABLE IF EXISTS ttl_move_test NO DELAY") @pytest.mark.parametrize( ("large_data", "iterations"), [ (False, 10), (True, 3), ] ) def test_s3_zero_copy_with_ttl_delete(cluster, large_data, iterations): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query("DROP TABLE IF EXISTS ttl_delete_test NO DELAY") node2.query("DROP TABLE IF EXISTS ttl_delete_test NO DELAY") for i in range(iterations): node1.query( """ CREATE TABLE ttl_delete_test ON CLUSTER test_cluster (d UInt64, d1 DateTime) ENGINE=ReplicatedMergeTree('/clickhouse/tables/ttl_delete_test', '{}') ORDER BY d TTL d1 + INTERVAL 2 DAY SETTINGS storage_policy='tiered' """ .format('{replica}') ) if large_data: insert_large_data(node1, 'ttl_delete_test') else: node1.query("INSERT INTO ttl_delete_test VALUES (10, now() - INTERVAL 3 DAY)") node1.query("INSERT INTO ttl_delete_test VALUES (11, now() - INTERVAL 1 DAY)") node1.query("OPTIMIZE TABLE ttl_delete_test FINAL") node2.query("SYSTEM SYNC REPLICA ttl_delete_test") if large_data: assert node1.query("SELECT count() FROM ttl_delete_test FORMAT Values") == "(1310721)" assert node2.query("SELECT count() FROM ttl_delete_test FORMAT Values") == "(1310721)" else: assert node1.query("SELECT count() FROM ttl_delete_test FORMAT Values") == "(1)" assert node2.query("SELECT count() FROM ttl_delete_test FORMAT Values") == "(1)" assert node1.query("SELECT d FROM ttl_delete_test ORDER BY d FORMAT Values") == "(11)" assert node2.query("SELECT d FROM ttl_delete_test ORDER BY d FORMAT Values") == "(11)" node1.query("DROP TABLE IF EXISTS ttl_delete_test NO DELAY") node2.query("DROP TABLE IF EXISTS ttl_delete_test NO DELAY") def test_s3_zero_copy_concurrent_merge(cluster): node1 = cluster.instances["node1"] node2 = cluster.instances["node2"] node1.query("DROP TABLE IF EXISTS concurrent_merge NO DELAY") node2.query("DROP TABLE IF EXISTS concurrent_merge NO DELAY") for node in (node1, node2): node.query( """ CREATE TABLE concurrent_merge (id UInt64) ENGINE=ReplicatedMergeTree('/clickhouse/tables/concurrent_merge', '{replica}') ORDER BY id SETTINGS index_granularity=2, storage_policy='s3', remote_fs_execute_merges_on_single_replica_time_threshold=1 """ ) node1.query("system stop merges") node2.query("system stop merges") node1.query("insert into concurrent_merge select number from numbers(40)") node1.query("insert into concurrent_merge select number + 1 from numbers(40)") wait_for_active_parts(node2, 2, 'concurrent_merge') node1.query("alter table concurrent_merge add column x UInt32 default sleep(0.1)") node1.query("system start merges") node2.query("system start merges") node1.query("optimize table concurrent_merge final") wait_for_active_parts(node1, 1, 'concurrent_merge') wait_for_active_parts(node2, 1, 'concurrent_merge') for node in (node1, node2): assert node.query('select sum(id) from concurrent_merge').strip() == '1600'
true
true
1c3713c65a243f5b58f9797d11119f784e2d2d9c
224
py
Python
QRCode/scan.py
sinalma/taobao_tools
222800ccd808ef4bbbcbcffc6b3f4fde133d8685
[ "MIT" ]
null
null
null
QRCode/scan.py
sinalma/taobao_tools
222800ccd808ef4bbbcbcffc6b3f4fde133d8685
[ "MIT" ]
null
null
null
QRCode/scan.py
sinalma/taobao_tools
222800ccd808ef4bbbcbcffc6b3f4fde133d8685
[ "MIT" ]
null
null
null
from PIL import Image import tesserocr, requests if __name__ == '__main__': image_path='F:/Python/Code/QRCode/test1431049.jpg'#图片文件路径 image = Image.open(image_path) result = tesserocr.image_to_text(image) print(result)
24.888889
58
0.776786
from PIL import Image import tesserocr, requests if __name__ == '__main__': image_path='F:/Python/Code/QRCode/test1431049.jpg' image = Image.open(image_path) result = tesserocr.image_to_text(image) print(result)
true
true
1c371414f8f302c1bfc87457632c7eb0eca5574e
887
py
Python
preproc.py
YasenPetrov/char-rnn-experiments
ae010e3f69173bb3a70a18907862529414d86d1a
[ "MIT" ]
null
null
null
preproc.py
YasenPetrov/char-rnn-experiments
ae010e3f69173bb3a70a18907862529414d86d1a
[ "MIT" ]
null
null
null
preproc.py
YasenPetrov/char-rnn-experiments
ae010e3f69173bb3a70a18907862529414d86d1a
[ "MIT" ]
null
null
null
import argparse from datautils.dataset import Alphabet from utils.general_utils import clean_and_split_file if __name__ == '__main__': parser = argparse.ArgumentParser(description='''Preprocesses files for PPM training''') parser.add_argument('source_file', metavar='source_file', type=str, help='A path to a the source file') parser.add_argument('dest_dir', metavar='dest_dir', type=str, help=' path to a directory in which the processed files will be saved') parser.add_argument('--use_first_n', default=0, type=int, help='Use only the first n characters of the text') # parser.add_argument('--alphabet_file', dest='alphabet_file', action='store_const', default=False) args = parser.parse_args() clean_and_split_file(args.source_file, args.dest_dir, .9, .05, .05, use_first_n_characters=args.use_first_n)
49.277778
113
0.715896
import argparse from datautils.dataset import Alphabet from utils.general_utils import clean_and_split_file if __name__ == '__main__': parser = argparse.ArgumentParser(description='''Preprocesses files for PPM training''') parser.add_argument('source_file', metavar='source_file', type=str, help='A path to a the source file') parser.add_argument('dest_dir', metavar='dest_dir', type=str, help=' path to a directory in which the processed files will be saved') parser.add_argument('--use_first_n', default=0, type=int, help='Use only the first n characters of the text') args = parser.parse_args() clean_and_split_file(args.source_file, args.dest_dir, .9, .05, .05, use_first_n_characters=args.use_first_n)
true
true
1c3714f8b97190de54387c05067462c712019aa2
7,071
py
Python
pyxform/tests_v1/test_support_external_instances.py
PMA-2020/pmaxform3
9d36f97f25cb09f0fb8aafb69370454731ecbbd5
[ "BSD-2-Clause" ]
null
null
null
pyxform/tests_v1/test_support_external_instances.py
PMA-2020/pmaxform3
9d36f97f25cb09f0fb8aafb69370454731ecbbd5
[ "BSD-2-Clause" ]
null
null
null
pyxform/tests_v1/test_support_external_instances.py
PMA-2020/pmaxform3
9d36f97f25cb09f0fb8aafb69370454731ecbbd5
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ Test external instance syntax """ from pyxform.tests_v1.pyxform_test_case import PyxformTestCase class ExternalCSVInstancesTest(PyxformTestCase): def test_external_csv_instances(self): # re: https://github.com/XLSForm/pyxform/issues/30 self.assertPyxformXform( name="ecsv", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.csv | city | City | | | select_multiple_from_file neighbourhoods.csv | neighbourhoods | Neighbourhoods | """, # noqa xml__contains=[ """<instance id="cities" src="jr://file-csv/cities.csv"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", # noqa '<select1 ref="/ecsv/city">', "<itemset nodeset=\"instance('cities')/root/item\">", """<instance id="neighbourhoods" src="jr://file-csv/neighbourhoods.csv"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", # noqa '<select ref="/ecsv/neighbourhoods">', "<itemset nodeset=\"instance('neighbourhoods')/root/item\">", ], run_odk_validate=True, ) def test_external_csv_instances_w_choice_filter(self): # re: https://github.com/XLSForm/pyxform/issues/30 self.assertPyxformXform( name="ecsv", md=""" | survey | | | | | | type | name | label | choice_filter | | | select_one_from_file cities.csv | city | City | | | | select_multiple_from_file neighbourhoods.csv | neighbourhoods | Neighbourhoods | city=${city} | """, # noqa xml__contains=[ """<instance id="cities" src="jr://file-csv/cities.csv"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", # noqa '<select1 ref="/ecsv/city">', """<instance id="neighbourhoods" src="jr://file-csv/neighbourhoods.csv"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", # noqa '<select ref="/ecsv/neighbourhoods">', "<itemset nodeset=\"instance('neighbourhoods')/root/item[city= /ecsv/city ]\">", # noqa ], run_odk_validate=True, ) class ExternalXMLInstancesTest(PyxformTestCase): def test_external_xml_instances(self): # re: https://github.com/XLSForm/pyxform/issues/30 self.assertPyxformXform( name="exml", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.xml | city | City | | | select_multiple_from_file neighbourhoods.xml | neighbourhoods | Neighbourhoods | """, # noqa xml__contains=[ """<instance id="cities" src="jr://file/cities.xml"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", # noqa '<select1 ref="/exml/city">', "<itemset nodeset=\"instance('cities')/root/item\">", """<instance id="neighbourhoods" src="jr://file/neighbourhoods.xml"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", # noqa '<select ref="/exml/neighbourhoods">', "<itemset nodeset=\"instance('neighbourhoods')/root/item\">", ], run_odk_validate=True, ) class InvalidExternalFileInstancesTest(PyxformTestCase): def test_external_other_extension_instances(self): # re: https://github.com/XLSForm/pyxform/issues/30 self.assertPyxformXform( name="epdf", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.pdf | city | City | | | select_multiple_from_file neighbourhoods.pdf | neighbourhoods | Neighbourhoods | """, # noqa errored=True, error_contains=["should be a choices sheet in this xlsform"], ) def test_external_choices_sheet_included_instances(self): # re: https://github.com/XLSForm/pyxform/issues/30 self.assertPyxformXform( name="epdf", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.pdf | city | City | | | select_multiple_from_file neighbourhoods.pdf | neighbourhoods | Neighbourhoods | | choices | | | list name | name | label | | | fruits | apple | Apple | """, # noqa errored=True, error__contains=["List name not in choices sheet: cities.pdf"], ) class ExternalCSVInstancesBugsTest(PyxformTestCase): def test_non_existent_itext_reference(self): # re: https://github.com/XLSForm/pyxform/issues/80 self.assertPyxformXform( name="ecsv", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.csv | city | City | | | select_multiple_from_file neighbourhoods.csv | neighbourhoods | Neighbourhoods | """, # noqa xml__contains=[ """<itemset nodeset="instance('cities')/root/item"> <value ref="name"/> <label ref="label"/> </itemset>""" ], )
42.089286
119
0.424975
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase class ExternalCSVInstancesTest(PyxformTestCase): def test_external_csv_instances(self): self.assertPyxformXform( name="ecsv", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.csv | city | City | | | select_multiple_from_file neighbourhoods.csv | neighbourhoods | Neighbourhoods | """, xml__contains=[ """<instance id="cities" src="jr://file-csv/cities.csv"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", '<select1 ref="/ecsv/city">', "<itemset nodeset=\"instance('cities')/root/item\">", """<instance id="neighbourhoods" src="jr://file-csv/neighbourhoods.csv"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", '<select ref="/ecsv/neighbourhoods">', "<itemset nodeset=\"instance('neighbourhoods')/root/item\">", ], run_odk_validate=True, ) def test_external_csv_instances_w_choice_filter(self): self.assertPyxformXform( name="ecsv", md=""" | survey | | | | | | type | name | label | choice_filter | | | select_one_from_file cities.csv | city | City | | | | select_multiple_from_file neighbourhoods.csv | neighbourhoods | Neighbourhoods | city=${city} | """, xml__contains=[ """<instance id="cities" src="jr://file-csv/cities.csv"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", '<select1 ref="/ecsv/city">', """<instance id="neighbourhoods" src="jr://file-csv/neighbourhoods.csv"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", '<select ref="/ecsv/neighbourhoods">', "<itemset nodeset=\"instance('neighbourhoods')/root/item[city= /ecsv/city ]\">", ], run_odk_validate=True, ) class ExternalXMLInstancesTest(PyxformTestCase): def test_external_xml_instances(self): self.assertPyxformXform( name="exml", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.xml | city | City | | | select_multiple_from_file neighbourhoods.xml | neighbourhoods | Neighbourhoods | """, xml__contains=[ """<instance id="cities" src="jr://file/cities.xml"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", '<select1 ref="/exml/city">', "<itemset nodeset=\"instance('cities')/root/item\">", """<instance id="neighbourhoods" src="jr://file/neighbourhoods.xml"> <root> <item> <name>_</name> <label>_</label> </item> </root> </instance>""", '<select ref="/exml/neighbourhoods">', "<itemset nodeset=\"instance('neighbourhoods')/root/item\">", ], run_odk_validate=True, ) class InvalidExternalFileInstancesTest(PyxformTestCase): def test_external_other_extension_instances(self): self.assertPyxformXform( name="epdf", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.pdf | city | City | | | select_multiple_from_file neighbourhoods.pdf | neighbourhoods | Neighbourhoods | """, errored=True, error_contains=["should be a choices sheet in this xlsform"], ) def test_external_choices_sheet_included_instances(self): self.assertPyxformXform( name="epdf", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.pdf | city | City | | | select_multiple_from_file neighbourhoods.pdf | neighbourhoods | Neighbourhoods | | choices | | | list name | name | label | | | fruits | apple | Apple | """, errored=True, error__contains=["List name not in choices sheet: cities.pdf"], ) class ExternalCSVInstancesBugsTest(PyxformTestCase): def test_non_existent_itext_reference(self): self.assertPyxformXform( name="ecsv", md=""" | survey | | | | | | type | name | label | | | select_one_from_file cities.csv | city | City | | | select_multiple_from_file neighbourhoods.csv | neighbourhoods | Neighbourhoods | """, xml__contains=[ """<itemset nodeset="instance('cities')/root/item"> <value ref="name"/> <label ref="label"/> </itemset>""" ], )
true
true
1c371548320574c02348dc736e51e1f71f3c4366
1,379
py
Python
run/core/setup/schema.py
matthewmuccio/TweetTweet
4ca6ae31fd3b8a1f32fd65676e945a3ec745ba9c
[ "MIT" ]
1
2020-03-30T04:00:15.000Z
2020-03-30T04:00:15.000Z
run/core/setup/schema.py
matthewmuccio/TweetTweet
4ca6ae31fd3b8a1f32fd65676e945a3ec745ba9c
[ "MIT" ]
null
null
null
run/core/setup/schema.py
matthewmuccio/TweetTweet
4ca6ae31fd3b8a1f32fd65676e945a3ec745ba9c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import sqlite3 connection = sqlite3.connect("master.db", check_same_thread=False) cursor = connection.cursor() # Creates users table. cursor.execute( """CREATE TABLE users( id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(20) UNIQUE NOT NULL, password VARCHAR(128) NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, num_posts INTEGER NOT NULL, num_reposts INTEGER NOT NULL, first_login DATETIME NOT NULL, last_login DATETIME NOT NULL );""" ) # Creates posts table. cursor.execute( """CREATE TABLE posts( id INTEGER PRIMARY KEY AUTOINCREMENT, author_username VARCHAR(20) NOT NULL, author_first_name VARCHAR(50) NOT NULL, author_last_name VARCHAR(50) NOT NULL, content VARCHAR(280) NOT NULL, post_time DATETIME NOT NULL, FOREIGN KEY(author_username) REFERENCES users(username), FOREIGN KEY(author_first_name) REFERENCES users(first_name), FOREIGN KEY(author_last_name) REFERENCES users(last_name) );""" ) # Creates reposts table. cursor.execute( """CREATE TABLE reposts( id INTEGER PRIMARY KEY AUTOINCREMENT, reposter_username VARCHAR(20) NOT NULL, post_id INTEGER NOT NULL, FOREIGN KEY(reposter_username) REFERENCES users(username), FOREIGN KEY(post_id) REFERENCES posts(id) );""" ) cursor.close() connection.close()
26.519231
67
0.729514
import sqlite3 connection = sqlite3.connect("master.db", check_same_thread=False) cursor = connection.cursor() cursor.execute( """CREATE TABLE users( id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(20) UNIQUE NOT NULL, password VARCHAR(128) NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, num_posts INTEGER NOT NULL, num_reposts INTEGER NOT NULL, first_login DATETIME NOT NULL, last_login DATETIME NOT NULL );""" ) cursor.execute( """CREATE TABLE posts( id INTEGER PRIMARY KEY AUTOINCREMENT, author_username VARCHAR(20) NOT NULL, author_first_name VARCHAR(50) NOT NULL, author_last_name VARCHAR(50) NOT NULL, content VARCHAR(280) NOT NULL, post_time DATETIME NOT NULL, FOREIGN KEY(author_username) REFERENCES users(username), FOREIGN KEY(author_first_name) REFERENCES users(first_name), FOREIGN KEY(author_last_name) REFERENCES users(last_name) );""" ) cursor.execute( """CREATE TABLE reposts( id INTEGER PRIMARY KEY AUTOINCREMENT, reposter_username VARCHAR(20) NOT NULL, post_id INTEGER NOT NULL, FOREIGN KEY(reposter_username) REFERENCES users(username), FOREIGN KEY(post_id) REFERENCES posts(id) );""" ) cursor.close() connection.close()
true
true
1c371550e1fc5c82bcba8cb87d91667ed7bcd636
4,883
py
Python
src/python/pants/backend/jvm/subsystems/jvm_tool_mixin.py
areitz/pants
9bfb3feb0272c05f36e190c9147091b97ee1950d
[ "Apache-2.0" ]
null
null
null
src/python/pants/backend/jvm/subsystems/jvm_tool_mixin.py
areitz/pants
9bfb3feb0272c05f36e190c9147091b97ee1950d
[ "Apache-2.0" ]
null
null
null
src/python/pants/backend/jvm/subsystems/jvm_tool_mixin.py
areitz/pants
9bfb3feb0272c05f36e190c9147091b97ee1950d
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.base.address_lookup_error import AddressLookupError from pants.base.exceptions import TaskError from pants.option.custom_types import target_list_option class JvmToolMixin(object): """A mixin for registering and accessing JVM-based tools. Must be mixed in to something that can register and use options, e.g., a Task or a Subsystem. """ class DepLookupError(AddressLookupError): """Thrown when a dependency can't be found.""" pass _tool_keys = [] # List of (scope, key, main, custom_rule) tuples. @classmethod def register_jvm_tool(cls, register, key, default=None, main=None, custom_rules=None, fingerprint=True): """Registers a jvm tool under `key` for lazy classpath resolution. Classpaths can be retrieved in `execute` scope via `tool_classpath`. NB: If the tool's `main` class name is supplied the tool classpath will be shaded. :param register: A function that can register options with the option system. :param unicode key: The key the tool configuration should be registered under. :param list default: The default tool classpath target address specs to use. :param unicode main: The fully qualified class name of the tool's main class if shading of the tool classpath is desired. :param list custom_rules: An optional list of `Shader.Rule`s to apply before the automatically generated binary jar shading rules. This is useful for excluding classes shared between the tool and the code it runs over. The canonical example is the `org.junit.Test` annotation read by junit runner tools from user code. In this sort of case the shared code must have a uniform name between the tool and the user code and so the shared code must be excluded from shading. :param bool fingerprint: Indicates whether to include the jvm tool in the task's fingerprint. Note that unlike for other options, fingerprinting is enabled for tools by default. """ register('--{0}'.format(key), advanced=True, type=target_list_option, default=['//:{0}'.format(key)] if default is None else default, help='Target specs for bootstrapping the {0} tool.'.format(key), fingerprint=fingerprint) # TODO(John Sirois): Move towards requiring tool specs point to jvm_binary targets. # These already have a main and are a natural place to house any custom shading rules. That # would eliminate the need to pass main and custom_rules here. # It is awkward that jars can no longer be inlined as dependencies - this will require 2 targets # for every tool - the jvm_binary, and a jar_library for its dependencies to point to. It may # be worth creating a JarLibrary subclass - say JarBinary, or else mixing in a Binary interface # to JarLibrary to endow it with main and shade_rules attributes to allow for single-target # definition of resolvable jvm binaries. JvmToolMixin._tool_keys.append((register.scope, key, main, custom_rules)) @staticmethod def get_registered_tools(): return JvmToolMixin._tool_keys @staticmethod def reset_registered_tools(): """Needed only for test isolation.""" JvmToolMixin._tool_keys = [] def tool_targets(self, context, key): """Return the Target objects obtained by resolving a tool's specs.""" specs = self.get_options()[key] targets = [] for spec in specs: # Resolve to actual targets. try: targets.extend(context.resolve(spec)) except AddressLookupError as e: raise self.DepLookupError("{message}\n specified by option --{key} in scope {scope}." .format(message=e, key=key, scope=self.options_scope)) return targets def tool_classpath_from_products(self, products, key, scope): """Get a classpath for the tool previously registered under key in the given scope. Returns a list of paths. """ callback_product_map = products.get_data('jvm_build_tools_classpath_callbacks') or {} callback = callback_product_map.get(scope, {}).get(key) if not callback: raise TaskError('No bootstrap callback registered for {key} in {scope}' .format(key=key, scope=scope)) return callback()
48.83
106
0.670489
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.base.address_lookup_error import AddressLookupError from pants.base.exceptions import TaskError from pants.option.custom_types import target_list_option class JvmToolMixin(object): class DepLookupError(AddressLookupError): pass _tool_keys = [] @classmethod def register_jvm_tool(cls, register, key, default=None, main=None, custom_rules=None, fingerprint=True): register('--{0}'.format(key), advanced=True, type=target_list_option, default=['//:{0}'.format(key)] if default is None else default, help='Target specs for bootstrapping the {0} tool.'.format(key), fingerprint=fingerprint) JvmToolMixin._tool_keys.append((register.scope, key, main, custom_rules)) @staticmethod def get_registered_tools(): return JvmToolMixin._tool_keys @staticmethod def reset_registered_tools(): JvmToolMixin._tool_keys = [] def tool_targets(self, context, key): specs = self.get_options()[key] targets = [] for spec in specs: try: targets.extend(context.resolve(spec)) except AddressLookupError as e: raise self.DepLookupError("{message}\n specified by option --{key} in scope {scope}." .format(message=e, key=key, scope=self.options_scope)) return targets def tool_classpath_from_products(self, products, key, scope): callback_product_map = products.get_data('jvm_build_tools_classpath_callbacks') or {} callback = callback_product_map.get(scope, {}).get(key) if not callback: raise TaskError('No bootstrap callback registered for {key} in {scope}' .format(key=key, scope=scope)) return callback()
true
true
1c3715d4e6766bf36a21922def2df4a36fcbc0b5
10
py
Python
Toolkit/Flattenizer/flattenizer_gui.py
croxis/RenderPipeline
43482c03a835dd620e6d45b08e56fa5679742482
[ "WTFPL" ]
null
null
null
Toolkit/Flattenizer/flattenizer_gui.py
croxis/RenderPipeline
43482c03a835dd620e6d45b08e56fa5679742482
[ "WTFPL" ]
null
null
null
Toolkit/Flattenizer/flattenizer_gui.py
croxis/RenderPipeline
43482c03a835dd620e6d45b08e56fa5679742482
[ "WTFPL" ]
null
null
null
# todo
2
6
0.4
true
true
1c371601e8e865fd0e4a08277966d6ce798dac89
3,104
py
Python
textattack/constraints/grammaticality/language_models/learning_to_write/rnn_model.py
k-ivey/TextAttack
47d15acea90bf92e6a7f19200a59da29e74731e6
[ "MIT" ]
1
2020-12-04T18:05:44.000Z
2020-12-04T18:05:44.000Z
textattack/constraints/grammaticality/language_models/learning_to_write/rnn_model.py
k-ivey/TextAttack
47d15acea90bf92e6a7f19200a59da29e74731e6
[ "MIT" ]
null
null
null
textattack/constraints/grammaticality/language_models/learning_to_write/rnn_model.py
k-ivey/TextAttack
47d15acea90bf92e6a7f19200a59da29e74731e6
[ "MIT" ]
null
null
null
from torch import nn as nn from torch.autograd import Variable from .adaptive_softmax import AdaptiveSoftmax class RNNModel(nn.Module): """Container module with an encoder, a recurrent module, and a decoder. Based on official pytorch examples """ def __init__( self, rnn_type, ntoken, ninp, nhid, nlayers, cutoffs, proj=False, dropout=0.5, tie_weights=False, lm1b=False, ): super(RNNModel, self).__init__() self.drop = nn.Dropout(dropout) self.encoder = nn.Embedding(ntoken, ninp) self.lm1b = lm1b if rnn_type == "GRU": self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout) else: try: nonlinearity = {"RNN_TANH": "tanh", "RNN_RELU": "relu"}[rnn_type] except KeyError: raise ValueError( """An invalid option for `--model` was supplied, options are ['GRU', 'RNN_TANH' or 'RNN_RELU']""" ) self.rnn = nn.RNN( ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout ) self.proj = proj if ninp != nhid and proj: self.proj_layer = nn.Linear(nhid, ninp) # if tie_weights: # if nhid != ninp and not proj: # raise ValueError('When using the tied flag, nhid must be equal to emsize') # self.decoder = nn.Linear(ninp, ntoken) # self.decoder.weight = self.encoder.weight # else: # if nhid != ninp and not proj: # if not lm1b: # self.decoder = nn.Linear(nhid, ntoken) # else: # self.decoder = adapt_loss # else: # self.decoder = nn.Linear(ninp, ntoken) self.init_weights() self.rnn_type = rnn_type self.nhid = nhid self.nlayers = nlayers if proj: self.softmax = AdaptiveSoftmax(ninp, cutoffs) else: self.softmax = AdaptiveSoftmax(nhid, cutoffs) self.full = False def init_weights(self): initrange = 0.1 self.encoder.weight.data.uniform_(-initrange, initrange) # self.decoder.bias.data.fill_(0) # self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, input, hidden): emb = self.drop(self.encoder(input)) output, hidden = self.rnn(emb, hidden) output = self.drop(output) if "proj" in vars(self): if self.proj: output = self.proj_layer(output) output = output.view(output.size(0) * output.size(1), output.size(2)) if self.full: decode = self.softmax.log_prob(output) else: decode = self.softmax(output) return decode, hidden def init_hidden(self, bsz): weight = next(self.parameters()).data return Variable(weight.new(self.nlayers, bsz, self.nhid).zero_())
29.561905
92
0.545425
from torch import nn as nn from torch.autograd import Variable from .adaptive_softmax import AdaptiveSoftmax class RNNModel(nn.Module): def __init__( self, rnn_type, ntoken, ninp, nhid, nlayers, cutoffs, proj=False, dropout=0.5, tie_weights=False, lm1b=False, ): super(RNNModel, self).__init__() self.drop = nn.Dropout(dropout) self.encoder = nn.Embedding(ntoken, ninp) self.lm1b = lm1b if rnn_type == "GRU": self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers, dropout=dropout) else: try: nonlinearity = {"RNN_TANH": "tanh", "RNN_RELU": "relu"}[rnn_type] except KeyError: raise ValueError( """An invalid option for `--model` was supplied, options are ['GRU', 'RNN_TANH' or 'RNN_RELU']""" ) self.rnn = nn.RNN( ninp, nhid, nlayers, nonlinearity=nonlinearity, dropout=dropout ) self.proj = proj if ninp != nhid and proj: self.proj_layer = nn.Linear(nhid, ninp) self.init_weights() self.rnn_type = rnn_type self.nhid = nhid self.nlayers = nlayers if proj: self.softmax = AdaptiveSoftmax(ninp, cutoffs) else: self.softmax = AdaptiveSoftmax(nhid, cutoffs) self.full = False def init_weights(self): initrange = 0.1 self.encoder.weight.data.uniform_(-initrange, initrange) def forward(self, input, hidden): emb = self.drop(self.encoder(input)) output, hidden = self.rnn(emb, hidden) output = self.drop(output) if "proj" in vars(self): if self.proj: output = self.proj_layer(output) output = output.view(output.size(0) * output.size(1), output.size(2)) if self.full: decode = self.softmax.log_prob(output) else: decode = self.softmax(output) return decode, hidden def init_hidden(self, bsz): weight = next(self.parameters()).data return Variable(weight.new(self.nlayers, bsz, self.nhid).zero_())
true
true
1c371610c95e03dca0b7df0fdff01ba7ea7c9f2a
8,512
py
Python
test/test_gameservice.py
pteichman/wildcatting-classic
bfe7d4cf699f6792f43d70f32b5d83969d29f91e
[ "MIT" ]
1
2020-04-13T21:21:04.000Z
2020-04-13T21:21:04.000Z
test/test_gameservice.py
pteichman/wildcatting-classic
bfe7d4cf699f6792f43d70f32b5d83969d29f91e
[ "MIT" ]
null
null
null
test/test_gameservice.py
pteichman/wildcatting-classic
bfe7d4cf699f6792f43d70f32b5d83969d29f91e
[ "MIT" ]
null
null
null
import unittest import base64 from wildcatting.exceptions import WildcattingException from wildcatting.server import GameService from wildcatting.model import Site, Well from wildcatting.theme import DefaultTheme class TestGameService(unittest.TestCase): def testGameStart(self): service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() gameId = service.new(10, 10, 13) handle1 = service.join(gameId, name1, well1) game, player1 = service._readHandle(handle1) self.assertEquals(False, service.isStarted(handle1)) service.start(handle1) self.assertEquals(True, service.isStarted(handle1)) def testShortGame(self): # start a game, survey once by each player service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() name2 = "bob" well2 = name2[0].upper() # create the game, join it gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) handle2 = service.join(gameId, name2, well2) game, player1 = service._readHandle(handle1) game, player2 = service._readHandle(handle2) self.assertEquals(False, service.isStarted(handle1)) self.assertEquals(False, service.isStarted(handle2)) # make sure player 2 isn't the game master self.assertRaises(WildcattingException, service.start, handle2) # start the game service.start(handle1) # make sure both players see the game started self.assertEquals(True, service.isStarted(handle1)) self.assertEquals(True, service.isStarted(handle2)) # make sure it's week 1 game, player = service._readHandle(handle1) self.assertEquals(1, game.getWeek().getWeekNum()) # it's player 1's turn - make sure player 2 can't survey self.assertRaises(WildcattingException, service.survey, handle2, 0, 0) # survey as player 1 site1 = Site.deserialize(service.survey(handle1, 0, 0)) # make sure player 1 can't survey twice in one turn self.assertRaises(WildcattingException, service.survey, handle1, 0, 0) # end player 1's turn service.endTurn(handle1) # make sure player 1 can't survey anymore self.assertRaises(WildcattingException, service.survey, handle1, 0, 0) # make sure it's still week 1 game, player = service._readHandle(handle1) self.assertEquals(1, game.getWeek().getWeekNum()) # survey as player 2 site2 = Site.deserialize(service.survey(handle2, 0, 1)) # end player 2's turn service.endTurn(handle2) # make sure player 2 can't survey anymore self.assertRaises(WildcattingException, service.survey, handle2, 0, 0) # make sure week is 2 game, player = service._readHandle(handle1) self.assertEquals(2, game.getWeek().getWeekNum()) # make sure both players see the game ended self.assertEquals(True, service.isFinished(handle1)) self.assertEquals(True, service.isFinished(handle2)) def testDrilling(self): # start a game, survey once by each player service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() # create the game, join it gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) game, player1 = service._readHandle(handle1) self.assertEquals(False, service.isStarted(handle1)) # start the game service.start(handle1) self.assertEquals(True, service.isStarted(handle1)) x, y = 0, 0 # survey site = Site.deserialize(service.survey(handle1, x, y)) site = Site.deserialize(service.erect(handle1, x, y)) well = site.getWell() while well.getOutput() is None and well.getDrillDepth() < 10: well = Well.deserialize(service.drill(handle1, x, y)) def testSneakyErecting(self): # start a game, survey once by each player service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() # create the game, join it gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) game, player1 = service._readHandle(handle1) self.assertEquals(False, service.isStarted(handle1)) # start the game service.start(handle1) self.assertEquals(True, service.isStarted(handle1)) # survey site1 = Site.deserialize(service.survey(handle1, 0, 0)) # make sure we can't erect elsewhere self.assertRaises(WildcattingException, service.survey, handle1, 0, 1) def testSneakyDrilling(self): # start a game, survey once by each player service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() # create the game, join it gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) game, player1 = service._readHandle(handle1) self.assertEquals(False, service.isStarted(handle1)) # start the game service.start(handle1) self.assertEquals(True, service.isStarted(handle1)) x, y = 0, 0 # survey site = Site.deserialize(service.survey(handle1, x, y)) site = Site.deserialize(service.erect(handle1, x, y)) well = Well.deserialize(service.drill(handle1, x, y)) self.assertRaises(WildcattingException, service.drill, handle1, x, y+1) def testSimultaneousGame(self): # start a game, survey once by each player service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() name2 = "bob" well2 = name2[0].upper() # create the game, join it gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) handle2 = service.join(gameId, name2, well2) game, player1 = service._readHandle(handle1) game, player2 = service._readHandle(handle2) self.assertEquals(False, service.isStarted(handle1)) self.assertEquals(False, service.isStarted(handle2)) service.start(handle1) self.assertEquals(name1, service.getPlayersTurn(handle1)) self.assertEquals(name1, service.getPlayersTurn(handle2)) site1 = Site.deserialize(service.survey(handle1, 0, 0)) self.assertEquals(name2, service.getPlayersTurn(handle1)) self.assertEquals(name2, service.getPlayersTurn(handle2)) site2 = Site.deserialize(service.survey(handle2, 0, 1)) service.endTurn(handle1) service.endTurn(handle2) def testGameWithoutSurvey(self): service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() name2 = "bob" well2 = name2[0].upper() name3 = "carol" well3 = name3[0].upper() # create the game, join it gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) handle2 = service.join(gameId, name2, well2) handle3 = service.join(gameId, name3, well3) game, player1 = service._readHandle(handle1) game, player2 = service._readHandle(handle2) game, player3 = service._readHandle(handle3) service.start(handle1) self.assertEquals(name1, service.getPlayersTurn(handle1)) self.assertEquals(name1, service.getPlayersTurn(handle2)) self.assertEquals(name1, service.getPlayersTurn(handle3)) site1 = Site.deserialize(service.survey(handle1, 0, 0)) service.endTurn(handle1) self.assertEquals(name2, service.getPlayersTurn(handle1)) self.assertEquals(name2, service.getPlayersTurn(handle2)) self.assertEquals(name2, service.getPlayersTurn(handle3)) service.endTurn(handle2) self.assertEquals(name3, service.getPlayersTurn(handle1)) self.assertEquals(name3, service.getPlayersTurn(handle2)) self.assertEquals(name3, service.getPlayersTurn(handle3)) service.endTurn(handle3) self.assertEquals(name1, service.getPlayersTurn(handle1)) self.assertEquals(name1, service.getPlayersTurn(handle2)) self.assertEquals(name1, service.getPlayersTurn(handle3)) if __name__ == "__main__": unittest.main()
32.48855
79
0.645794
import unittest import base64 from wildcatting.exceptions import WildcattingException from wildcatting.server import GameService from wildcatting.model import Site, Well from wildcatting.theme import DefaultTheme class TestGameService(unittest.TestCase): def testGameStart(self): service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() gameId = service.new(10, 10, 13) handle1 = service.join(gameId, name1, well1) game, player1 = service._readHandle(handle1) self.assertEquals(False, service.isStarted(handle1)) service.start(handle1) self.assertEquals(True, service.isStarted(handle1)) def testShortGame(self): service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() name2 = "bob" well2 = name2[0].upper() gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) handle2 = service.join(gameId, name2, well2) game, player1 = service._readHandle(handle1) game, player2 = service._readHandle(handle2) self.assertEquals(False, service.isStarted(handle1)) self.assertEquals(False, service.isStarted(handle2)) self.assertRaises(WildcattingException, service.start, handle2) # start the game service.start(handle1) # make sure both players see the game started self.assertEquals(True, service.isStarted(handle1)) self.assertEquals(True, service.isStarted(handle2)) # make sure it's week 1 game, player = service._readHandle(handle1) self.assertEquals(1, game.getWeek().getWeekNum()) self.assertRaises(WildcattingException, service.survey, handle2, 0, 0) # survey as player 1 site1 = Site.deserialize(service.survey(handle1, 0, 0)) # make sure player 1 can't survey twice in one turn self.assertRaises(WildcattingException, service.survey, handle1, 0, 0) service.endTurn(handle1) # make sure player 1 can't survey anymore self.assertRaises(WildcattingException, service.survey, handle1, 0, 0) game, player = service._readHandle(handle1) self.assertEquals(1, game.getWeek().getWeekNum()) # survey as player 2 site2 = Site.deserialize(service.survey(handle2, 0, 1)) # end player 2's turn service.endTurn(handle2) self.assertRaises(WildcattingException, service.survey, handle2, 0, 0) # make sure week is 2 game, player = service._readHandle(handle1) self.assertEquals(2, game.getWeek().getWeekNum()) # make sure both players see the game ended self.assertEquals(True, service.isFinished(handle1)) self.assertEquals(True, service.isFinished(handle2)) def testDrilling(self): # start a game, survey once by each player service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() # create the game, join it gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) game, player1 = service._readHandle(handle1) self.assertEquals(False, service.isStarted(handle1)) # start the game service.start(handle1) self.assertEquals(True, service.isStarted(handle1)) x, y = 0, 0 # survey site = Site.deserialize(service.survey(handle1, x, y)) site = Site.deserialize(service.erect(handle1, x, y)) well = site.getWell() while well.getOutput() is None and well.getDrillDepth() < 10: well = Well.deserialize(service.drill(handle1, x, y)) def testSneakyErecting(self): # start a game, survey once by each player service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() # create the game, join it gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) game, player1 = service._readHandle(handle1) self.assertEquals(False, service.isStarted(handle1)) # start the game service.start(handle1) self.assertEquals(True, service.isStarted(handle1)) # survey site1 = Site.deserialize(service.survey(handle1, 0, 0)) # make sure we can't erect elsewhere self.assertRaises(WildcattingException, service.survey, handle1, 0, 1) def testSneakyDrilling(self): service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) game, player1 = service._readHandle(handle1) self.assertEquals(False, service.isStarted(handle1)) service.start(handle1) self.assertEquals(True, service.isStarted(handle1)) x, y = 0, 0 site = Site.deserialize(service.survey(handle1, x, y)) site = Site.deserialize(service.erect(handle1, x, y)) well = Well.deserialize(service.drill(handle1, x, y)) self.assertRaises(WildcattingException, service.drill, handle1, x, y+1) def testSimultaneousGame(self): service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() name2 = "bob" well2 = name2[0].upper() gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) handle2 = service.join(gameId, name2, well2) game, player1 = service._readHandle(handle1) game, player2 = service._readHandle(handle2) self.assertEquals(False, service.isStarted(handle1)) self.assertEquals(False, service.isStarted(handle2)) service.start(handle1) self.assertEquals(name1, service.getPlayersTurn(handle1)) self.assertEquals(name1, service.getPlayersTurn(handle2)) site1 = Site.deserialize(service.survey(handle1, 0, 0)) self.assertEquals(name2, service.getPlayersTurn(handle1)) self.assertEquals(name2, service.getPlayersTurn(handle2)) site2 = Site.deserialize(service.survey(handle2, 0, 1)) service.endTurn(handle1) service.endTurn(handle2) def testGameWithoutSurvey(self): service = GameService(DefaultTheme()) name1 = "alice" well1 = name1[0].upper() name2 = "bob" well2 = name2[0].upper() name3 = "carol" well3 = name3[0].upper() gameId = service.new(10, 10, 1) handle1 = service.join(gameId, name1, well1) handle2 = service.join(gameId, name2, well2) handle3 = service.join(gameId, name3, well3) game, player1 = service._readHandle(handle1) game, player2 = service._readHandle(handle2) game, player3 = service._readHandle(handle3) service.start(handle1) self.assertEquals(name1, service.getPlayersTurn(handle1)) self.assertEquals(name1, service.getPlayersTurn(handle2)) self.assertEquals(name1, service.getPlayersTurn(handle3)) site1 = Site.deserialize(service.survey(handle1, 0, 0)) service.endTurn(handle1) self.assertEquals(name2, service.getPlayersTurn(handle1)) self.assertEquals(name2, service.getPlayersTurn(handle2)) self.assertEquals(name2, service.getPlayersTurn(handle3)) service.endTurn(handle2) self.assertEquals(name3, service.getPlayersTurn(handle1)) self.assertEquals(name3, service.getPlayersTurn(handle2)) self.assertEquals(name3, service.getPlayersTurn(handle3)) service.endTurn(handle3) self.assertEquals(name1, service.getPlayersTurn(handle1)) self.assertEquals(name1, service.getPlayersTurn(handle2)) self.assertEquals(name1, service.getPlayersTurn(handle3)) if __name__ == "__main__": unittest.main()
true
true
1c37161cbdb144f148feab8b0fd5cde889335344
11,874
py
Python
tests/sentry/tasks/test_deletion.py
kinghuang/sentry
5c22673994a62f54a782d1c595852986ccc51ae9
[ "BSD-3-Clause" ]
1
2019-10-17T17:46:16.000Z
2019-10-17T17:46:16.000Z
tests/sentry/tasks/test_deletion.py
kinghuang/sentry
5c22673994a62f54a782d1c595852986ccc51ae9
[ "BSD-3-Clause" ]
null
null
null
tests/sentry/tasks/test_deletion.py
kinghuang/sentry
5c22673994a62f54a782d1c595852986ccc51ae9
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from datetime import datetime, timedelta from mock import patch from uuid import uuid4 import pytest from sentry.constants import ObjectStatus from sentry.exceptions import DeleteAborted from sentry.models import ( ApiApplication, ApiApplicationStatus, ApiGrant, ApiToken, Commit, CommitAuthor, Environment, EnvironmentProject, Event, Group, GroupAssignee, GroupHash, GroupMeta, GroupRedirect, GroupResolution, GroupStatus, Organization, OrganizationStatus, Project, ProjectStatus, Release, ReleaseCommit, ReleaseEnvironment, Repository, Team, TeamStatus, ) from sentry.plugins.providers.dummy.repository import DummyRepositoryProvider from sentry.tasks.deletion import ( delete_api_application, delete_groups, delete_organization, delete_project, delete_repository, delete_team, generic_delete, revoke_api_tokens, ) from sentry.testutils import TestCase from sentry.testutils.helpers.datetime import iso_format, before_now class DeleteOrganizationTest(TestCase): def test_simple(self): org = self.create_organization(name="test", status=OrganizationStatus.PENDING_DELETION) user = self.create_user() self.create_team(organization=org, name="test1") self.create_team(organization=org, name="test2") release = Release.objects.create(version="a" * 32, organization_id=org.id) repo = Repository.objects.create(organization_id=org.id, name=org.name, provider="dummy") commit_author = CommitAuthor.objects.create( organization_id=org.id, name="foo", email="foo@example.com" ) commit = Commit.objects.create( repository_id=repo.id, organization_id=org.id, author=commit_author, key="a" * 40 ) ReleaseCommit.objects.create( organization_id=org.id, release=release, commit=commit, order=0 ) env = Environment.objects.create(organization_id=org.id, project_id=4, name="foo") release_env = ReleaseEnvironment.objects.create( organization_id=org.id, project_id=4, release_id=release.id, environment_id=env.id ) with self.tasks(): with patch.object(DummyRepositoryProvider, "delete_repository") as mock_delete_repo: delete_organization(object_id=org.id, actor_id=user.id) assert mock_delete_repo.call_count == 1 assert not Organization.objects.filter(id=org.id).exists() assert not Environment.objects.filter(id=env.id).exists() assert not ReleaseEnvironment.objects.filter(id=release_env.id).exists() assert not Repository.objects.filter(id=repo.id).exists() assert not ReleaseCommit.objects.filter(organization_id=org.id).exists() assert not Release.objects.filter(organization_id=org.id).exists() assert not CommitAuthor.objects.filter(id=commit_author.id).exists() assert not Commit.objects.filter(id=commit.id).exists() def test_cancels_without_pending_status(self): org = self.create_organization(name="test", status=OrganizationStatus.VISIBLE) self.create_team(organization=org, name="test1") self.create_team(organization=org, name="test2") with self.assertRaises(DeleteAborted): with self.tasks(): delete_organization(object_id=org.id) assert Organization.objects.filter(id=org.id).exists() class DeleteTeamTest(TestCase): def test_simple(self): team = self.create_team(name="test", status=TeamStatus.PENDING_DELETION) self.create_project(teams=[team], name="test1") self.create_project(teams=[team], name="test2") with self.tasks(): delete_team(object_id=team.id) assert not Team.objects.filter(id=team.id).exists() def test_cancels_without_pending_status(self): team = self.create_team(name="test", status=TeamStatus.VISIBLE) self.create_project(teams=[team], name="test1") self.create_project(teams=[team], name="test2") with self.assertRaises(DeleteAborted): with self.tasks(): delete_team(object_id=team.id) assert Team.objects.filter(id=team.id).exists() class DeleteProjectTest(TestCase): def test_simple(self): project = self.create_project(name="test", status=ProjectStatus.PENDING_DELETION) group = self.create_group(project=project) GroupAssignee.objects.create(group=group, project=project, user=self.user) GroupMeta.objects.create(group=group, key="foo", value="bar") release = Release.objects.create(version="a" * 32, organization_id=project.organization_id) release.add_project(project) GroupResolution.objects.create(group=group, release=release) env = Environment.objects.create( organization_id=project.organization_id, project_id=project.id, name="foo" ) env.add_project(project) repo = Repository.objects.create(organization_id=project.organization_id, name=project.name) commit_author = CommitAuthor.objects.create( organization_id=project.organization_id, name="foo", email="foo@example.com" ) commit = Commit.objects.create( repository_id=repo.id, organization_id=project.organization_id, author=commit_author, key="a" * 40, ) ReleaseCommit.objects.create( organization_id=project.organization_id, project_id=project.id, release=release, commit=commit, order=0, ) with self.tasks(): delete_project(object_id=project.id) assert not Project.objects.filter(id=project.id).exists() assert not EnvironmentProject.objects.filter( project_id=project.id, environment_id=env.id ).exists() assert Environment.objects.filter(id=env.id).exists() assert Release.objects.filter(id=release.id).exists() assert ReleaseCommit.objects.filter(release_id=release.id).exists() assert Commit.objects.filter(id=commit.id).exists() def test_cancels_without_pending_status(self): project = self.create_project(name="test", status=ProjectStatus.VISIBLE) with self.assertRaises(DeleteAborted): with self.tasks(): delete_project(object_id=project.id) assert Project.objects.filter(id=project.id).exists() class DeleteGroupTest(TestCase): def test_simple(self): event_id = "a" * 32 project = self.create_project() event = self.store_event( data={"event_id": event_id, "timestamp": iso_format(before_now(minutes=1))}, project_id=project.id, ) group = event.group group.update(status=GroupStatus.PENDING_DELETION) GroupAssignee.objects.create(group=group, project=project, user=self.user) GroupHash.objects.create(project=project, group=group, hash=uuid4().hex) GroupMeta.objects.create(group=group, key="foo", value="bar") GroupRedirect.objects.create(group_id=group.id, previous_group_id=1) with self.tasks(): delete_groups(object_ids=[group.id]) assert not Event.objects.filter(id=event.id).exists() assert not GroupRedirect.objects.filter(group_id=group.id).exists() assert not GroupHash.objects.filter(group_id=group.id).exists() assert not Group.objects.filter(id=group.id).exists() class DeleteApplicationTest(TestCase): def test_simple(self): app = ApiApplication.objects.create( owner=self.user, status=ApiApplicationStatus.pending_deletion ) ApiToken.objects.create(application=app, user=self.user, scopes=0) ApiGrant.objects.create( application=app, user=self.user, scopes=0, redirect_uri="http://example.com" ) with self.tasks(): delete_api_application(object_id=app.id) assert not ApiApplication.objects.filter(id=app.id).exists() assert not ApiGrant.objects.filter(application=app).exists() assert not ApiToken.objects.filter(application=app).exists() class RevokeApiTokensTest(TestCase): def test_basic(self): app = ApiApplication.objects.create(owner=self.user) token1 = ApiToken.objects.create( application=app, user=self.create_user("bar@example.com"), scopes=0 ) token2 = ApiToken.objects.create( application=app, user=self.create_user("foo@example.com"), scopes=0 ) with self.tasks(): revoke_api_tokens(object_id=app.id) assert not ApiToken.objects.filter(id=token1.id).exists() assert not ApiToken.objects.filter(id=token2.id).exists() def test_with_timestamp(self): cutoff = datetime(2017, 1, 1) app = ApiApplication.objects.create(owner=self.user) token1 = ApiToken.objects.create( application=app, user=self.create_user("bar@example.com"), scopes=0, date_added=cutoff ) token2 = ApiToken.objects.create( application=app, user=self.create_user("foo@example.com"), scopes=0, date_added=cutoff + timedelta(days=1), ) with self.tasks(): revoke_api_tokens(object_id=app.id, timestamp=cutoff) assert not ApiToken.objects.filter(id=token1.id).exists() assert ApiToken.objects.filter(id=token2.id).exists() class GenericDeleteTest(TestCase): def test_does_not_delete_visible(self): project = self.create_project(status=ObjectStatus.VISIBLE) with self.tasks(): with pytest.raises(DeleteAborted): generic_delete("sentry", "project", object_id=project.id) project = Project.objects.get(id=project.id) assert project.status == ObjectStatus.VISIBLE def test_deletes(self): project = self.create_project(status=ObjectStatus.PENDING_DELETION) with self.tasks(): generic_delete("sentry", "project", object_id=project.id) assert not Project.objects.filter(id=project.id).exists() class DeleteRepoTest(TestCase): def test_does_not_delete_visible(self): org = self.create_organization() repo = Repository.objects.create( status=ObjectStatus.VISIBLE, provider="dummy", organization_id=org.id, name="example/example", ) with self.tasks(): with pytest.raises(DeleteAborted): delete_repository(object_id=repo.id) repo = Repository.objects.get(id=repo.id) assert repo.status == ObjectStatus.VISIBLE def test_deletes(self): org = self.create_organization() repo = Repository.objects.create( status=ObjectStatus.PENDING_DELETION, organization_id=org.id, provider="dummy", name="example/example", ) repo2 = Repository.objects.create( status=ObjectStatus.PENDING_DELETION, organization_id=org.id, provider="dummy", name="example/example2", ) commit = Commit.objects.create( repository_id=repo.id, organization_id=org.id, key="1234abcd" ) commit2 = Commit.objects.create( repository_id=repo2.id, organization_id=org.id, key="1234abcd" ) with self.tasks(): delete_repository(object_id=repo.id) assert not Repository.objects.filter(id=repo.id).exists() assert not Commit.objects.filter(id=commit.id).exists() assert Commit.objects.filter(id=commit2.id).exists()
36.875776
100
0.666161
from __future__ import absolute_import from datetime import datetime, timedelta from mock import patch from uuid import uuid4 import pytest from sentry.constants import ObjectStatus from sentry.exceptions import DeleteAborted from sentry.models import ( ApiApplication, ApiApplicationStatus, ApiGrant, ApiToken, Commit, CommitAuthor, Environment, EnvironmentProject, Event, Group, GroupAssignee, GroupHash, GroupMeta, GroupRedirect, GroupResolution, GroupStatus, Organization, OrganizationStatus, Project, ProjectStatus, Release, ReleaseCommit, ReleaseEnvironment, Repository, Team, TeamStatus, ) from sentry.plugins.providers.dummy.repository import DummyRepositoryProvider from sentry.tasks.deletion import ( delete_api_application, delete_groups, delete_organization, delete_project, delete_repository, delete_team, generic_delete, revoke_api_tokens, ) from sentry.testutils import TestCase from sentry.testutils.helpers.datetime import iso_format, before_now class DeleteOrganizationTest(TestCase): def test_simple(self): org = self.create_organization(name="test", status=OrganizationStatus.PENDING_DELETION) user = self.create_user() self.create_team(organization=org, name="test1") self.create_team(organization=org, name="test2") release = Release.objects.create(version="a" * 32, organization_id=org.id) repo = Repository.objects.create(organization_id=org.id, name=org.name, provider="dummy") commit_author = CommitAuthor.objects.create( organization_id=org.id, name="foo", email="foo@example.com" ) commit = Commit.objects.create( repository_id=repo.id, organization_id=org.id, author=commit_author, key="a" * 40 ) ReleaseCommit.objects.create( organization_id=org.id, release=release, commit=commit, order=0 ) env = Environment.objects.create(organization_id=org.id, project_id=4, name="foo") release_env = ReleaseEnvironment.objects.create( organization_id=org.id, project_id=4, release_id=release.id, environment_id=env.id ) with self.tasks(): with patch.object(DummyRepositoryProvider, "delete_repository") as mock_delete_repo: delete_organization(object_id=org.id, actor_id=user.id) assert mock_delete_repo.call_count == 1 assert not Organization.objects.filter(id=org.id).exists() assert not Environment.objects.filter(id=env.id).exists() assert not ReleaseEnvironment.objects.filter(id=release_env.id).exists() assert not Repository.objects.filter(id=repo.id).exists() assert not ReleaseCommit.objects.filter(organization_id=org.id).exists() assert not Release.objects.filter(organization_id=org.id).exists() assert not CommitAuthor.objects.filter(id=commit_author.id).exists() assert not Commit.objects.filter(id=commit.id).exists() def test_cancels_without_pending_status(self): org = self.create_organization(name="test", status=OrganizationStatus.VISIBLE) self.create_team(organization=org, name="test1") self.create_team(organization=org, name="test2") with self.assertRaises(DeleteAborted): with self.tasks(): delete_organization(object_id=org.id) assert Organization.objects.filter(id=org.id).exists() class DeleteTeamTest(TestCase): def test_simple(self): team = self.create_team(name="test", status=TeamStatus.PENDING_DELETION) self.create_project(teams=[team], name="test1") self.create_project(teams=[team], name="test2") with self.tasks(): delete_team(object_id=team.id) assert not Team.objects.filter(id=team.id).exists() def test_cancels_without_pending_status(self): team = self.create_team(name="test", status=TeamStatus.VISIBLE) self.create_project(teams=[team], name="test1") self.create_project(teams=[team], name="test2") with self.assertRaises(DeleteAborted): with self.tasks(): delete_team(object_id=team.id) assert Team.objects.filter(id=team.id).exists() class DeleteProjectTest(TestCase): def test_simple(self): project = self.create_project(name="test", status=ProjectStatus.PENDING_DELETION) group = self.create_group(project=project) GroupAssignee.objects.create(group=group, project=project, user=self.user) GroupMeta.objects.create(group=group, key="foo", value="bar") release = Release.objects.create(version="a" * 32, organization_id=project.organization_id) release.add_project(project) GroupResolution.objects.create(group=group, release=release) env = Environment.objects.create( organization_id=project.organization_id, project_id=project.id, name="foo" ) env.add_project(project) repo = Repository.objects.create(organization_id=project.organization_id, name=project.name) commit_author = CommitAuthor.objects.create( organization_id=project.organization_id, name="foo", email="foo@example.com" ) commit = Commit.objects.create( repository_id=repo.id, organization_id=project.organization_id, author=commit_author, key="a" * 40, ) ReleaseCommit.objects.create( organization_id=project.organization_id, project_id=project.id, release=release, commit=commit, order=0, ) with self.tasks(): delete_project(object_id=project.id) assert not Project.objects.filter(id=project.id).exists() assert not EnvironmentProject.objects.filter( project_id=project.id, environment_id=env.id ).exists() assert Environment.objects.filter(id=env.id).exists() assert Release.objects.filter(id=release.id).exists() assert ReleaseCommit.objects.filter(release_id=release.id).exists() assert Commit.objects.filter(id=commit.id).exists() def test_cancels_without_pending_status(self): project = self.create_project(name="test", status=ProjectStatus.VISIBLE) with self.assertRaises(DeleteAborted): with self.tasks(): delete_project(object_id=project.id) assert Project.objects.filter(id=project.id).exists() class DeleteGroupTest(TestCase): def test_simple(self): event_id = "a" * 32 project = self.create_project() event = self.store_event( data={"event_id": event_id, "timestamp": iso_format(before_now(minutes=1))}, project_id=project.id, ) group = event.group group.update(status=GroupStatus.PENDING_DELETION) GroupAssignee.objects.create(group=group, project=project, user=self.user) GroupHash.objects.create(project=project, group=group, hash=uuid4().hex) GroupMeta.objects.create(group=group, key="foo", value="bar") GroupRedirect.objects.create(group_id=group.id, previous_group_id=1) with self.tasks(): delete_groups(object_ids=[group.id]) assert not Event.objects.filter(id=event.id).exists() assert not GroupRedirect.objects.filter(group_id=group.id).exists() assert not GroupHash.objects.filter(group_id=group.id).exists() assert not Group.objects.filter(id=group.id).exists() class DeleteApplicationTest(TestCase): def test_simple(self): app = ApiApplication.objects.create( owner=self.user, status=ApiApplicationStatus.pending_deletion ) ApiToken.objects.create(application=app, user=self.user, scopes=0) ApiGrant.objects.create( application=app, user=self.user, scopes=0, redirect_uri="http://example.com" ) with self.tasks(): delete_api_application(object_id=app.id) assert not ApiApplication.objects.filter(id=app.id).exists() assert not ApiGrant.objects.filter(application=app).exists() assert not ApiToken.objects.filter(application=app).exists() class RevokeApiTokensTest(TestCase): def test_basic(self): app = ApiApplication.objects.create(owner=self.user) token1 = ApiToken.objects.create( application=app, user=self.create_user("bar@example.com"), scopes=0 ) token2 = ApiToken.objects.create( application=app, user=self.create_user("foo@example.com"), scopes=0 ) with self.tasks(): revoke_api_tokens(object_id=app.id) assert not ApiToken.objects.filter(id=token1.id).exists() assert not ApiToken.objects.filter(id=token2.id).exists() def test_with_timestamp(self): cutoff = datetime(2017, 1, 1) app = ApiApplication.objects.create(owner=self.user) token1 = ApiToken.objects.create( application=app, user=self.create_user("bar@example.com"), scopes=0, date_added=cutoff ) token2 = ApiToken.objects.create( application=app, user=self.create_user("foo@example.com"), scopes=0, date_added=cutoff + timedelta(days=1), ) with self.tasks(): revoke_api_tokens(object_id=app.id, timestamp=cutoff) assert not ApiToken.objects.filter(id=token1.id).exists() assert ApiToken.objects.filter(id=token2.id).exists() class GenericDeleteTest(TestCase): def test_does_not_delete_visible(self): project = self.create_project(status=ObjectStatus.VISIBLE) with self.tasks(): with pytest.raises(DeleteAborted): generic_delete("sentry", "project", object_id=project.id) project = Project.objects.get(id=project.id) assert project.status == ObjectStatus.VISIBLE def test_deletes(self): project = self.create_project(status=ObjectStatus.PENDING_DELETION) with self.tasks(): generic_delete("sentry", "project", object_id=project.id) assert not Project.objects.filter(id=project.id).exists() class DeleteRepoTest(TestCase): def test_does_not_delete_visible(self): org = self.create_organization() repo = Repository.objects.create( status=ObjectStatus.VISIBLE, provider="dummy", organization_id=org.id, name="example/example", ) with self.tasks(): with pytest.raises(DeleteAborted): delete_repository(object_id=repo.id) repo = Repository.objects.get(id=repo.id) assert repo.status == ObjectStatus.VISIBLE def test_deletes(self): org = self.create_organization() repo = Repository.objects.create( status=ObjectStatus.PENDING_DELETION, organization_id=org.id, provider="dummy", name="example/example", ) repo2 = Repository.objects.create( status=ObjectStatus.PENDING_DELETION, organization_id=org.id, provider="dummy", name="example/example2", ) commit = Commit.objects.create( repository_id=repo.id, organization_id=org.id, key="1234abcd" ) commit2 = Commit.objects.create( repository_id=repo2.id, organization_id=org.id, key="1234abcd" ) with self.tasks(): delete_repository(object_id=repo.id) assert not Repository.objects.filter(id=repo.id).exists() assert not Commit.objects.filter(id=commit.id).exists() assert Commit.objects.filter(id=commit2.id).exists()
true
true
1c37161fbb98dd1f93525f52f546809b3ad06b4d
438
py
Python
test/test_spi_opi.py
osterwood/litex
db20cb172dc982c5879aa8080ec7aa18de181cc5
[ "ADSL" ]
1,501
2016-04-19T18:16:21.000Z
2022-03-31T17:46:31.000Z
test/test_spi_opi.py
osterwood/litex
db20cb172dc982c5879aa8080ec7aa18de181cc5
[ "ADSL" ]
1,135
2016-04-19T05:49:14.000Z
2022-03-31T15:21:19.000Z
test/test_spi_opi.py
osterwood/litex
db20cb172dc982c5879aa8080ec7aa18de181cc5
[ "ADSL" ]
357
2016-04-19T05:00:24.000Z
2022-03-31T11:28:32.000Z
# # This file is part of LiteX. # # Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause import unittest from migen import * from litex.soc.cores.spi_opi import S7SPIOPI class TestI2S(unittest.TestCase): def test_s7spiopi_syntax(self): spi_opi_pads = Record([("dqs", 1), ("dq", 8), ("sclk", 1), ("cs_n", 1), ("ecs_n", 1)]) spi_opi = S7SPIOPI(pads=spi_opi_pads)
23.052632
94
0.678082
import unittest from migen import * from litex.soc.cores.spi_opi import S7SPIOPI class TestI2S(unittest.TestCase): def test_s7spiopi_syntax(self): spi_opi_pads = Record([("dqs", 1), ("dq", 8), ("sclk", 1), ("cs_n", 1), ("ecs_n", 1)]) spi_opi = S7SPIOPI(pads=spi_opi_pads)
true
true
1c37162a832c23c29e1286d1ec49eadb1b07d246
1,260
py
Python
28_OpenCV_FaceImageExtraction/imgGenerate.py
ManMohan291/PyProgram
edcaa927bd70676bd14355acad7262ae2d32b8e5
[ "MIT" ]
2
2018-09-07T17:44:54.000Z
2018-09-07T17:44:57.000Z
28_OpenCV_FaceImageExtraction/imgGenerate.py
ManMohan291/PyProgram
edcaa927bd70676bd14355acad7262ae2d32b8e5
[ "MIT" ]
null
null
null
28_OpenCV_FaceImageExtraction/imgGenerate.py
ManMohan291/PyProgram
edcaa927bd70676bd14355acad7262ae2d32b8e5
[ "MIT" ]
null
null
null
import numpy as np import cv2 as cv2 import sys #im = cv2.imread("ManMohan\frame1.jpg") #cv2.imshow('Videoc', im) #cascPath = sys.argv[1] faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') video_capture = cv2.VideoCapture(0) count = 0 while True: # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(50, 50) #maxSize=(150,150) #, #flags=cv2.CASCADE_SCALE_IMAGE ) # Draw a rectangle around the faces for (x, y, w, h) in faces: count = count+1 x0,y0=int(x),int(y) x1,y1=int(x+w),int(y+h) roi=frame[y0:y1,x0:x1]#crop cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) cropped=cv2.resize(roi, dsize=(150,150)) cv2.imshow('Videoc', cropped) cv2.imwrite("output/frame%d.jpg" % count, cropped) # Display the resulting frame cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything is done, release the capture video_capture.release() cv2.destroyAllWindows()
24.230769
74
0.607143
import numpy as np import cv2 as cv2 import sys faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') video_capture = cv2.VideoCapture(0) count = 0 while True: ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(50, 50) ) for (x, y, w, h) in faces: count = count+1 x0,y0=int(x),int(y) x1,y1=int(x+w),int(y+h) roi=frame[y0:y1,x0:x1] cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) cropped=cv2.resize(roi, dsize=(150,150)) cv2.imshow('Videoc', cropped) cv2.imwrite("output/frame%d.jpg" % count, cropped) cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
true
true
1c3716a6997641010abbad3897b4e9154b9d5e1d
220
py
Python
students/K33401/practical_works/Kasatkin_Daniil/simple_django_web_project/simple_django_web_project/djangoApp/admin.py
aglaya-pill/ITMO_ICT_WebDevelopment_2021-2022
a63691317a72fb9b29ae537bc3d7766661458c22
[ "MIT" ]
null
null
null
students/K33401/practical_works/Kasatkin_Daniil/simple_django_web_project/simple_django_web_project/djangoApp/admin.py
aglaya-pill/ITMO_ICT_WebDevelopment_2021-2022
a63691317a72fb9b29ae537bc3d7766661458c22
[ "MIT" ]
null
null
null
students/K33401/practical_works/Kasatkin_Daniil/simple_django_web_project/simple_django_web_project/djangoApp/admin.py
aglaya-pill/ITMO_ICT_WebDevelopment_2021-2022
a63691317a72fb9b29ae537bc3d7766661458c22
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import User, Car, DriversLicense, Ownership admin.site.register(User) admin.site.register(Car) admin.site.register(Ownership) admin.site.register(DriversLicense)
22
57
0.781818
from django.contrib import admin from .models import User, Car, DriversLicense, Ownership admin.site.register(User) admin.site.register(Car) admin.site.register(Ownership) admin.site.register(DriversLicense)
true
true
1c371750f041b8a0f7d3ca39767fd031f8a351d0
3,892
py
Python
google/ads/googleads/v9/services/services/topic_constant_service/transports/base.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
google/ads/googleads/v9/services/services/topic_constant_service/transports/base.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
google/ads/googleads/v9/services/services/topic_constant_service/transports/base.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import abc import typing import pkg_resources import google.auth # type: ignore from google.api_core import gapic_v1 from google.auth import credentials as ga_credentials # type: ignore from google.ads.googleads.v9.resources.types import topic_constant from google.ads.googleads.v9.services.types import topic_constant_service try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-ads",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class TopicConstantServiceTransport(metaclass=abc.ABCMeta): """Abstract transport class for TopicConstantService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/adwords",) def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: host += ":443" self._host = host # If no credentials are provided, then determine the appropriate # defaults. if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # Save the credentials. self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. self._prep_wrapped_messages(client_info) def _prep_wrapped_messages(self, client_info): # Precomputed wrapped methods self._wrapped_methods = { self.get_topic_constant: gapic_v1.method.wrap_method( self.get_topic_constant, default_timeout=None, client_info=client_info, ), } def close(self): """Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property def get_topic_constant( self, ) -> typing.Callable[ [topic_constant_service.GetTopicConstantRequest], topic_constant.TopicConstant, ]: raise NotImplementedError __all__ = ("TopicConstantServiceTransport",)
35.706422
78
0.670606
import abc import typing import pkg_resources import google.auth from google.api_core import gapic_v1 from google.auth import credentials as ga_credentials from google.ads.googleads.v9.resources.types import topic_constant from google.ads.googleads.v9.services.types import topic_constant_service try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-ads",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class TopicConstantServiceTransport(metaclass=abc.ABCMeta): AUTH_SCOPES = ("https://www.googleapis.com/auth/adwords",) def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: if ":" not in host: host += ":443" self._host = host if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) self._credentials = credentials self._prep_wrapped_messages(client_info) def _prep_wrapped_messages(self, client_info): self._wrapped_methods = { self.get_topic_constant: gapic_v1.method.wrap_method( self.get_topic_constant, default_timeout=None, client_info=client_info, ), } def close(self): raise NotImplementedError() @property def get_topic_constant( self, ) -> typing.Callable[ [topic_constant_service.GetTopicConstantRequest], topic_constant.TopicConstant, ]: raise NotImplementedError __all__ = ("TopicConstantServiceTransport",)
true
true
1c3719a95a9ee64094fcb1c02f19bb4e976313b9
4,678
py
Python
src/natcap/invest/ui/recreation.py
testacc-art/invest
8f34712f89b8245ed7a4593b833d7d7a7d5e0c6e
[ "BSD-3-Clause" ]
null
null
null
src/natcap/invest/ui/recreation.py
testacc-art/invest
8f34712f89b8245ed7a4593b833d7d7a7d5e0c6e
[ "BSD-3-Clause" ]
1
2021-12-08T19:49:56.000Z
2021-12-11T01:59:55.000Z
src/natcap/invest/ui/recreation.py
emlys/invest
5b0391fd456df5a6afd2fdfbaed542a090f58f17
[ "BSD-3-Clause" ]
null
null
null
# coding=UTF-8 from natcap.invest.ui import model, inputs from natcap.invest.recreation import recmodel_client class Recreation(model.InVESTModel): def __init__(self): model.InVESTModel.__init__( self, label='Recreation Model', target=recmodel_client.execute, validator=recmodel_client.validate, localdoc='recreation.html') self.internet_warning = inputs.Label( text=( "Note, this computer must have an Internet connection " "in order to run this model.")) self.aoi_path = inputs.File( args_key='aoi_path', helptext=( "An OGR-supported vector file representing the area " "of interest where the model will run the analysis."), label='Area of Interest (Vector)', validator=self.validator) self.add_input(self.aoi_path) self.start_year = inputs.Text( args_key='start_year', helptext='Year to start PUD calculations, date starts on Jan 1st.', label='Start Year (inclusive, must be >= 2005)', validator=self.validator) self.add_input(self.start_year) self.end_year = inputs.Text( args_key='end_year', helptext=( 'Year to end PUD calculations, date ends and includes ' 'Dec 31st.'), label='End Year (inclusive, must be <= 2017)', validator=self.validator) self.add_input(self.end_year) self.regression_container = inputs.Container( args_key='compute_regression', expandable=True, expanded=True, label='Compute Regression') self.add_input(self.regression_container) self.predictor_table_path = inputs.File( args_key='predictor_table_path', helptext=( "A table that maps predictor IDs to files and their " "types with required headers of 'id', 'path', and " "'type'. The file paths can be absolute, or relative " "to the table."), label='Predictor Table', validator=self.validator) self.regression_container.add_input(self.predictor_table_path) self.scenario_predictor_table_path = inputs.File( args_key='scenario_predictor_table_path', helptext=( "A table that maps predictor IDs to files and their " "types with required headers of 'id', 'path', and " "'type'. The file paths can be absolute, or relative " "to the table."), label='Scenario Predictor Table (optional)', validator=self.validator) self.regression_container.add_input(self.scenario_predictor_table_path) self.grid_container = inputs.Container( args_key='grid_aoi', expandable=True, expanded=True, label='Grid the AOI') self.add_input(self.grid_container) self.grid_type = inputs.Dropdown( args_key='grid_type', label='Grid Type', options=['square', 'hexagon']) self.grid_container.add_input(self.grid_type) self.cell_size = inputs.Text( args_key='cell_size', helptext=( "The size of the grid units measured in the " "projection units of the AOI. For example, UTM " "projections use meters."), label='Cell Size', validator=self.validator) self.grid_container.add_input(self.cell_size) def assemble_args(self): args = { self.workspace.args_key: self.workspace.value(), self.suffix.args_key: self.suffix.value(), self.aoi_path.args_key: self.aoi_path.value(), self.start_year.args_key: self.start_year.value(), self.end_year.args_key: self.end_year.value(), self.regression_container.args_key: self.regression_container.value(), self.grid_container.args_key: self.grid_container.value(), } if self.regression_container.value(): args[self.predictor_table_path.args_key] = ( self.predictor_table_path.value()) args[self.scenario_predictor_table_path.args_key] = ( self.scenario_predictor_table_path.value()) if self.grid_container.value(): args[self.grid_type.args_key] = self.grid_type.value() args[self.cell_size.args_key] = self.cell_size.value() return args
41.767857
79
0.592347
from natcap.invest.ui import model, inputs from natcap.invest.recreation import recmodel_client class Recreation(model.InVESTModel): def __init__(self): model.InVESTModel.__init__( self, label='Recreation Model', target=recmodel_client.execute, validator=recmodel_client.validate, localdoc='recreation.html') self.internet_warning = inputs.Label( text=( "Note, this computer must have an Internet connection " "in order to run this model.")) self.aoi_path = inputs.File( args_key='aoi_path', helptext=( "An OGR-supported vector file representing the area " "of interest where the model will run the analysis."), label='Area of Interest (Vector)', validator=self.validator) self.add_input(self.aoi_path) self.start_year = inputs.Text( args_key='start_year', helptext='Year to start PUD calculations, date starts on Jan 1st.', label='Start Year (inclusive, must be >= 2005)', validator=self.validator) self.add_input(self.start_year) self.end_year = inputs.Text( args_key='end_year', helptext=( 'Year to end PUD calculations, date ends and includes ' 'Dec 31st.'), label='End Year (inclusive, must be <= 2017)', validator=self.validator) self.add_input(self.end_year) self.regression_container = inputs.Container( args_key='compute_regression', expandable=True, expanded=True, label='Compute Regression') self.add_input(self.regression_container) self.predictor_table_path = inputs.File( args_key='predictor_table_path', helptext=( "A table that maps predictor IDs to files and their " "types with required headers of 'id', 'path', and " "'type'. The file paths can be absolute, or relative " "to the table."), label='Predictor Table', validator=self.validator) self.regression_container.add_input(self.predictor_table_path) self.scenario_predictor_table_path = inputs.File( args_key='scenario_predictor_table_path', helptext=( "A table that maps predictor IDs to files and their " "types with required headers of 'id', 'path', and " "'type'. The file paths can be absolute, or relative " "to the table."), label='Scenario Predictor Table (optional)', validator=self.validator) self.regression_container.add_input(self.scenario_predictor_table_path) self.grid_container = inputs.Container( args_key='grid_aoi', expandable=True, expanded=True, label='Grid the AOI') self.add_input(self.grid_container) self.grid_type = inputs.Dropdown( args_key='grid_type', label='Grid Type', options=['square', 'hexagon']) self.grid_container.add_input(self.grid_type) self.cell_size = inputs.Text( args_key='cell_size', helptext=( "The size of the grid units measured in the " "projection units of the AOI. For example, UTM " "projections use meters."), label='Cell Size', validator=self.validator) self.grid_container.add_input(self.cell_size) def assemble_args(self): args = { self.workspace.args_key: self.workspace.value(), self.suffix.args_key: self.suffix.value(), self.aoi_path.args_key: self.aoi_path.value(), self.start_year.args_key: self.start_year.value(), self.end_year.args_key: self.end_year.value(), self.regression_container.args_key: self.regression_container.value(), self.grid_container.args_key: self.grid_container.value(), } if self.regression_container.value(): args[self.predictor_table_path.args_key] = ( self.predictor_table_path.value()) args[self.scenario_predictor_table_path.args_key] = ( self.scenario_predictor_table_path.value()) if self.grid_container.value(): args[self.grid_type.args_key] = self.grid_type.value() args[self.cell_size.args_key] = self.cell_size.value() return args
true
true
1c3719c29c4c320accf134850e237b449aec24fa
419
py
Python
server/test_server.py
doas3140/face-pipeline
e1d8affb945beb0d257e75d865dfdb1ee9cda75e
[ "Apache-2.0" ]
null
null
null
server/test_server.py
doas3140/face-pipeline
e1d8affb945beb0d257e75d865dfdb1ee9cda75e
[ "Apache-2.0" ]
2
2021-09-28T00:52:38.000Z
2022-02-26T06:39:29.000Z
server/test_server.py
doas3140/face-pipeline
e1d8affb945beb0d257e75d865dfdb1ee9cda75e
[ "Apache-2.0" ]
null
null
null
from __future__ import print_function import requests import json import cv2 test_url = 'http://localhost:5000/api/test' img = cv2.imread('newfam.jpg') print(img) _, img_encoded = cv2.imencode('.jpg', img) response = requests.post(test_url, files={'image': img_encoded.tostring()}) res = json.loads(response.text) if 'message' in res: print('Worked!', res['message']) else: raise Exception('Something went wrong!')
24.647059
75
0.73747
from __future__ import print_function import requests import json import cv2 test_url = 'http://localhost:5000/api/test' img = cv2.imread('newfam.jpg') print(img) _, img_encoded = cv2.imencode('.jpg', img) response = requests.post(test_url, files={'image': img_encoded.tostring()}) res = json.loads(response.text) if 'message' in res: print('Worked!', res['message']) else: raise Exception('Something went wrong!')
true
true
1c371a60fb4a30220579e772c0528de6944a2052
421
py
Python
config.py
higuseonhye/visual-comet
df8b8f8ac27f41c6340985b09967b61173f3a847
[ "MIT" ]
1
2020-09-02T14:30:02.000Z
2020-09-02T14:30:02.000Z
config.py
higuseonhye/visual-comet
df8b8f8ac27f41c6340985b09967b61173f3a847
[ "MIT" ]
null
null
null
config.py
higuseonhye/visual-comet
df8b8f8ac27f41c6340985b09967b61173f3a847
[ "MIT" ]
null
null
null
import os USE_IMAGENET_PRETRAINED = True # otherwise use detectron, but that doesnt seem to work?!? # Change these to match where your annotations and images are VCR_IMAGES_DIR = '/home/jamesp/data/vcr/vcr1images'# os.environ['VCR_PARENT_DIR'] if not os.path.exists(VCR_IMAGES_DIR): raise ValueError("Update config.py with where you saved VCR images to.") VCR_FEATURES_DIR = '/home/jamesp/data/visualcomet/features'
46.777778
89
0.783848
import os USE_IMAGENET_PRETRAINED = True VCR_IMAGES_DIR = '/home/jamesp/data/vcr/vcr1images' if not os.path.exists(VCR_IMAGES_DIR): raise ValueError("Update config.py with where you saved VCR images to.") VCR_FEATURES_DIR = '/home/jamesp/data/visualcomet/features'
true
true
1c371a82c00eb77226772d507aab6da3d5d6dfcb
9,798
py
Python
optimade/filtertransformers/elasticsearch.py
ltalirz/optimade-python-tools
ddf11f51ba34f8dea6b46a1f37a7574e902521dd
[ "MIT" ]
1
2020-01-20T15:24:23.000Z
2020-01-20T15:24:23.000Z
optimade/filtertransformers/elasticsearch.py
blokhin/optimade-python-tools
be7816b5614a28e9870502e26de6c3e7eca85424
[ "MIT" ]
null
null
null
optimade/filtertransformers/elasticsearch.py
blokhin/optimade-python-tools
be7816b5614a28e9870502e26de6c3e7eca85424
[ "MIT" ]
null
null
null
import lark from elasticsearch_dsl import Q, Text, Keyword, Integer, Field from optimade.models import CHEMICAL_SYMBOLS, ATOMIC_NUMBERS _cmp_operators = {">": "gt", ">=": "gte", "<": "lt", "<=": "lte"} _rev_cmp_operators = {">": "<", ">=": "<=", "<": ">", "<=": "=>"} _has_operators = {"ALL": "must", "ANY": "should"} _length_quantities = { "elements": "nelements", "elements_rations": "nelements", "dimension_types": "dimension_types", } class Quantity: """ Class to provide information about available quantities to the transformer. The elasticsearch transformer will :class:`Quantity`s to (a) do some semantic checks, (b) map quantities to the underlying elastic index. Attributes: name: The name of the quantity as used in the filter expressions. es_field: The name of the field for this quanity in elastic search, will be ``name`` by default. elastic_mapping_type: A decendent of an elasticsearch_dsl Field that denotes which mapping was used in the elastic search index. length_quantity: Elasticsearch does not support length of arrays, but we can map fields with array to other fields with ints about the array length. The LENGTH operator will only be supported for quantities with this attribute. has_only_quantity: Elasticsearch does not support exclusive search on arrays, like a list of chemical elements. But, we can order all elements by atomic number and use a keyword field with all elements to perform this search. This only works for elements (i.e. labels in ``CHEMICAL_SYMBOLS``) and quantities with this attribute. nested_quantity: To support optimade's 'zipped tuple' feature (e.g. 'elements:elements_ratios HAS "H":>0.33), we use elasticsearch nested objects and nested queries. This quantity will provide the field for the nested object that contains the quantity (and others). The zipped tuples will only work for quantities that share the same nested object quantity. """ def __init__( self, name, es_field: str = None, elastic_mapping_type: Field = None, length_quantity: "Quantity" = None, has_only_quantity: "Quantity" = None, nested_quantity: "Quantity" = None, ): self.name = name self.es_field = es_field if es_field is not None else name self.elastic_mapping_type = ( Keyword if elastic_mapping_type is None else elastic_mapping_type ) self.length_quantity = length_quantity self.has_only_quantity = has_only_quantity self.nested_quantity = nested_quantity def __repr__(self): return self.name class Transformer(lark.Transformer): """ Transformer that transforms ``v0.10.0`` grammer parse trees into queries. Uses elasticsearch_dsl and will produce a :class:`Q` instance. Arguments: quantities: A list of :class:`Quantity`s that describe how optimade (and other) quantities are mapped to the elasticsearch index. """ def __init__(self, quantities): self.index_mapping = {quantity.name: quantity for quantity in quantities} def _field(self, quantity, nested=None): if nested is not None: return "%s.%s" % (nested.es_field, quantity.name) return quantity.es_field def _order_terms(self, l, o, r): if isinstance(l, Quantity): if isinstance(r, Quantity): raise Exception( "Cannot compare two quantities: %s, %s" % (l.name, r.name) ) return l, o, r else: if isinstance(r, Quantity): o = _rev_cmp_operators.get(o, o) return r, o, l raise Exception("Cannot compare two values: %s, %s" % (str(l), str(l))) def _query(self, quantity, o, value, nested=None): field = self._field(quantity, nested=nested) if o in _cmp_operators: return Q("range", **{field: {_cmp_operators[o]: value}}) if quantity.elastic_mapping_type == Text: query_type = "match" elif quantity.elastic_mapping_type in [Keyword, Integer]: query_type = "term" else: raise NotImplementedError("Quantity has unsupported ES field type") if o in ["=", ""]: return Q(query_type, **{field: value}) if o == "!=": return ~Q( query_type, **{field: value} ) # pylint: disable=invalid-unary-operand-type raise Exception("Unknown operator %s" % o) def _has_query(self, quantities, predicates): if len(quantities) != len(predicates): raise Exception( "Tuple length does not match: %s <o> %s " % (":".join(quantities), ":".join(predicates)) ) if len(quantities) == 1: o, value = predicates[0] return self._query(quantities[0], o, value) nested_quantity = quantities[0].nested_quantity if nested_quantity is None or any( q.nested_quantity != nested_quantity for q in quantities ): raise Exception( "Expression with tuples are only supported for %s" % ", ".join(quantities) ) queries = [ self._query(field, o, value, nested=nested_quantity) for field, (o, value) in zip(quantities, predicates) ] return Q( "nested", path=self._field(nested_quantity), query=dict(bool=dict(must=queries)), ) def _wildcard_query(self, quantity, wildcard): return Q("wildcard", **{self._field(quantity): wildcard}) def __default__(self, tree, children, *args, **kwargs): """ Default behavior for rules that only replace one symbol with another """ return children[0] def and_expr(self, args): if len(args) == 1: return args[0] l, r = args return l & r def or_expr(self, args): if len(args) == 1: return args[0] l, r = args return l | r def not_expr(self, args): (o,) = args return ~o def cmp_op(self, args): l, o, r = args field, o, value = self._order_terms(l, o, r) return self._query(field, o, value) def has_op(self, args): quantities, predicates = args return self._has_query(quantities, predicates) def has_list_op(self, args): quantities, o, predicates_list = args queries = [ self._has_query(quantities, predicates) for predicates in predicates_list ] if o in _has_operators: return Q("bool", **{_has_operators[o]: queries}) raise NotImplementedError def has_only_op(self, args): quantity, lst = args if quantity.has_only_quantity is None: raise Exception("HAS ONLY is not supported by %s" % quantity.name) def values(): for predicates in lst: if len(predicates) != 1: raise Exception("Tuples not supported in HAS ONLY") op, value = predicates[0] if op != "": raise Exception("Predicated not supported in HAS ONLY") if not isinstance(value, str): raise Exception("Only strings supported in HAS ONLY") yield value try: order_numbers = list([ATOMIC_NUMBERS[element] for element in values()]) order_numbers.sort() value = "".join([CHEMICAL_SYMBOLS[number] for number in order_numbers]) except KeyError: raise Exception("HAS ONLY is only supported for chemical symbols") return Q("term", **{quantity.has_only_quantity.name: value}) def length(self, args): (quantity,) = args if quantity.length_quantity is None: raise Exception("LENGTH is not supported for %s" % quantity.name) return quantity.length_quantity def known_op(self, args): quantity, qualifier = args query = Q("exists", field=self._field(quantity)) if qualifier == "KNOWN": return query elif qualifier == "UNKNOWN": return ~query # pylint: disable=invalid-unary-operand-type raise NotImplementedError def contains_op(self, args): quantity, value = args return self._wildcard_query(quantity, "*%s*" % value) def starts_op(self, args): quantity, value = args return self._wildcard_query(quantity, "%s*" % value) def ends_op(self, args): quantity, value = args return self._wildcard_query(quantity, "*%s" % value) def list(self, args): return list(args) def quantity_tuple(self, args): return list(args) def predicate_tuple(self, args): return list(args) def predicate(self, args): if len(args) == 1: return "", args[0] else: return args[0], args[1] def quantity(self, args): quantity_name = args[0] if quantity_name not in self.index_mapping: raise Exception("%s is not a searchable quantity" % quantity_name) quantity = self.index_mapping.get(quantity_name, None) if quantity is None: quantity = Quantity(name=quantity_name) return quantity def int_literal(self, args): return int(args[0]) def float_literal(self, args): return float(args[0]) def string_literal(self, args): return args[0].strip('"')
34.258741
90
0.599408
import lark from elasticsearch_dsl import Q, Text, Keyword, Integer, Field from optimade.models import CHEMICAL_SYMBOLS, ATOMIC_NUMBERS _cmp_operators = {">": "gt", ">=": "gte", "<": "lt", "<=": "lte"} _rev_cmp_operators = {">": "<", ">=": "<=", "<": ">", "<=": "=>"} _has_operators = {"ALL": "must", "ANY": "should"} _length_quantities = { "elements": "nelements", "elements_rations": "nelements", "dimension_types": "dimension_types", } class Quantity: def __init__( self, name, es_field: str = None, elastic_mapping_type: Field = None, length_quantity: "Quantity" = None, has_only_quantity: "Quantity" = None, nested_quantity: "Quantity" = None, ): self.name = name self.es_field = es_field if es_field is not None else name self.elastic_mapping_type = ( Keyword if elastic_mapping_type is None else elastic_mapping_type ) self.length_quantity = length_quantity self.has_only_quantity = has_only_quantity self.nested_quantity = nested_quantity def __repr__(self): return self.name class Transformer(lark.Transformer): def __init__(self, quantities): self.index_mapping = {quantity.name: quantity for quantity in quantities} def _field(self, quantity, nested=None): if nested is not None: return "%s.%s" % (nested.es_field, quantity.name) return quantity.es_field def _order_terms(self, l, o, r): if isinstance(l, Quantity): if isinstance(r, Quantity): raise Exception( "Cannot compare two quantities: %s, %s" % (l.name, r.name) ) return l, o, r else: if isinstance(r, Quantity): o = _rev_cmp_operators.get(o, o) return r, o, l raise Exception("Cannot compare two values: %s, %s" % (str(l), str(l))) def _query(self, quantity, o, value, nested=None): field = self._field(quantity, nested=nested) if o in _cmp_operators: return Q("range", **{field: {_cmp_operators[o]: value}}) if quantity.elastic_mapping_type == Text: query_type = "match" elif quantity.elastic_mapping_type in [Keyword, Integer]: query_type = "term" else: raise NotImplementedError("Quantity has unsupported ES field type") if o in ["=", ""]: return Q(query_type, **{field: value}) if o == "!=": return ~Q( query_type, **{field: value} ) raise Exception("Unknown operator %s" % o) def _has_query(self, quantities, predicates): if len(quantities) != len(predicates): raise Exception( "Tuple length does not match: %s <o> %s " % (":".join(quantities), ":".join(predicates)) ) if len(quantities) == 1: o, value = predicates[0] return self._query(quantities[0], o, value) nested_quantity = quantities[0].nested_quantity if nested_quantity is None or any( q.nested_quantity != nested_quantity for q in quantities ): raise Exception( "Expression with tuples are only supported for %s" % ", ".join(quantities) ) queries = [ self._query(field, o, value, nested=nested_quantity) for field, (o, value) in zip(quantities, predicates) ] return Q( "nested", path=self._field(nested_quantity), query=dict(bool=dict(must=queries)), ) def _wildcard_query(self, quantity, wildcard): return Q("wildcard", **{self._field(quantity): wildcard}) def __default__(self, tree, children, *args, **kwargs): return children[0] def and_expr(self, args): if len(args) == 1: return args[0] l, r = args return l & r def or_expr(self, args): if len(args) == 1: return args[0] l, r = args return l | r def not_expr(self, args): (o,) = args return ~o def cmp_op(self, args): l, o, r = args field, o, value = self._order_terms(l, o, r) return self._query(field, o, value) def has_op(self, args): quantities, predicates = args return self._has_query(quantities, predicates) def has_list_op(self, args): quantities, o, predicates_list = args queries = [ self._has_query(quantities, predicates) for predicates in predicates_list ] if o in _has_operators: return Q("bool", **{_has_operators[o]: queries}) raise NotImplementedError def has_only_op(self, args): quantity, lst = args if quantity.has_only_quantity is None: raise Exception("HAS ONLY is not supported by %s" % quantity.name) def values(): for predicates in lst: if len(predicates) != 1: raise Exception("Tuples not supported in HAS ONLY") op, value = predicates[0] if op != "": raise Exception("Predicated not supported in HAS ONLY") if not isinstance(value, str): raise Exception("Only strings supported in HAS ONLY") yield value try: order_numbers = list([ATOMIC_NUMBERS[element] for element in values()]) order_numbers.sort() value = "".join([CHEMICAL_SYMBOLS[number] for number in order_numbers]) except KeyError: raise Exception("HAS ONLY is only supported for chemical symbols") return Q("term", **{quantity.has_only_quantity.name: value}) def length(self, args): (quantity,) = args if quantity.length_quantity is None: raise Exception("LENGTH is not supported for %s" % quantity.name) return quantity.length_quantity def known_op(self, args): quantity, qualifier = args query = Q("exists", field=self._field(quantity)) if qualifier == "KNOWN": return query elif qualifier == "UNKNOWN": return ~query raise NotImplementedError def contains_op(self, args): quantity, value = args return self._wildcard_query(quantity, "*%s*" % value) def starts_op(self, args): quantity, value = args return self._wildcard_query(quantity, "%s*" % value) def ends_op(self, args): quantity, value = args return self._wildcard_query(quantity, "*%s" % value) def list(self, args): return list(args) def quantity_tuple(self, args): return list(args) def predicate_tuple(self, args): return list(args) def predicate(self, args): if len(args) == 1: return "", args[0] else: return args[0], args[1] def quantity(self, args): quantity_name = args[0] if quantity_name not in self.index_mapping: raise Exception("%s is not a searchable quantity" % quantity_name) quantity = self.index_mapping.get(quantity_name, None) if quantity is None: quantity = Quantity(name=quantity_name) return quantity def int_literal(self, args): return int(args[0]) def float_literal(self, args): return float(args[0]) def string_literal(self, args): return args[0].strip('"')
true
true
1c371aabba46c58425637f54217fa76dc4623b54
262
py
Python
lopy4_firmware/lib/lorakeys.py
dnear1/smarterbham
864215844e1017366c69b6c77119476d50c2e7c1
[ "MIT" ]
3
2020-01-03T18:24:19.000Z
2020-06-06T22:38:34.000Z
lopy4_firmware/lib/lorakeys.py
alyssafrost/smarterbham
6e5878ded0c31b418b2b3dfd561746e6b9e31da6
[ "MIT" ]
3
2019-07-06T16:50:46.000Z
2020-03-26T21:28:56.000Z
lopy4_firmware/lib/lorakeys.py
alyssafrost/smarterbham
6e5878ded0c31b418b2b3dfd561746e6b9e31da6
[ "MIT" ]
4
2020-02-13T02:39:14.000Z
2020-06-06T22:38:21.000Z
#store Lora OTAA keys here - but don't back this up to Github import struct import ubinascii _dev_eui = ubinascii.unhexlify('0000000000000000') _app_eui = ubinascii.unhexlify('0000000000000000') _app_key = ubinascii.unhexlify('00000000000000000000000000000000')
37.428571
66
0.820611
import struct import ubinascii _dev_eui = ubinascii.unhexlify('0000000000000000') _app_eui = ubinascii.unhexlify('0000000000000000') _app_key = ubinascii.unhexlify('00000000000000000000000000000000')
true
true
1c371acf466b43b5acc94830e7f79b70ef48c763
10,059
py
Python
isi_sdk_8_1_0/isi_sdk_8_1_0/models/job_event.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
24
2018-06-22T14:13:23.000Z
2022-03-23T01:21:26.000Z
isi_sdk_8_1_0/isi_sdk_8_1_0/models/job_event.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
46
2018-04-30T13:28:22.000Z
2022-03-21T21:11:07.000Z
isi_sdk_8_1_0/isi_sdk_8_1_0/models/job_event.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
29
2018-06-19T00:14:04.000Z
2022-02-08T17:51:19.000Z
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 5 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class JobEvent(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'flags': 'str', 'fmt_type': 'str', 'id': 'int', 'job_id': 'int', 'job_type': 'str', 'key': 'str', 'phase': 'int', 'raw_type': 'int', 'time': 'int', 'value': 'str' } attribute_map = { 'flags': 'flags', 'fmt_type': 'fmt_type', 'id': 'id', 'job_id': 'job_id', 'job_type': 'job_type', 'key': 'key', 'phase': 'phase', 'raw_type': 'raw_type', 'time': 'time', 'value': 'value' } def __init__(self, flags=None, fmt_type=None, id=None, job_id=None, job_type=None, key=None, phase=None, raw_type=None, time=None, value=None): # noqa: E501 """JobEvent - a model defined in Swagger""" # noqa: E501 self._flags = None self._fmt_type = None self._id = None self._job_id = None self._job_type = None self._key = None self._phase = None self._raw_type = None self._time = None self._value = None self.discriminator = None self.flags = flags self.fmt_type = fmt_type self.id = id self.job_id = job_id self.job_type = job_type self.key = key self.phase = phase self.raw_type = raw_type self.time = time if value is not None: self.value = value @property def flags(self): """Gets the flags of this JobEvent. # noqa: E501 Event flags. # noqa: E501 :return: The flags of this JobEvent. # noqa: E501 :rtype: str """ return self._flags @flags.setter def flags(self, flags): """Sets the flags of this JobEvent. Event flags. # noqa: E501 :param flags: The flags of this JobEvent. # noqa: E501 :type: str """ if flags is None: raise ValueError("Invalid value for `flags`, must not be `None`") # noqa: E501 self._flags = flags @property def fmt_type(self): """Gets the fmt_type of this JobEvent. # noqa: E501 A string representation of the type of the data value. # noqa: E501 :return: The fmt_type of this JobEvent. # noqa: E501 :rtype: str """ return self._fmt_type @fmt_type.setter def fmt_type(self, fmt_type): """Sets the fmt_type of this JobEvent. A string representation of the type of the data value. # noqa: E501 :param fmt_type: The fmt_type of this JobEvent. # noqa: E501 :type: str """ if fmt_type is None: raise ValueError("Invalid value for `fmt_type`, must not be `None`") # noqa: E501 self._fmt_type = fmt_type @property def id(self): """Gets the id of this JobEvent. # noqa: E501 Job event ID. # noqa: E501 :return: The id of this JobEvent. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): """Sets the id of this JobEvent. Job event ID. # noqa: E501 :param id: The id of this JobEvent. # noqa: E501 :type: int """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def job_id(self): """Gets the job_id of this JobEvent. # noqa: E501 Job ID. # noqa: E501 :return: The job_id of this JobEvent. # noqa: E501 :rtype: int """ return self._job_id @job_id.setter def job_id(self, job_id): """Sets the job_id of this JobEvent. Job ID. # noqa: E501 :param job_id: The job_id of this JobEvent. # noqa: E501 :type: int """ if job_id is None: raise ValueError("Invalid value for `job_id`, must not be `None`") # noqa: E501 if job_id is not None and job_id < 1: # noqa: E501 raise ValueError("Invalid value for `job_id`, must be a value greater than or equal to `1`") # noqa: E501 self._job_id = job_id @property def job_type(self): """Gets the job_type of this JobEvent. # noqa: E501 Job Type. # noqa: E501 :return: The job_type of this JobEvent. # noqa: E501 :rtype: str """ return self._job_type @job_type.setter def job_type(self, job_type): """Sets the job_type of this JobEvent. Job Type. # noqa: E501 :param job_type: The job_type of this JobEvent. # noqa: E501 :type: str """ if job_type is None: raise ValueError("Invalid value for `job_type`, must not be `None`") # noqa: E501 self._job_type = job_type @property def key(self): """Gets the key of this JobEvent. # noqa: E501 Event key name. # noqa: E501 :return: The key of this JobEvent. # noqa: E501 :rtype: str """ return self._key @key.setter def key(self, key): """Sets the key of this JobEvent. Event key name. # noqa: E501 :param key: The key of this JobEvent. # noqa: E501 :type: str """ if key is None: raise ValueError("Invalid value for `key`, must not be `None`") # noqa: E501 self._key = key @property def phase(self): """Gets the phase of this JobEvent. # noqa: E501 Job phase number at time of event. # noqa: E501 :return: The phase of this JobEvent. # noqa: E501 :rtype: int """ return self._phase @phase.setter def phase(self, phase): """Sets the phase of this JobEvent. Job phase number at time of event. # noqa: E501 :param phase: The phase of this JobEvent. # noqa: E501 :type: int """ if phase is None: raise ValueError("Invalid value for `phase`, must not be `None`") # noqa: E501 self._phase = phase @property def raw_type(self): """Gets the raw_type of this JobEvent. # noqa: E501 An integer representation of the type of the data value. # noqa: E501 :return: The raw_type of this JobEvent. # noqa: E501 :rtype: int """ return self._raw_type @raw_type.setter def raw_type(self, raw_type): """Sets the raw_type of this JobEvent. An integer representation of the type of the data value. # noqa: E501 :param raw_type: The raw_type of this JobEvent. # noqa: E501 :type: int """ if raw_type is None: raise ValueError("Invalid value for `raw_type`, must not be `None`") # noqa: E501 self._raw_type = raw_type @property def time(self): """Gets the time of this JobEvent. # noqa: E501 Time of event in Unix epoch seconds. # noqa: E501 :return: The time of this JobEvent. # noqa: E501 :rtype: int """ return self._time @time.setter def time(self, time): """Sets the time of this JobEvent. Time of event in Unix epoch seconds. # noqa: E501 :param time: The time of this JobEvent. # noqa: E501 :type: int """ if time is None: raise ValueError("Invalid value for `time`, must not be `None`") # noqa: E501 self._time = time @property def value(self): """Gets the value of this JobEvent. # noqa: E501 Event value. # noqa: E501 :return: The value of this JobEvent. # noqa: E501 :rtype: str """ return self._value @value.setter def value(self, value): """Sets the value of this JobEvent. Event value. # noqa: E501 :param value: The value of this JobEvent. # noqa: E501 :type: str """ self._value = value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, JobEvent): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
26.611111
161
0.545482
import pprint import re import six class JobEvent(object): swagger_types = { 'flags': 'str', 'fmt_type': 'str', 'id': 'int', 'job_id': 'int', 'job_type': 'str', 'key': 'str', 'phase': 'int', 'raw_type': 'int', 'time': 'int', 'value': 'str' } attribute_map = { 'flags': 'flags', 'fmt_type': 'fmt_type', 'id': 'id', 'job_id': 'job_id', 'job_type': 'job_type', 'key': 'key', 'phase': 'phase', 'raw_type': 'raw_type', 'time': 'time', 'value': 'value' } def __init__(self, flags=None, fmt_type=None, id=None, job_id=None, job_type=None, key=None, phase=None, raw_type=None, time=None, value=None): self._flags = None self._fmt_type = None self._id = None self._job_id = None self._job_type = None self._key = None self._phase = None self._raw_type = None self._time = None self._value = None self.discriminator = None self.flags = flags self.fmt_type = fmt_type self.id = id self.job_id = job_id self.job_type = job_type self.key = key self.phase = phase self.raw_type = raw_type self.time = time if value is not None: self.value = value @property def flags(self): return self._flags @flags.setter def flags(self, flags): if flags is None: raise ValueError("Invalid value for `flags`, must not be `None`") self._flags = flags @property def fmt_type(self): return self._fmt_type @fmt_type.setter def fmt_type(self, fmt_type): if fmt_type is None: raise ValueError("Invalid value for `fmt_type`, must not be `None`") self._fmt_type = fmt_type @property def id(self): return self._id @id.setter def id(self, id): if id is None: raise ValueError("Invalid value for `id`, must not be `None`") self._id = id @property def job_id(self): return self._job_id @job_id.setter def job_id(self, job_id): if job_id is None: raise ValueError("Invalid value for `job_id`, must not be `None`") if job_id is not None and job_id < 1: raise ValueError("Invalid value for `job_id`, must be a value greater than or equal to `1`") self._job_id = job_id @property def job_type(self): return self._job_type @job_type.setter def job_type(self, job_type): if job_type is None: raise ValueError("Invalid value for `job_type`, must not be `None`") self._job_type = job_type @property def key(self): return self._key @key.setter def key(self, key): if key is None: raise ValueError("Invalid value for `key`, must not be `None`") self._key = key @property def phase(self): return self._phase @phase.setter def phase(self, phase): if phase is None: raise ValueError("Invalid value for `phase`, must not be `None`") self._phase = phase @property def raw_type(self): return self._raw_type @raw_type.setter def raw_type(self, raw_type): if raw_type is None: raise ValueError("Invalid value for `raw_type`, must not be `None`") self._raw_type = raw_type @property def time(self): return self._time @time.setter def time(self, time): if time is None: raise ValueError("Invalid value for `time`, must not be `None`") self._time = time @property def value(self): return self._value @value.setter def value(self, value): self._value = value def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, JobEvent): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c371c19caeb1241fb3379853889d5e1c5d178ad
5,192
py
Python
kargers.py
mkner/algorithms
4eec707f6ca8f65ee4659064a61f12326d2d049e
[ "MIT" ]
null
null
null
kargers.py
mkner/algorithms
4eec707f6ca8f65ee4659064a61f12326d2d049e
[ "MIT" ]
null
null
null
kargers.py
mkner/algorithms
4eec707f6ca8f65ee4659064a61f12326d2d049e
[ "MIT" ]
null
null
null
# # # kargers min-cut randomized contraction algorithm # # # (c) Mike Knerr 2019 # # ver: 0.15 # based on tim roughgarden's version # of karger's min-cut algorithm import numpy as np import matplotlib.pyplot as plt import os #import math as m #from statistics import median import random as rand import copy #graphfile='graphdata.txt' def load_graph_from(fname): # # inputs: a file containing data about the nodes and # the adjacent nodes in format node number # followed by a list of adjacent nodes # outputs: a dictionary of lists # the keys are the node numbers and each list # contains the variable number of adjacent node numbers g={} ilist=[] f = open(fname, 'r') ilist = f.readlines() f.close() # file has to be stripped of tabs and newlines # as possible delimiters and converted into ints for i in range(len(ilist)): # the one-liners stuff you can do with python! # its a little rough on the eyes but... works ilist[i]=ilist[i].split('\t') # split into strings ilist[i]=ilist[i][0:len(ilist[i])-1] # strips out ending newline ilist[i]=list(map(int,ilist[i])) # convert strings to ints idx=int(ilist[i][0]) g[idx]=ilist[i][1:len(ilist)-1] return g def get_random_edge(graph): v = rand.choice(list(graph.keys())) #get a random node number w = rand.choice(graph[v]) # get one of its adjacent node randomly return(v,w) def contract_nodes(graph, supernode, adjnode): # supernode absorbs and replaces the adjacent node # assumes undirected graph ie pointers on all edges go both ways for node in graph[adjnode]: # merge all nodes adj node is adjacent to if node != supernode: # dont create a self-loop graph[supernode].append(node) # merge adj nodes into super graph[node].remove(adjnode) # since adjnode is absorbed it doesnt exist if node != supernode: # put in supernode in its place graph[node].append(supernode) del graph[adjnode] # adj node was just absorbed is no longer in graph return def run_graph(graph,iterations): savedgraphs=[] savedcuts=[] for i in range(iterations): g = copy.deepcopy(graph) # get fresh copy while len(g)>2: v1,v2= get_random_edge(g) contract_nodes(g,v1,v2) savedgraphs.append(g) # just get any node from the collapsed graph and save the # save the number of its adjacent nodes as the cut savedcuts.append( len(g[min(g.keys())]) ) # get some any entry cut len return min(savedcuts),savedcuts ###### START HERE ###### ### TEST algo development with some minimal cases # to see if code holds up # test a null case # what if mincut=0 g={1:[]} r= run_graph(g,10) r[0] # one node in a self-loop # and no edges g={1:[1]} #mincut of self loop = 1 run_graph(g,10) # 2 node linear # mincut is 1 g = {1: [2], 2: [1]} r=run_graph(g,10) r[0] # 3 node linear # mincut is 1 g = {1:[2], 2:[1,3], 3:[2]} r=run_graph(g,10) r[0] # attach 3rd back to node 1 to create a n-cycle # mincut is 1 g = {1:[2,3], 2:[1,3], 3:[2,1]} run_graph(g,10) r[0] # 3 node fully connected # mincut is 2 g = {1:[2,3], 2:[1,3], 3:[1,2]} r=run_graph(g,10) r[0] g = {1:[2,3], 2:[1,3], 3:[2,1]} r=run_graph(g,10) r[0] # attach 4th to node 3 in 3 node fully connected # mincut is 1 g = {1:[2,3], 2:[1,3], 3:[1,2,4], 4:[3]} r=run_graph(g,10) r[0] # fully connected square # mincut is 3 g = {1:[2,3,4],2:[1,3,4],3:[1,2,4],4:[1,2,3]} r= run_graph(g,100) r[0] # attach 5th node to node 4 from the fully connected square # mincut is 1 g = {1:[2,3,4],2:[1,3,4],3:[1,2,4],4:[1,2,3,5], 5:[4]} #mincut=1 : dangling node attached to fully connected square r=run_graph(g,50) r[0] # attach 5th node to node 4 AND 3 # mincut is 2 g = {1:[2,3,4],2:[1,3,4],3:[1,2,4,5],4:[1,2,3,5],5:[3,4]} #mincut=1 : dangling node attached to fully connected square r=run_graph(g,1000) r[0] max(r[1]) # each entry in dictionary graph is a (key,list) # get adjacency list to run # load a graph or use a g from above g = load_graph_from("graphdata.txt") testresults=[] minlist=[] ntests = 25 # run this far then check for convergence for tests in range(1,ntests+1): r=run_graph(g,tests) testresults.append(r) minlist.append(r[0]) #min(minlist) print("Current run of: ",ntests) print("Current min: ",min(minlist))
25.576355
124
0.547188
# of karger's min-cut algorithm import numpy as np import matplotlib.pyplot as plt import os import random as rand import copy def load_graph_from(fname): g={} ilist=[] f = open(fname, 'r') ilist = f.readlines() f.close() for i in range(len(ilist)): ilist[i]=ilist[i].split('\t') ilist[i]=ilist[i][0:len(ilist[i])-1] ilist[i]=list(map(int,ilist[i])) idx=int(ilist[i][0]) g[idx]=ilist[i][1:len(ilist)-1] return g def get_random_edge(graph): v = rand.choice(list(graph.keys())) w = rand.choice(graph[v]) return(v,w) def contract_nodes(graph, supernode, adjnode): for node in graph[adjnode]: if node != supernode: graph[supernode].append(node) graph[node].remove(adjnode) if node != supernode: graph[node].append(supernode) del graph[adjnode] return def run_graph(graph,iterations): savedgraphs=[] savedcuts=[] for i in range(iterations): g = copy.deepcopy(graph) while len(g)>2: v1,v2= get_random_edge(g) contract_nodes(g,v1,v2) savedgraphs.append(g) savedcuts.append( len(g[min(g.keys())]) ) return min(savedcuts),savedcuts ], 3:[2]} r=run_graph(g,10) r[0] g = {1:[2,3], 2:[1,3], 3:[2,1]} run_graph(g,10) r[0] g = {1:[2,3], 2:[1,3], 3:[1,2]} r=run_graph(g,10) r[0] g = {1:[2,3], 2:[1,3], 3:[2,1]} r=run_graph(g,10) r[0] g = {1:[2,3], 2:[1,3], 3:[1,2,4], 4:[3]} r=run_graph(g,10) r[0] g = {1:[2,3,4],2:[1,3,4],3:[1,2,4],4:[1,2,3]} r= run_graph(g,100) r[0] g = {1:[2,3,4],2:[1,3,4],3:[1,2,4],4:[1,2,3,5], 5:[4]} r=run_graph(g,50) r[0] g = {1:[2,3,4],2:[1,3,4],3:[1,2,4,5],4:[1,2,3,5],5:[3,4]} r=run_graph(g,1000) r[0] max(r[1]) g = load_graph_from("graphdata.txt") testresults=[] minlist=[] ntests = 25 for tests in range(1,ntests+1): r=run_graph(g,tests) testresults.append(r) minlist.append(r[0]) print("Current run of: ",ntests) print("Current min: ",min(minlist))
true
true
1c371e23e8db86e74aa72b244b98f0b0ae0bbd54
2,180
py
Python
app/utils/pokemon.py
antonpirker/asyncdjango
855a4425f345fd9685980447a56cd11af9078e89
[ "MIT" ]
null
null
null
app/utils/pokemon.py
antonpirker/asyncdjango
855a4425f345fd9685980447a56cd11af9078e89
[ "MIT" ]
4
2021-06-24T11:36:05.000Z
2021-07-27T08:32:28.000Z
app/utils/pokemon.py
antonpirker/asyncdjango
855a4425f345fd9685980447a56cd11af9078e89
[ "MIT" ]
null
null
null
import requests import psycopg2 import aiohttp import asyncio import asyncpg from django.conf import settings import time import logging logger = logging.getLogger(__name__) POKEMON_NUMBER = 25 SQL_STATEMENT = "SELECT * FROM app_pokemon ORDER BY number;" SQL_STATEMENT_ONE = f"SELECT * FROM app_pokemon WHERE number = {POKEMON_NUMBER};" DB = settings.DATABASES['default'] CONNECTION_STRING = f'postgresql://{DB["USER"]}:{DB["PASSWORD"]}@{DB["HOST"]}:{DB["PORT"]}/{DB["NAME"]}' def get_pokemon_sync(): # Getting the Pokemon from DB without using the Django ORM # (for better comparison, because there is no async ORM yet) conn = psycopg2.connect(CONNECTION_STRING) cur = conn.cursor() cur.execute(SQL_STATEMENT) pokemons = cur.fetchmany(1000) cur.close() conn.close() return [{'number': pokemon[1], 'name': pokemon[2]} for pokemon in pokemons] def get_one_pokemon_sync(): # Getting the Pokemon from DB without using the Django ORM # (for better comparison, because there is no async ORM yet) conn = psycopg2.connect(CONNECTION_STRING) cur = conn.cursor() cur.execute(SQL_STATEMENT_ONE) pokemon = cur.fetchone() cur.close() conn.close() return { 'name': pokemon[2], 'number': pokemon[1], 'type1': pokemon[3], 'type2': pokemon[4], 'hp': pokemon[5], 'attack': pokemon[6], 'defense': pokemon[7], 'sp_atk': pokemon[8], 'sp_def': pokemon[9], 'speed': pokemon[10], 'generation': pokemon[11], 'legendary': pokemon[12] } async def get_pokemon_async(): conn = await asyncpg.connect(CONNECTION_STRING) async with conn.transaction(): cur = await conn.cursor(SQL_STATEMENT) pokemons = await cur.fetch(1000) await conn.close() return [{'number': pokemon['number'], 'name': pokemon['name']} for pokemon in pokemons] async def get_one_pokemon_async(): conn = await asyncpg.connect(CONNECTION_STRING) async with conn.transaction(): cur = await conn.cursor(SQL_STATEMENT_ONE) pokemon = await cur.fetchrow() await conn.close() return pokemon
25.952381
104
0.66055
import requests import psycopg2 import aiohttp import asyncio import asyncpg from django.conf import settings import time import logging logger = logging.getLogger(__name__) POKEMON_NUMBER = 25 SQL_STATEMENT = "SELECT * FROM app_pokemon ORDER BY number;" SQL_STATEMENT_ONE = f"SELECT * FROM app_pokemon WHERE number = {POKEMON_NUMBER};" DB = settings.DATABASES['default'] CONNECTION_STRING = f'postgresql://{DB["USER"]}:{DB["PASSWORD"]}@{DB["HOST"]}:{DB["PORT"]}/{DB["NAME"]}' def get_pokemon_sync(): conn = psycopg2.connect(CONNECTION_STRING) cur = conn.cursor() cur.execute(SQL_STATEMENT) pokemons = cur.fetchmany(1000) cur.close() conn.close() return [{'number': pokemon[1], 'name': pokemon[2]} for pokemon in pokemons] def get_one_pokemon_sync(): conn = psycopg2.connect(CONNECTION_STRING) cur = conn.cursor() cur.execute(SQL_STATEMENT_ONE) pokemon = cur.fetchone() cur.close() conn.close() return { 'name': pokemon[2], 'number': pokemon[1], 'type1': pokemon[3], 'type2': pokemon[4], 'hp': pokemon[5], 'attack': pokemon[6], 'defense': pokemon[7], 'sp_atk': pokemon[8], 'sp_def': pokemon[9], 'speed': pokemon[10], 'generation': pokemon[11], 'legendary': pokemon[12] } async def get_pokemon_async(): conn = await asyncpg.connect(CONNECTION_STRING) async with conn.transaction(): cur = await conn.cursor(SQL_STATEMENT) pokemons = await cur.fetch(1000) await conn.close() return [{'number': pokemon['number'], 'name': pokemon['name']} for pokemon in pokemons] async def get_one_pokemon_async(): conn = await asyncpg.connect(CONNECTION_STRING) async with conn.transaction(): cur = await conn.cursor(SQL_STATEMENT_ONE) pokemon = await cur.fetchrow() await conn.close() return pokemon
true
true
1c3720d78947bec0e2b0220515498d9e4e2de982
96,051
py
Python
saleor/graphql/translations/tests/test_translations.py
haoyang09/saleor
33f17288459012aab28d517c899fac439a07b729
[ "CC-BY-4.0" ]
1
2021-08-23T09:23:43.000Z
2021-08-23T09:23:43.000Z
saleor/graphql/translations/tests/test_translations.py
haoyang09/saleor
33f17288459012aab28d517c899fac439a07b729
[ "CC-BY-4.0" ]
172
2021-05-03T04:34:37.000Z
2022-03-28T04:41:53.000Z
saleor/graphql/translations/tests/test_translations.py
twocucao/saleor
308413ed9c19e7938e690fe3cf339b526fd34df2
[ "CC-BY-4.0" ]
1
2022-03-24T08:37:58.000Z
2022-03-24T08:37:58.000Z
import json from unittest.mock import patch import graphene import pytest from django.contrib.auth.models import Permission from freezegun import freeze_time from ....tests.utils import dummy_editorjs from ....webhook.event_types import WebhookEventAsyncType from ....webhook.payloads import generate_translation_payload from ...core.enums import LanguageCodeEnum from ...tests.utils import assert_no_permission, get_graphql_content from ..schema import TranslatableKinds def test_product_translation(user_api_client, product, channel_USD): description = dummy_editorjs("test desription") product.translations.create( language_code="pl", name="Produkt", description=description ) query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = user_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] translation_data = data["product"]["translation"] assert translation_data["name"] == "Produkt" assert translation_data["language"]["code"] == "PL" assert ( translation_data["description"] == translation_data["descriptionJson"] == dummy_editorjs("test desription", json_format=True) ) def test_product_translation_without_description(user_api_client, product, channel_USD): product.translations.create(language_code="pl", name="Produkt") query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = user_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] translation_data = data["product"]["translation"] assert translation_data["name"] == "Produkt" assert translation_data["language"]["code"] == "PL" assert translation_data["description"] is None assert translation_data["descriptionJson"] == "{}" def test_product_translation_with_app(app_api_client, product, channel_USD): product.translations.create(language_code="pl", name="Produkt") query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = app_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] assert data["product"]["translation"]["name"] == "Produkt" assert data["product"]["translation"]["language"]["code"] == "PL" def test_product_variant_translation(user_api_client, variant, channel_USD): variant.translations.create(language_code="pl", name="Wariant") query = """ query productVariantById($productVariantId: ID!, $channel: String) { productVariant(id: $productVariantId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) response = user_api_client.post_graphql( query, {"productVariantId": product_variant_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] assert data["productVariant"]["translation"]["name"] == "Wariant" assert data["productVariant"]["translation"]["language"]["code"] == "PL" def test_collection_translation(user_api_client, published_collection, channel_USD): description = dummy_editorjs("test desription") published_collection.translations.create( language_code="pl", name="Kolekcja", description=description ) query = """ query collectionById($collectionId: ID!, $channel: String) { collection(id: $collectionId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ collection_id = graphene.Node.to_global_id("Collection", published_collection.id) variables = {"collectionId": collection_id, "channel": channel_USD.slug} response = user_api_client.post_graphql(query, variables) data = get_graphql_content(response)["data"] translation_data = data["collection"]["translation"] assert translation_data["name"] == "Kolekcja" assert translation_data["language"]["code"] == "PL" assert ( translation_data["description"] == translation_data["descriptionJson"] == dummy_editorjs("test desription", json_format=True) ) def test_collection_translation_without_description( user_api_client, published_collection, channel_USD ): published_collection.translations.create(language_code="pl", name="Kolekcja") query = """ query collectionById($collectionId: ID!, $channel: String) { collection(id: $collectionId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ collection_id = graphene.Node.to_global_id("Collection", published_collection.id) variables = {"collectionId": collection_id, "channel": channel_USD.slug} response = user_api_client.post_graphql(query, variables) data = get_graphql_content(response)["data"] translation_data = data["collection"]["translation"] assert translation_data["name"] == "Kolekcja" assert translation_data["language"]["code"] == "PL" assert translation_data["description"] is None assert translation_data["descriptionJson"] == "{}" def test_category_translation(user_api_client, category): description = dummy_editorjs("test description") category.translations.create( language_code="pl", name="Kategoria", description=description ) query = """ query categoryById($categoryId: ID!) { category(id: $categoryId) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ category_id = graphene.Node.to_global_id("Category", category.id) response = user_api_client.post_graphql(query, {"categoryId": category_id}) data = get_graphql_content(response)["data"] translation_data = data["category"]["translation"] assert translation_data["name"] == "Kategoria" assert translation_data["language"]["code"] == "PL" assert ( translation_data["description"] == translation_data["descriptionJson"] == dummy_editorjs("test description", json_format=True) ) def test_category_translation_without_description(user_api_client, category): category.translations.create(language_code="pl", name="Kategoria") query = """ query categoryById($categoryId: ID!) { category(id: $categoryId) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ category_id = graphene.Node.to_global_id("Category", category.id) response = user_api_client.post_graphql(query, {"categoryId": category_id}) data = get_graphql_content(response)["data"] translation_data = data["category"]["translation"] assert translation_data["name"] == "Kategoria" assert translation_data["language"]["code"] == "PL" assert translation_data["description"] is None assert translation_data["descriptionJson"] == "{}" def test_voucher_translation(staff_api_client, voucher, permission_manage_discounts): voucher.translations.create(language_code="pl", name="Bon") query = """ query voucherById($voucherId: ID!) { voucher(id: $voucherId) { translation(languageCode: PL) { name language { code } } } } """ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) response = staff_api_client.post_graphql( query, {"voucherId": voucher_id}, permissions=[permission_manage_discounts] ) data = get_graphql_content(response)["data"] assert data["voucher"]["translation"]["name"] == "Bon" assert data["voucher"]["translation"]["language"]["code"] == "PL" def test_sale_translation(staff_api_client, sale, permission_manage_discounts): sale.translations.create(language_code="pl", name="Wyprz") query = """ query saleById($saleId: ID!) { sale(id: $saleId) { translation(languageCode: PL) { name language { code } } } } """ sale_id = graphene.Node.to_global_id("Sale", sale.id) response = staff_api_client.post_graphql( query, {"saleId": sale_id}, permissions=[permission_manage_discounts] ) data = get_graphql_content(response)["data"] assert data["sale"]["translation"]["name"] == "Wyprz" assert data["sale"]["translation"]["language"]["code"] == "PL" def test_page_translation(user_api_client, page): content = dummy_editorjs("test content") page.translations.create(language_code="pl", title="Strona", content=content) query = """ query pageById($pageId: ID!) { page(id: $pageId) { translation(languageCode: PL) { title content contentJson language { code } } } } """ page_id = graphene.Node.to_global_id("Page", page.id) response = user_api_client.post_graphql(query, {"pageId": page_id}) data = get_graphql_content(response)["data"] translation_data = data["page"]["translation"] assert translation_data["title"] == "Strona" assert translation_data["language"]["code"] == "PL" assert ( translation_data["content"] == translation_data["contentJson"] == dummy_editorjs("test content", json_format=True) ) def test_page_translation_without_content(user_api_client, page): page.translations.create(language_code="pl", title="Strona") query = """ query pageById($pageId: ID!) { page(id: $pageId) { translation(languageCode: PL) { title content contentJson language { code } } } } """ page_id = graphene.Node.to_global_id("Page", page.id) response = user_api_client.post_graphql(query, {"pageId": page_id}) data = get_graphql_content(response)["data"] translation_data = data["page"]["translation"] assert translation_data["title"] == "Strona" assert translation_data["language"]["code"] == "PL" assert translation_data["content"] is None assert translation_data["contentJson"] == "{}" def test_attribute_translation(user_api_client, color_attribute): color_attribute.translations.create(language_code="pl", name="Kolor") query = """ query { attributes(first: 1) { edges { node { translation(languageCode: PL) { name language { code } } } } } } """ response = user_api_client.post_graphql(query) data = get_graphql_content(response)["data"] attribute = data["attributes"]["edges"][0]["node"] assert attribute["translation"]["name"] == "Kolor" assert attribute["translation"]["language"]["code"] == "PL" def test_attribute_value_translation(user_api_client, pink_attribute_value): pink_attribute_value.translations.create( language_code="pl", name="Różowy", rich_text=dummy_editorjs("Pink") ) query = """ query { attributes(first: 1) { edges { node { choices(first: 10) { edges { node { translation(languageCode: PL) { name richText language { code } } } } } } } } } """ attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) response = user_api_client.post_graphql( query, {"attributeValueId": attribute_value_id} ) data = get_graphql_content(response)["data"] attribute_value = data["attributes"]["edges"][0]["node"]["choices"]["edges"][-1][ "node" ] assert attribute_value["translation"]["name"] == "Różowy" assert attribute_value["translation"]["richText"] == json.dumps( dummy_editorjs("Pink") ) assert attribute_value["translation"]["language"]["code"] == "PL" def test_shipping_method_translation( staff_api_client, shipping_method, permission_manage_shipping ): shipping_method.translations.create(language_code="pl", name="DHL Polska") query = """ query shippingZoneById($shippingZoneId: ID!) { shippingZone(id: $shippingZoneId) { shippingMethods { translation(languageCode: PL) { name language { code } } } } } """ shipping_zone_id = graphene.Node.to_global_id( "ShippingZone", shipping_method.shipping_zone.id ) response = staff_api_client.post_graphql( query, {"shippingZoneId": shipping_zone_id}, permissions=[permission_manage_shipping], ) data = get_graphql_content(response)["data"] shipping_method = data["shippingZone"]["shippingMethods"][-1] assert shipping_method["translation"]["name"] == "DHL Polska" assert shipping_method["translation"]["language"]["code"] == "PL" def test_menu_item_translation(user_api_client, menu_item): menu_item.translations.create(language_code="pl", name="Odnośnik 1") query = """ query menuItemById($menuItemId: ID!) { menuItem(id: $menuItemId) { translation(languageCode: PL) { name language { code } } } } """ menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) response = user_api_client.post_graphql(query, {"menuItemId": menu_item_id}) data = get_graphql_content(response)["data"] assert data["menuItem"]["translation"]["name"] == "Odnośnik 1" assert data["menuItem"]["translation"]["language"]["code"] == "PL" def test_shop_translation(user_api_client, site_settings): site_settings.translations.create(language_code="pl", header_text="Nagłówek") query = """ query { shop { translation(languageCode: PL) { headerText language { code } } } } """ response = user_api_client.post_graphql(query) data = get_graphql_content(response)["data"] assert data["shop"]["translation"]["headerText"] == "Nagłówek" assert data["shop"]["translation"]["language"]["code"] == "PL" def test_product_no_translation(user_api_client, product, channel_USD): query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = user_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] assert data["product"]["translation"] is None def test_product_variant_no_translation(user_api_client, variant, channel_USD): query = """ query productVariantById($productVariantId: ID!, $channel: String) { productVariant(id: $productVariantId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) response = user_api_client.post_graphql( query, {"productVariantId": product_variant_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] assert data["productVariant"]["translation"] is None def test_collection_no_translation(user_api_client, published_collection, channel_USD): query = """ query collectionById($collectionId: ID!, $channel: String) { collection(id: $collectionId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ collection_id = graphene.Node.to_global_id("Collection", published_collection.id) variables = {"collectionId": collection_id, "channel": channel_USD.slug} response = user_api_client.post_graphql(query, variables) data = get_graphql_content(response)["data"] assert data["collection"]["translation"] is None def test_category_no_translation(user_api_client, category): query = """ query categoryById($categoryId: ID!) { category(id: $categoryId) { translation(languageCode: PL) { name language { code } } } } """ category_id = graphene.Node.to_global_id("Category", category.id) response = user_api_client.post_graphql(query, {"categoryId": category_id}) data = get_graphql_content(response)["data"] assert data["category"]["translation"] is None def test_voucher_no_translation(staff_api_client, voucher, permission_manage_discounts): query = """ query voucherById($voucherId: ID!) { voucher(id: $voucherId) { translation(languageCode: PL) { name language { code } } } } """ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) response = staff_api_client.post_graphql( query, {"voucherId": voucher_id}, permissions=[permission_manage_discounts] ) data = get_graphql_content(response)["data"] assert data["voucher"]["translation"] is None def test_page_no_translation(user_api_client, page): query = """ query pageById($pageId: ID!) { page(id: $pageId) { translation(languageCode: PL) { title language { code } } } } """ page_id = graphene.Node.to_global_id("Page", page.id) response = user_api_client.post_graphql(query, {"pageId": page_id}) data = get_graphql_content(response)["data"] assert data["page"]["translation"] is None def test_attribute_no_translation(user_api_client, color_attribute): query = """ query { attributes(first: 1) { edges { node { translation(languageCode: PL) { name language { code } } } } } } """ response = user_api_client.post_graphql(query) data = get_graphql_content(response)["data"] attribute = data["attributes"]["edges"][0]["node"] assert attribute["translation"] is None def test_attribute_value_no_translation(user_api_client, pink_attribute_value): query = """ query { attributes(first: 1) { edges { node { choices(first: 10) { edges { node { translation(languageCode: PL) { name language { code } } } } } } } } } """ attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) response = user_api_client.post_graphql( query, {"attributeValueId": attribute_value_id} ) data = get_graphql_content(response)["data"] attribute_value = data["attributes"]["edges"][0]["node"]["choices"]["edges"][-1][ "node" ] assert attribute_value["translation"] is None def test_shipping_method_no_translation( staff_api_client, shipping_method, permission_manage_shipping ): query = """ query shippingZoneById($shippingZoneId: ID!) { shippingZone(id: $shippingZoneId) { shippingMethods { translation(languageCode: PL) { name language { code } } } } } """ shipping_zone_id = graphene.Node.to_global_id( "ShippingZone", shipping_method.shipping_zone.id ) response = staff_api_client.post_graphql( query, {"shippingZoneId": shipping_zone_id}, permissions=[permission_manage_shipping], ) data = get_graphql_content(response)["data"] shipping_method = data["shippingZone"]["shippingMethods"][0] assert shipping_method["translation"] is None def test_menu_item_no_translation(user_api_client, menu_item): query = """ query menuItemById($menuItemId: ID!) { menuItem(id: $menuItemId) { translation(languageCode: PL) { name language { code } } } } """ menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) response = user_api_client.post_graphql(query, {"menuItemId": menu_item_id}) data = get_graphql_content(response)["data"] assert data["menuItem"]["translation"] is None def test_shop_no_translation(user_api_client, site_settings): query = """ query { shop { translation(languageCode: PL) { headerText language { code } } } } """ response = user_api_client.post_graphql(query) data = get_graphql_content(response)["data"] assert data["shop"]["translation"] is None PRODUCT_TRANSLATE_MUTATION = """ mutation productTranslate($productId: ID!, $input: TranslationInput!) { productTranslate(id: $productId, languageCode: PL, input: $input) { product { translation(languageCode: PL) { name description language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_product_create_translation( mocked_webhook_trigger, staff_api_client, product, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] product_id = graphene.Node.to_global_id("Product", product.id) response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, {"productId": product_id, "input": {"name": "Produkt PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] == "Produkt PL" assert data["product"]["translation"]["language"]["code"] == "PL" translation = product.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_product_create_translation_for_description( staff_api_client, product, permission_manage_translations ): product_id = graphene.Node.to_global_id("Product", product.id) description = dummy_editorjs("description", True) variables = {"productId": product_id, "input": {"description": description}} response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, variables, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] is None assert data["product"]["translation"]["description"] == description assert data["product"]["translation"]["language"]["code"] == "PL" def test_product_create_translation_for_description_and_name_as_null( staff_api_client, product, permission_manage_translations ): product_id = graphene.Node.to_global_id("Product", product.id) description = dummy_editorjs("description", True) variables = { "productId": product_id, "input": {"description": description, "name": None}, } response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, variables, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] is None assert data["product"]["translation"]["description"] == description assert data["product"]["translation"]["language"]["code"] == "PL" def test_product_create_translation_with_app( app_api_client, product, permission_manage_translations ): product_id = graphene.Node.to_global_id("Product", product.id) response = app_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, {"productId": product_id, "input": {"name": "Produkt PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] == "Produkt PL" assert data["product"]["translation"]["language"]["code"] == "PL" def test_product_create_translation_by_translatable_content_id( staff_api_client, product, permission_manage_translations ): translatable_content_id = graphene.Node.to_global_id( "ProductTranslatableContent", product.id ) response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, {"productId": translatable_content_id, "input": {"name": "Produkt PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] == "Produkt PL" assert data["product"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_product_update_translation( mocked_webhook_trigger, staff_api_client, product, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = product.translations.create(language_code="pl", name="Produkt") product_id = graphene.Node.to_global_id("Product", product.id) response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, {"productId": product_id, "input": {"name": "Produkt PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] == "Produkt PL" assert data["product"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) PRODUCT_VARIANT_TRANSLATE_MUTATION = """ mutation productVariantTranslate( $productVariantId: ID!, $input: NameTranslationInput! ) { productVariantTranslate( id: $productVariantId, languageCode: PL, input: $input) { productVariant { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_product_variant_create_translation( mocked_webhook_trigger, staff_api_client, variant, channel_USD, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) response = staff_api_client.post_graphql( PRODUCT_VARIANT_TRANSLATE_MUTATION, {"productVariantId": product_variant_id, "input": {"name": "Wariant PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productVariantTranslate"] assert data["productVariant"]["translation"]["name"] == "Wariant PL" assert data["productVariant"]["translation"]["language"]["code"] == "PL" translation = variant.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_product_variant_create_translation_by_translatable_content_id( staff_api_client, variant, channel_USD, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "ProductVariantTranslatableContent", variant.id ) response = staff_api_client.post_graphql( PRODUCT_VARIANT_TRANSLATE_MUTATION, {"productVariantId": translatable_content_id, "input": {"name": "Wariant PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productVariantTranslate"] assert data["productVariant"]["translation"]["name"] == "Wariant PL" assert data["productVariant"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_product_variant_update_translation( mocked_webhook_trigger, staff_api_client, variant, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = variant.translations.create(language_code="pl", name="Wariant") product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) response = staff_api_client.post_graphql( PRODUCT_VARIANT_TRANSLATE_MUTATION, {"productVariantId": product_variant_id, "input": {"name": "Wariant PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productVariantTranslate"] assert data["productVariant"]["translation"]["name"] == "Wariant PL" assert data["productVariant"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) COLLECTION_TRANSLATE_MUTATION = """ mutation collectionTranslate($collectionId: ID!, $input: TranslationInput!) { collectionTranslate( id: $collectionId, languageCode: PL, input: $input) { collection { translation(languageCode: PL) { name description language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_collection_create_translation( mocked_webhook_trigger, staff_api_client, published_collection, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] collection_id = graphene.Node.to_global_id("Collection", published_collection.id) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, {"collectionId": collection_id, "input": {"name": "Kolekcja PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] == "Kolekcja PL" assert data["collection"]["translation"]["language"]["code"] == "PL" translation = published_collection.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_collection_create_translation_by_translatable_content_id( staff_api_client, published_collection, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "CollectionTranslatableContent", published_collection.id ) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, {"collectionId": translatable_content_id, "input": {"name": "Kolekcja PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] == "Kolekcja PL" assert data["collection"]["translation"]["language"]["code"] == "PL" def test_collection_create_translation_for_description( staff_api_client, published_collection, permission_manage_translations ): collection_id = graphene.Node.to_global_id("Collection", published_collection.id) description = dummy_editorjs("description", True) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, {"collectionId": collection_id, "input": {"description": description}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] is None assert data["collection"]["translation"]["description"] == description assert data["collection"]["translation"]["language"]["code"] == "PL" def test_collection_create_translation_for_description_name_as_null( staff_api_client, published_collection, permission_manage_translations ): collection_id = graphene.Node.to_global_id("Collection", published_collection.id) description = dummy_editorjs("description", True) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, { "collectionId": collection_id, "input": {"description": description, "name": None}, }, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] is None assert data["collection"]["translation"]["description"] == description assert data["collection"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_collection_update_translation( mocked_webhook_trigger, staff_api_client, published_collection, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = published_collection.translations.create( language_code="pl", name="Kolekcja" ) collection_id = graphene.Node.to_global_id("Collection", published_collection.id) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, {"collectionId": collection_id, "input": {"name": "Kolekcja PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] == "Kolekcja PL" assert data["collection"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) CATEGORY_TRANSLATE_MUTATION = """ mutation categoryTranslate($categoryId: ID!, $input: TranslationInput!) { categoryTranslate( id: $categoryId, languageCode: PL, input: $input) { category { translation(languageCode: PL) { name description language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_category_create_translation( mocked_webhook_trigger, staff_api_client, category, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] category_id = graphene.Node.to_global_id("Category", category.id) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, {"categoryId": category_id, "input": {"name": "Kategoria PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] == "Kategoria PL" assert data["category"]["translation"]["language"]["code"] == "PL" translation = category.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_category_create_translation_by_translatable_content_id( staff_api_client, category, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "CategoryTranslatableContent", category.id ) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, {"categoryId": translatable_content_id, "input": {"name": "Kategoria PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] == "Kategoria PL" assert data["category"]["translation"]["language"]["code"] == "PL" def test_category_create_translation_for_description( staff_api_client, category, permission_manage_translations ): category_id = graphene.Node.to_global_id("Category", category.id) description = dummy_editorjs("description", True) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, {"categoryId": category_id, "input": {"description": description}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] is None assert data["category"]["translation"]["description"] == description assert data["category"]["translation"]["language"]["code"] == "PL" def test_category_create_translation_for_description_name_as_null( staff_api_client, category, permission_manage_translations ): category_id = graphene.Node.to_global_id("Category", category.id) description = dummy_editorjs("description", True) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, { "categoryId": category_id, "input": {"name": None, "description": description}, }, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] is None assert data["category"]["translation"]["description"] == description assert data["category"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_category_update_translation( mocked_webhook_trigger, staff_api_client, category, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = category.translations.create(language_code="pl", name="Kategoria") category_id = graphene.Node.to_global_id("Category", category.id) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, {"categoryId": category_id, "input": {"name": "Kategoria PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] == "Kategoria PL" assert data["category"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) VOUCHER_TRANSLATE_MUTATION = """ mutation voucherTranslate($voucherId: ID!) { voucherTranslate( id: $voucherId, languageCode: PL, input: {name: "Bon PL"}) { voucher { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_voucher_create_translation( mocked_webhook_trigger, staff_api_client, voucher, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) response = staff_api_client.post_graphql( VOUCHER_TRANSLATE_MUTATION, {"voucherId": voucher_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["voucherTranslate"] assert data["voucher"]["translation"]["name"] == "Bon PL" assert data["voucher"]["translation"]["language"]["code"] == "PL" translation = voucher.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_voucher_create_translation_by_translatable_content_id( staff_api_client, voucher, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "VoucherTranslatableContent", voucher.id ) response = staff_api_client.post_graphql( VOUCHER_TRANSLATE_MUTATION, {"voucherId": translatable_content_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["voucherTranslate"] assert data["voucher"]["translation"]["name"] == "Bon PL" assert data["voucher"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_voucher_update_translation( mocked_webhook_trigger, staff_api_client, voucher, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = voucher.translations.create(language_code="pl", name="Kategoria") voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) response = staff_api_client.post_graphql( VOUCHER_TRANSLATE_MUTATION, {"voucherId": voucher_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["voucherTranslate"] assert data["voucher"]["translation"]["name"] == "Bon PL" assert data["voucher"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) SALE_TRANSLATION_MUTATION = """ mutation saleTranslate($saleId: ID!) { saleTranslate( id: $saleId, languageCode: PL, input: {name: "Wyprz PL"}) { sale { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_sale_create_translation( mocked_webhook_trigger, staff_api_client, sale, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] sale_id = graphene.Node.to_global_id("Sale", sale.id) response = staff_api_client.post_graphql( SALE_TRANSLATION_MUTATION, {"saleId": sale_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["saleTranslate"] assert data["sale"]["translation"]["name"] == "Wyprz PL" assert data["sale"]["translation"]["language"]["code"] == "PL" translation = sale.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_sale_create_translation_by_translatable_content_id( staff_api_client, sale, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "SaleTranslatableContent", sale.id ) response = staff_api_client.post_graphql( SALE_TRANSLATION_MUTATION, {"saleId": translatable_content_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["saleTranslate"] assert data["sale"]["translation"]["name"] == "Wyprz PL" assert data["sale"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_sale_update_translation( mocked_webhook_trigger, staff_api_client, sale, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = sale.translations.create(language_code="pl", name="Sale") sale_id = graphene.Node.to_global_id("Sale", sale.id) response = staff_api_client.post_graphql( SALE_TRANSLATION_MUTATION, {"saleId": sale_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["saleTranslate"] assert data["sale"]["translation"]["name"] == "Wyprz PL" assert data["sale"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) PAGE_TRANSLATE_MUTATION = """ mutation pageTranslate($pageId: ID!, $input: PageTranslationInput!) { pageTranslate( id: $pageId, languageCode: PL, input: $input) { page { translation(languageCode: PL) { title content language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_page_create_translation( mocked_webhook_trigger, staff_api_client, page, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] page_id = graphene.Node.to_global_id("Page", page.id) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": page_id, "input": {"title": "Strona PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] == "Strona PL" assert data["page"]["translation"]["language"]["code"] == "PL" translation = page.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_page_create_translation_for_content( staff_api_client, page, permission_manage_translations ): page_id = graphene.Node.to_global_id("Page", page.id) content = dummy_editorjs("content", True) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": page_id, "input": {"content": content}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] is None assert data["page"]["translation"]["content"] == content assert data["page"]["translation"]["language"]["code"] == "PL" def test_page_create_translation_for_content_title_as_null( staff_api_client, page, permission_manage_translations ): page_id = graphene.Node.to_global_id("Page", page.id) content = dummy_editorjs("content", True) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": page_id, "input": {"title": None, "content": content}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] is None assert data["page"]["translation"]["content"] == content assert data["page"]["translation"]["language"]["code"] == "PL" def test_page_create_translation_by_translatable_content_id( staff_api_client, page, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "PageTranslatableContent", page.id ) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": translatable_content_id, "input": {"title": "Strona PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] == "Strona PL" assert data["page"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_page_update_translation( mocked_webhook_trigger, staff_api_client, page, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = page.translations.create(language_code="pl", title="Strona") page_id = graphene.Node.to_global_id("Page", page.id) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": page_id, "input": {"title": "Strona PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] == "Strona PL" assert data["page"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) ATTRIBUTE_TRANSLATE_MUTATION = """ mutation attributeTranslate($attributeId: ID!) { attributeTranslate( id: $attributeId, languageCode: PL, input: {name: "Kolor PL"} ) { attribute { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_attribute_create_translation( mocked_webhook_trigger, staff_api_client, color_attribute, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id) response = staff_api_client.post_graphql( ATTRIBUTE_TRANSLATE_MUTATION, {"attributeId": attribute_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeTranslate"] assert data["attribute"]["translation"]["name"] == "Kolor PL" assert data["attribute"]["translation"]["language"]["code"] == "PL" translation = color_attribute.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_attribute_create_translation_by_translatable_content_id( staff_api_client, color_attribute, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "Attribute", color_attribute.id ) response = staff_api_client.post_graphql( ATTRIBUTE_TRANSLATE_MUTATION, {"attributeId": translatable_content_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeTranslate"] assert data["attribute"]["translation"]["name"] == "Kolor PL" assert data["attribute"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_attribute_update_translation( mocked_webhook_trigger, staff_api_client, color_attribute, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = color_attribute.translations.create(language_code="pl", name="Kolor") attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id) response = staff_api_client.post_graphql( ATTRIBUTE_TRANSLATE_MUTATION, {"attributeId": attribute_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeTranslate"] assert data["attribute"]["translation"]["name"] == "Kolor PL" assert data["attribute"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) ATTRIBUTE_VALUE_TRANSLATE_MUTATION = """ mutation attributeValueTranslate($attributeValueId: ID!, $name: String) { attributeValueTranslate( id: $attributeValueId, languageCode: PL, input: { name: $name } ) { attributeValue { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_attribute_value_create_translation( mocked_webhook_trigger, staff_api_client, pink_attribute_value, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) response = staff_api_client.post_graphql( ATTRIBUTE_VALUE_TRANSLATE_MUTATION, {"attributeValueId": attribute_value_id, "name": "Róż PL"}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeValueTranslate"] assert data["attributeValue"]["translation"]["name"] == "Róż PL" assert data["attributeValue"]["translation"]["language"]["code"] == "PL" translation = pink_attribute_value.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_attribute_value_create_translation_by_translatable_content_id( staff_api_client, pink_attribute_value, permission_manage_translations ): translatable_content_id = graphene.Node.to_global_id( "AttributeValueTranslatableContent", pink_attribute_value.id ) response = staff_api_client.post_graphql( ATTRIBUTE_VALUE_TRANSLATE_MUTATION, {"attributeValueId": translatable_content_id, "name": "Róż PL"}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeValueTranslate"] assert data["attributeValue"]["translation"]["name"] == "Róż PL" assert data["attributeValue"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_attribute_value_update_translation( mocked_webhook_trigger, staff_api_client, pink_attribute_value, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = pink_attribute_value.translations.create( language_code="pl", name="Różowy" ) attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) response = staff_api_client.post_graphql( ATTRIBUTE_VALUE_TRANSLATE_MUTATION, {"attributeValueId": attribute_value_id, "name": "Róż PL"}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeValueTranslate"] assert data["attributeValue"]["translation"]["name"] == "Róż PL" assert data["attributeValue"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) SHIPPING_PRICE_TRANSLATE = """ mutation shippingPriceTranslate( $shippingMethodId: ID!, $input: ShippingPriceTranslationInput! ) { shippingPriceTranslate( id: $shippingMethodId, languageCode: PL, input: $input ) { shippingMethod { translation(languageCode: PL) { name description language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_shipping_method_create_translation( mocked_webhook_trigger, staff_api_client, shipping_method, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] shipping_method_id = graphene.Node.to_global_id( "ShippingMethod", shipping_method.id ) description = dummy_editorjs("description", True) variables = { "shippingMethodId": shipping_method_id, "input": {"name": "DHL PL", "description": description}, } response = staff_api_client.post_graphql( SHIPPING_PRICE_TRANSLATE, variables, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["shippingPriceTranslate"] assert data["shippingMethod"]["translation"]["name"] == "DHL PL" assert data["shippingMethod"]["translation"]["description"] == description assert data["shippingMethod"]["translation"]["language"]["code"] == "PL" translation = shipping_method.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_shipping_method_create_translation_by_translatable_content_id( staff_api_client, shipping_method, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "ShippingMethodTranslatableContent", shipping_method.id ) description = dummy_editorjs("description", True) variables = { "shippingMethodId": translatable_content_id, "input": {"name": "DHL PL", "description": description}, } response = staff_api_client.post_graphql( SHIPPING_PRICE_TRANSLATE, variables, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["shippingPriceTranslate"] assert data["shippingMethod"]["translation"]["name"] == "DHL PL" assert data["shippingMethod"]["translation"]["description"] == description assert data["shippingMethod"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_shipping_method_update_translation( mocked_webhook_trigger, staff_api_client, shipping_method, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = shipping_method.translations.create(language_code="pl", name="DHL") query = """ mutation shippingPriceTranslate($shippingMethodId: ID!) { shippingPriceTranslate( id: $shippingMethodId, languageCode: PL, input: {name: "DHL PL"}) { shippingMethod { translation(languageCode: PL) { name language { code } } } } } """ shipping_method_id = graphene.Node.to_global_id( "ShippingMethod", shipping_method.id ) response = staff_api_client.post_graphql( query, {"shippingMethodId": shipping_method_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["shippingPriceTranslate"] assert data["shippingMethod"]["translation"]["name"] == "DHL PL" assert data["shippingMethod"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) MENU_ITEM_TRANSLATE = """ mutation menuItemTranslate($menuItemId: ID!) { menuItemTranslate( id: $menuItemId, languageCode: PL, input: {name: "Odnośnik PL"} ) { menuItem { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_menu_item_update_translation( mocked_webhook_trigger, staff_api_client, menu_item, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = menu_item.translations.create(language_code="pl", name="Odnośnik") translatable_content_id = graphene.Node.to_global_id( "MenuItemTranslatableContent", menu_item.id ) response = staff_api_client.post_graphql( MENU_ITEM_TRANSLATE, {"menuItemId": translatable_content_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["menuItemTranslate"] assert data["menuItem"]["translation"]["name"] == "Odnośnik PL" assert data["menuItem"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) def test_menu_item_create_translation_by_translatable_content_id( staff_api_client, menu_item, permission_manage_translations, ): menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) response = staff_api_client.post_graphql( MENU_ITEM_TRANSLATE, {"menuItemId": menu_item_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["menuItemTranslate"] assert data["menuItem"]["translation"]["name"] == "Odnośnik PL" assert data["menuItem"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_shop_create_translation( mocked_webhook_trigger, staff_api_client, site_settings, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] query = """ mutation shopSettingsTranslate { shopSettingsTranslate( languageCode: PL, input: {headerText: "Nagłówek PL"}) { shop { translation(languageCode: PL) { headerText language { code } } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"]["shopSettingsTranslate"] assert data["shop"]["translation"]["headerText"] == "Nagłówek PL" assert data["shop"]["translation"]["language"]["code"] == "PL" translation = site_settings.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_shop_update_translation( mocked_webhook_trigger, staff_api_client, site_settings, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = site_settings.translations.create( language_code="pl", header_text="Nagłówek" ) query = """ mutation shopSettingsTranslate { shopSettingsTranslate( languageCode: PL, input: {headerText: "Nagłówek PL"}) { shop { translation(languageCode: PL) { headerText language { code } } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"]["shopSettingsTranslate"] assert data["shop"]["translation"]["headerText"] == "Nagłówek PL" assert data["shop"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) @pytest.mark.parametrize( "kind, expected_typename", [ (TranslatableKinds.PRODUCT, "ProductTranslatableContent"), (TranslatableKinds.COLLECTION, "CollectionTranslatableContent"), (TranslatableKinds.CATEGORY, "CategoryTranslatableContent"), (TranslatableKinds.PAGE, "PageTranslatableContent"), (TranslatableKinds.SHIPPING_METHOD, "ShippingMethodTranslatableContent"), (TranslatableKinds.VOUCHER, "VoucherTranslatableContent"), (TranslatableKinds.SALE, "SaleTranslatableContent"), (TranslatableKinds.ATTRIBUTE, "AttributeTranslatableContent"), (TranslatableKinds.ATTRIBUTE_VALUE, "AttributeValueTranslatableContent"), (TranslatableKinds.VARIANT, "ProductVariantTranslatableContent"), (TranslatableKinds.MENU_ITEM, "MenuItemTranslatableContent"), ], ) def test_translations_query( staff_api_client, permission_manage_translations, product, published_collection, voucher, sale, shipping_method, page, menu_item, kind, expected_typename, ): query = """ query TranslationsQuery($kind: TranslatableKinds!) { translations(kind: $kind, first: 1) { edges { node { __typename } } totalCount } } """ response = staff_api_client.post_graphql( query, {"kind": kind.name}, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"]["translations"] assert data["edges"][0]["node"]["__typename"] == expected_typename assert data["totalCount"] > 0 def test_translations_query_inline_fragment( staff_api_client, permission_manage_translations, product ): product.translations.create(language_code="pl", name="Produkt testowy") query = """ { translations(kind: PRODUCT, first: 1) { edges { node { ... on ProductTranslatableContent { name translation(languageCode: PL) { name } } } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"]["translations"]["edges"][0] assert data["node"]["name"] == "Test product" assert data["node"]["translation"]["name"] == "Produkt testowy" QUERY_TRANSLATION_PRODUCT = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on ProductTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_product( staff_api_client, permission_manage_translations, product, product_translation_fr, ): product_id = graphene.Node.to_global_id("Product", product.id) variables = { "id": product_id, "kind": TranslatableKinds.PRODUCT.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_PRODUCT, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == product.name assert data["translation"]["name"] == product_translation_fr.name QUERY_TRANSLATION_COLLECTION = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on CollectionTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_collection( staff_api_client, published_collection, collection_translation_fr, permission_manage_translations, channel_USD, ): channel_listing = published_collection.channel_listings.get() channel_listing.save() collection_id = graphene.Node.to_global_id("Collection", published_collection.id) variables = { "id": collection_id, "kind": TranslatableKinds.COLLECTION.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_COLLECTION, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == published_collection.name assert data["translation"]["name"] == collection_translation_fr.name QUERY_TRANSLATION_CATEGORY = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on CategoryTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_category( staff_api_client, category, category_translation_fr, permission_manage_translations ): category_id = graphene.Node.to_global_id("Category", category.id) variables = { "id": category_id, "kind": TranslatableKinds.CATEGORY.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_CATEGORY, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == category.name assert data["translation"]["name"] == category_translation_fr.name QUERY_TRANSLATION_ATTRIBUTE = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on AttributeTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_attribute( staff_api_client, translated_attribute, permission_manage_translations ): attribute = translated_attribute.attribute attribute_id = graphene.Node.to_global_id("Attribute", attribute.id) variables = { "id": attribute_id, "kind": TranslatableKinds.ATTRIBUTE.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_ATTRIBUTE, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == attribute.name assert data["translation"]["name"] == translated_attribute.name QUERY_TRANSLATION_ATTRIBUTE_VALUE = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on AttributeValueTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_attribute_value( staff_api_client, pink_attribute_value, translated_attribute_value, permission_manage_translations, ): attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) variables = { "id": attribute_value_id, "kind": TranslatableKinds.ATTRIBUTE_VALUE.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_ATTRIBUTE_VALUE, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == pink_attribute_value.name assert data["translation"]["name"] == translated_attribute_value.name QUERY_TRANSLATION_VARIANT = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on ProductVariantTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_variant( staff_api_client, permission_manage_translations, product, variant, variant_translation_fr, ): variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) variables = { "id": variant_id, "kind": TranslatableKinds.VARIANT.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_VARIANT, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == variant.name assert data["translation"]["name"] == variant_translation_fr.name QUERY_TRANSLATION_PAGE = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on PageTranslatableContent{ id title translation(languageCode: $languageCode){ title } } } } """ @pytest.mark.parametrize( "is_published, perm_codenames", [ (True, ["manage_translations"]), (False, ["manage_translations"]), (False, ["manage_translations", "manage_pages"]), ], ) def test_translation_query_page( staff_api_client, page, page_translation_fr, is_published, perm_codenames, ): page.is_published = is_published page.save() page_id = graphene.Node.to_global_id("Page", page.id) perms = list(Permission.objects.filter(codename__in=perm_codenames)) variables = { "id": page_id, "kind": TranslatableKinds.PAGE.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_PAGE, variables, permissions=perms ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["title"] == page.title assert data["translation"]["title"] == page_translation_fr.title QUERY_TRANSLATION_SHIPPING_METHOD = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on ShippingMethodTranslatableContent{ id name description translation(languageCode: $languageCode){ name } } } } """ @pytest.mark.parametrize( "perm_codenames, return_shipping_method", [ (["manage_translations"], False), (["manage_translations", "manage_shipping"], True), ], ) def test_translation_query_shipping_method( staff_api_client, shipping_method, shipping_method_translation_fr, perm_codenames, return_shipping_method, ): shipping_method_id = graphene.Node.to_global_id( "ShippingMethod", shipping_method.id ) perms = list(Permission.objects.filter(codename__in=perm_codenames)) variables = { "id": shipping_method_id, "kind": TranslatableKinds.SHIPPING_METHOD.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_SHIPPING_METHOD, variables, permissions=perms ) content = get_graphql_content(response, ignore_errors=True) data = content["data"]["translation"] assert data["name"] == shipping_method.name assert data["description"] == shipping_method.description assert data["translation"]["name"] == shipping_method_translation_fr.name QUERY_TRANSLATION_SALE = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on SaleTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ @pytest.mark.parametrize( "perm_codenames, return_sale", [ (["manage_translations"], False), (["manage_translations", "manage_discounts"], True), ], ) def test_translation_query_sale( staff_api_client, sale, sale_translation_fr, perm_codenames, return_sale ): sale_id = graphene.Node.to_global_id("Sale", sale.id) perms = list(Permission.objects.filter(codename__in=perm_codenames)) variables = { "id": sale_id, "kind": TranslatableKinds.SALE.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_SALE, variables, permissions=perms ) content = get_graphql_content(response, ignore_errors=True) data = content["data"]["translation"] assert data["name"] == sale.name assert data["translation"]["name"] == sale_translation_fr.name QUERY_TRANSLATION_VOUCHER = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on VoucherTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ @pytest.mark.parametrize( "perm_codenames, return_voucher", [ (["manage_translations"], False), (["manage_translations", "manage_discounts"], True), ], ) def test_translation_query_voucher( staff_api_client, voucher, voucher_translation_fr, perm_codenames, return_voucher ): voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) perms = list(Permission.objects.filter(codename__in=perm_codenames)) variables = { "id": voucher_id, "kind": TranslatableKinds.VOUCHER.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_VOUCHER, variables, permissions=perms ) content = get_graphql_content(response, ignore_errors=True) data = content["data"]["translation"] assert data["name"] == voucher.name assert data["translation"]["name"] == voucher_translation_fr.name QUERY_TRANSLATION_MENU_ITEM = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on MenuItemTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_menu_item( staff_api_client, menu_item, menu_item_translation_fr, permission_manage_translations, ): menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) variables = { "id": menu_item_id, "kind": TranslatableKinds.MENU_ITEM.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_MENU_ITEM, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == menu_item.name assert data["translation"]["name"] == menu_item_translation_fr.name def test_translation_query_incorrect_kind( staff_api_client, menu_item, permission_manage_translations ): menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) variables = { "id": menu_item_id, "kind": TranslatableKinds.PRODUCT.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_MENU_ITEM, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) assert not content["data"]["translation"] def test_translation_query_no_permission(staff_api_client, menu_item): menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) variables = { "id": menu_item_id, "kind": TranslatableKinds.MENU_ITEM.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql(QUERY_TRANSLATION_MENU_ITEM, variables) assert_no_permission(response) def test_product_and_attribute_translation(user_api_client, product, channel_USD): description = dummy_editorjs("test desription") product.translations.create( language_code="pl", name="Produkt", description=description ) assigned_attribute = product.attributes.first() attribute = assigned_attribute.attribute attribute.translations.create(language_code="pl", name="Kolor") query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } attributes{ attribute{ translation(languageCode: PL){ id name language{ code } } } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = user_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] product_translation_data = data["product"]["translation"] assert product_translation_data["name"] == "Produkt" assert product_translation_data["language"]["code"] == "PL" assert ( product_translation_data["description"] == product_translation_data["descriptionJson"] == dummy_editorjs("test desription", json_format=True) ) attribute_translation_data = data["product"]["attributes"][0]["attribute"][ "translation" ] assert attribute_translation_data["name"] == "Kolor" assert attribute_translation_data["language"]["code"] == "PL" def test_product_attribute_value_rich_text_translation( staff_api_client, product_with_rich_text_attribute, permission_manage_translations, ): rich_text = dummy_editorjs("Test_dummy_data") assigned_attribute = product_with_rich_text_attribute[0].attributes.first() attribute_value = assigned_attribute.attribute.values.first() attribute_value.translations.create(language_code="pl", rich_text=rich_text) product_id = graphene.Node.to_global_id( "Product", product_with_rich_text_attribute[0].id ) query = """ query translation( $kind: TranslatableKinds! $id: ID! $languageCode: LanguageCodeEnum! ) { translation(kind: $kind, id: $id) { ... on ProductTranslatableContent { name attributeValues { name richText translation(languageCode: $languageCode) { name richText } } } } } """ variables = { "id": product_id, "kind": TranslatableKinds.PRODUCT.name, "languageCode": LanguageCodeEnum.PL.name, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"] attribute_value_response = data["translation"]["attributeValues"][0] assert attribute_value_response["name"] == attribute_value.name assert attribute_value_response["richText"] == json.dumps(attribute_value.rich_text) assert attribute_value_response["translation"]["richText"] == json.dumps(rich_text) def test_product_variant_attribute_value_rich_text_translation( staff_api_client, product_with_rich_text_attribute, permission_manage_translations, product_type_with_rich_text_attribute, ): rich_text = dummy_editorjs("Test_dummy_data") variant_attr = product_type_with_rich_text_attribute.variant_attributes.first() attribute_value = variant_attr.values.first() attribute_value.translations.create(language_code="pl", rich_text=rich_text) variant_id = graphene.Node.to_global_id( "ProductVariant", product_with_rich_text_attribute[1].id ) query = """ query translation( $kind: TranslatableKinds! $id: ID! $languageCode: LanguageCodeEnum! ) { translation(kind: $kind, id: $id) { ... on ProductVariantTranslatableContent { name attributeValues { name richText translation(languageCode: $languageCode) { name richText } } } } } """ variables = { "id": variant_id, "kind": TranslatableKinds.VARIANT.name, "languageCode": LanguageCodeEnum.PL.name, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"] translations_response = data["translation"]["attributeValues"][0] assert translations_response["name"] == attribute_value.name assert translations_response["richText"] == json.dumps(attribute_value.rich_text) assert translations_response["translation"]["richText"] == json.dumps(rich_text) def test_page_attribute_value_rich_text_translation( staff_api_client, page_with_rich_text_attribute, permission_manage_translations, page_type_with_rich_text_attribute, permission_manage_pages, ): rich_text = dummy_editorjs("Test_dummy_data") variant_attr = page_type_with_rich_text_attribute.page_attributes.first() attribute_value = variant_attr.values.first() attribute_value.translations.create(language_code="pl", rich_text=rich_text) page_id = graphene.Node.to_global_id("Page", page_with_rich_text_attribute.id) query = """ query translation( $kind: TranslatableKinds! $id: ID! $languageCode: LanguageCodeEnum! ) { translation(kind: $kind, id: $id) { ... on PageTranslatableContent { attributeValues { name richText translation(languageCode: $languageCode) { name richText } } } } } """ variables = { "id": page_id, "kind": TranslatableKinds.PAGE.name, "languageCode": LanguageCodeEnum.PL.name, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"] attribute_value_response = data["translation"]["attributeValues"][0] assert attribute_value_response["name"] == attribute_value.name assert attribute_value_response["richText"] == json.dumps(attribute_value.rich_text) assert attribute_value_response["translation"]["richText"] == json.dumps(rich_text)
32.526583
88
0.641316
import json from unittest.mock import patch import graphene import pytest from django.contrib.auth.models import Permission from freezegun import freeze_time from ....tests.utils import dummy_editorjs from ....webhook.event_types import WebhookEventAsyncType from ....webhook.payloads import generate_translation_payload from ...core.enums import LanguageCodeEnum from ...tests.utils import assert_no_permission, get_graphql_content from ..schema import TranslatableKinds def test_product_translation(user_api_client, product, channel_USD): description = dummy_editorjs("test desription") product.translations.create( language_code="pl", name="Produkt", description=description ) query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = user_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] translation_data = data["product"]["translation"] assert translation_data["name"] == "Produkt" assert translation_data["language"]["code"] == "PL" assert ( translation_data["description"] == translation_data["descriptionJson"] == dummy_editorjs("test desription", json_format=True) ) def test_product_translation_without_description(user_api_client, product, channel_USD): product.translations.create(language_code="pl", name="Produkt") query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = user_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] translation_data = data["product"]["translation"] assert translation_data["name"] == "Produkt" assert translation_data["language"]["code"] == "PL" assert translation_data["description"] is None assert translation_data["descriptionJson"] == "{}" def test_product_translation_with_app(app_api_client, product, channel_USD): product.translations.create(language_code="pl", name="Produkt") query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = app_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] assert data["product"]["translation"]["name"] == "Produkt" assert data["product"]["translation"]["language"]["code"] == "PL" def test_product_variant_translation(user_api_client, variant, channel_USD): variant.translations.create(language_code="pl", name="Wariant") query = """ query productVariantById($productVariantId: ID!, $channel: String) { productVariant(id: $productVariantId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) response = user_api_client.post_graphql( query, {"productVariantId": product_variant_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] assert data["productVariant"]["translation"]["name"] == "Wariant" assert data["productVariant"]["translation"]["language"]["code"] == "PL" def test_collection_translation(user_api_client, published_collection, channel_USD): description = dummy_editorjs("test desription") published_collection.translations.create( language_code="pl", name="Kolekcja", description=description ) query = """ query collectionById($collectionId: ID!, $channel: String) { collection(id: $collectionId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ collection_id = graphene.Node.to_global_id("Collection", published_collection.id) variables = {"collectionId": collection_id, "channel": channel_USD.slug} response = user_api_client.post_graphql(query, variables) data = get_graphql_content(response)["data"] translation_data = data["collection"]["translation"] assert translation_data["name"] == "Kolekcja" assert translation_data["language"]["code"] == "PL" assert ( translation_data["description"] == translation_data["descriptionJson"] == dummy_editorjs("test desription", json_format=True) ) def test_collection_translation_without_description( user_api_client, published_collection, channel_USD ): published_collection.translations.create(language_code="pl", name="Kolekcja") query = """ query collectionById($collectionId: ID!, $channel: String) { collection(id: $collectionId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ collection_id = graphene.Node.to_global_id("Collection", published_collection.id) variables = {"collectionId": collection_id, "channel": channel_USD.slug} response = user_api_client.post_graphql(query, variables) data = get_graphql_content(response)["data"] translation_data = data["collection"]["translation"] assert translation_data["name"] == "Kolekcja" assert translation_data["language"]["code"] == "PL" assert translation_data["description"] is None assert translation_data["descriptionJson"] == "{}" def test_category_translation(user_api_client, category): description = dummy_editorjs("test description") category.translations.create( language_code="pl", name="Kategoria", description=description ) query = """ query categoryById($categoryId: ID!) { category(id: $categoryId) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ category_id = graphene.Node.to_global_id("Category", category.id) response = user_api_client.post_graphql(query, {"categoryId": category_id}) data = get_graphql_content(response)["data"] translation_data = data["category"]["translation"] assert translation_data["name"] == "Kategoria" assert translation_data["language"]["code"] == "PL" assert ( translation_data["description"] == translation_data["descriptionJson"] == dummy_editorjs("test description", json_format=True) ) def test_category_translation_without_description(user_api_client, category): category.translations.create(language_code="pl", name="Kategoria") query = """ query categoryById($categoryId: ID!) { category(id: $categoryId) { translation(languageCode: PL) { name description descriptionJson language { code } } } } """ category_id = graphene.Node.to_global_id("Category", category.id) response = user_api_client.post_graphql(query, {"categoryId": category_id}) data = get_graphql_content(response)["data"] translation_data = data["category"]["translation"] assert translation_data["name"] == "Kategoria" assert translation_data["language"]["code"] == "PL" assert translation_data["description"] is None assert translation_data["descriptionJson"] == "{}" def test_voucher_translation(staff_api_client, voucher, permission_manage_discounts): voucher.translations.create(language_code="pl", name="Bon") query = """ query voucherById($voucherId: ID!) { voucher(id: $voucherId) { translation(languageCode: PL) { name language { code } } } } """ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) response = staff_api_client.post_graphql( query, {"voucherId": voucher_id}, permissions=[permission_manage_discounts] ) data = get_graphql_content(response)["data"] assert data["voucher"]["translation"]["name"] == "Bon" assert data["voucher"]["translation"]["language"]["code"] == "PL" def test_sale_translation(staff_api_client, sale, permission_manage_discounts): sale.translations.create(language_code="pl", name="Wyprz") query = """ query saleById($saleId: ID!) { sale(id: $saleId) { translation(languageCode: PL) { name language { code } } } } """ sale_id = graphene.Node.to_global_id("Sale", sale.id) response = staff_api_client.post_graphql( query, {"saleId": sale_id}, permissions=[permission_manage_discounts] ) data = get_graphql_content(response)["data"] assert data["sale"]["translation"]["name"] == "Wyprz" assert data["sale"]["translation"]["language"]["code"] == "PL" def test_page_translation(user_api_client, page): content = dummy_editorjs("test content") page.translations.create(language_code="pl", title="Strona", content=content) query = """ query pageById($pageId: ID!) { page(id: $pageId) { translation(languageCode: PL) { title content contentJson language { code } } } } """ page_id = graphene.Node.to_global_id("Page", page.id) response = user_api_client.post_graphql(query, {"pageId": page_id}) data = get_graphql_content(response)["data"] translation_data = data["page"]["translation"] assert translation_data["title"] == "Strona" assert translation_data["language"]["code"] == "PL" assert ( translation_data["content"] == translation_data["contentJson"] == dummy_editorjs("test content", json_format=True) ) def test_page_translation_without_content(user_api_client, page): page.translations.create(language_code="pl", title="Strona") query = """ query pageById($pageId: ID!) { page(id: $pageId) { translation(languageCode: PL) { title content contentJson language { code } } } } """ page_id = graphene.Node.to_global_id("Page", page.id) response = user_api_client.post_graphql(query, {"pageId": page_id}) data = get_graphql_content(response)["data"] translation_data = data["page"]["translation"] assert translation_data["title"] == "Strona" assert translation_data["language"]["code"] == "PL" assert translation_data["content"] is None assert translation_data["contentJson"] == "{}" def test_attribute_translation(user_api_client, color_attribute): color_attribute.translations.create(language_code="pl", name="Kolor") query = """ query { attributes(first: 1) { edges { node { translation(languageCode: PL) { name language { code } } } } } } """ response = user_api_client.post_graphql(query) data = get_graphql_content(response)["data"] attribute = data["attributes"]["edges"][0]["node"] assert attribute["translation"]["name"] == "Kolor" assert attribute["translation"]["language"]["code"] == "PL" def test_attribute_value_translation(user_api_client, pink_attribute_value): pink_attribute_value.translations.create( language_code="pl", name="Różowy", rich_text=dummy_editorjs("Pink") ) query = """ query { attributes(first: 1) { edges { node { choices(first: 10) { edges { node { translation(languageCode: PL) { name richText language { code } } } } } } } } } """ attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) response = user_api_client.post_graphql( query, {"attributeValueId": attribute_value_id} ) data = get_graphql_content(response)["data"] attribute_value = data["attributes"]["edges"][0]["node"]["choices"]["edges"][-1][ "node" ] assert attribute_value["translation"]["name"] == "Różowy" assert attribute_value["translation"]["richText"] == json.dumps( dummy_editorjs("Pink") ) assert attribute_value["translation"]["language"]["code"] == "PL" def test_shipping_method_translation( staff_api_client, shipping_method, permission_manage_shipping ): shipping_method.translations.create(language_code="pl", name="DHL Polska") query = """ query shippingZoneById($shippingZoneId: ID!) { shippingZone(id: $shippingZoneId) { shippingMethods { translation(languageCode: PL) { name language { code } } } } } """ shipping_zone_id = graphene.Node.to_global_id( "ShippingZone", shipping_method.shipping_zone.id ) response = staff_api_client.post_graphql( query, {"shippingZoneId": shipping_zone_id}, permissions=[permission_manage_shipping], ) data = get_graphql_content(response)["data"] shipping_method = data["shippingZone"]["shippingMethods"][-1] assert shipping_method["translation"]["name"] == "DHL Polska" assert shipping_method["translation"]["language"]["code"] == "PL" def test_menu_item_translation(user_api_client, menu_item): menu_item.translations.create(language_code="pl", name="Odnośnik 1") query = """ query menuItemById($menuItemId: ID!) { menuItem(id: $menuItemId) { translation(languageCode: PL) { name language { code } } } } """ menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) response = user_api_client.post_graphql(query, {"menuItemId": menu_item_id}) data = get_graphql_content(response)["data"] assert data["menuItem"]["translation"]["name"] == "Odnośnik 1" assert data["menuItem"]["translation"]["language"]["code"] == "PL" def test_shop_translation(user_api_client, site_settings): site_settings.translations.create(language_code="pl", header_text="Nagłówek") query = """ query { shop { translation(languageCode: PL) { headerText language { code } } } } """ response = user_api_client.post_graphql(query) data = get_graphql_content(response)["data"] assert data["shop"]["translation"]["headerText"] == "Nagłówek" assert data["shop"]["translation"]["language"]["code"] == "PL" def test_product_no_translation(user_api_client, product, channel_USD): query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = user_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] assert data["product"]["translation"] is None def test_product_variant_no_translation(user_api_client, variant, channel_USD): query = """ query productVariantById($productVariantId: ID!, $channel: String) { productVariant(id: $productVariantId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) response = user_api_client.post_graphql( query, {"productVariantId": product_variant_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] assert data["productVariant"]["translation"] is None def test_collection_no_translation(user_api_client, published_collection, channel_USD): query = """ query collectionById($collectionId: ID!, $channel: String) { collection(id: $collectionId, channel: $channel) { translation(languageCode: PL) { name language { code } } } } """ collection_id = graphene.Node.to_global_id("Collection", published_collection.id) variables = {"collectionId": collection_id, "channel": channel_USD.slug} response = user_api_client.post_graphql(query, variables) data = get_graphql_content(response)["data"] assert data["collection"]["translation"] is None def test_category_no_translation(user_api_client, category): query = """ query categoryById($categoryId: ID!) { category(id: $categoryId) { translation(languageCode: PL) { name language { code } } } } """ category_id = graphene.Node.to_global_id("Category", category.id) response = user_api_client.post_graphql(query, {"categoryId": category_id}) data = get_graphql_content(response)["data"] assert data["category"]["translation"] is None def test_voucher_no_translation(staff_api_client, voucher, permission_manage_discounts): query = """ query voucherById($voucherId: ID!) { voucher(id: $voucherId) { translation(languageCode: PL) { name language { code } } } } """ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) response = staff_api_client.post_graphql( query, {"voucherId": voucher_id}, permissions=[permission_manage_discounts] ) data = get_graphql_content(response)["data"] assert data["voucher"]["translation"] is None def test_page_no_translation(user_api_client, page): query = """ query pageById($pageId: ID!) { page(id: $pageId) { translation(languageCode: PL) { title language { code } } } } """ page_id = graphene.Node.to_global_id("Page", page.id) response = user_api_client.post_graphql(query, {"pageId": page_id}) data = get_graphql_content(response)["data"] assert data["page"]["translation"] is None def test_attribute_no_translation(user_api_client, color_attribute): query = """ query { attributes(first: 1) { edges { node { translation(languageCode: PL) { name language { code } } } } } } """ response = user_api_client.post_graphql(query) data = get_graphql_content(response)["data"] attribute = data["attributes"]["edges"][0]["node"] assert attribute["translation"] is None def test_attribute_value_no_translation(user_api_client, pink_attribute_value): query = """ query { attributes(first: 1) { edges { node { choices(first: 10) { edges { node { translation(languageCode: PL) { name language { code } } } } } } } } } """ attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) response = user_api_client.post_graphql( query, {"attributeValueId": attribute_value_id} ) data = get_graphql_content(response)["data"] attribute_value = data["attributes"]["edges"][0]["node"]["choices"]["edges"][-1][ "node" ] assert attribute_value["translation"] is None def test_shipping_method_no_translation( staff_api_client, shipping_method, permission_manage_shipping ): query = """ query shippingZoneById($shippingZoneId: ID!) { shippingZone(id: $shippingZoneId) { shippingMethods { translation(languageCode: PL) { name language { code } } } } } """ shipping_zone_id = graphene.Node.to_global_id( "ShippingZone", shipping_method.shipping_zone.id ) response = staff_api_client.post_graphql( query, {"shippingZoneId": shipping_zone_id}, permissions=[permission_manage_shipping], ) data = get_graphql_content(response)["data"] shipping_method = data["shippingZone"]["shippingMethods"][0] assert shipping_method["translation"] is None def test_menu_item_no_translation(user_api_client, menu_item): query = """ query menuItemById($menuItemId: ID!) { menuItem(id: $menuItemId) { translation(languageCode: PL) { name language { code } } } } """ menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) response = user_api_client.post_graphql(query, {"menuItemId": menu_item_id}) data = get_graphql_content(response)["data"] assert data["menuItem"]["translation"] is None def test_shop_no_translation(user_api_client, site_settings): query = """ query { shop { translation(languageCode: PL) { headerText language { code } } } } """ response = user_api_client.post_graphql(query) data = get_graphql_content(response)["data"] assert data["shop"]["translation"] is None PRODUCT_TRANSLATE_MUTATION = """ mutation productTranslate($productId: ID!, $input: TranslationInput!) { productTranslate(id: $productId, languageCode: PL, input: $input) { product { translation(languageCode: PL) { name description language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_product_create_translation( mocked_webhook_trigger, staff_api_client, product, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] product_id = graphene.Node.to_global_id("Product", product.id) response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, {"productId": product_id, "input": {"name": "Produkt PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] == "Produkt PL" assert data["product"]["translation"]["language"]["code"] == "PL" translation = product.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_product_create_translation_for_description( staff_api_client, product, permission_manage_translations ): product_id = graphene.Node.to_global_id("Product", product.id) description = dummy_editorjs("description", True) variables = {"productId": product_id, "input": {"description": description}} response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, variables, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] is None assert data["product"]["translation"]["description"] == description assert data["product"]["translation"]["language"]["code"] == "PL" def test_product_create_translation_for_description_and_name_as_null( staff_api_client, product, permission_manage_translations ): product_id = graphene.Node.to_global_id("Product", product.id) description = dummy_editorjs("description", True) variables = { "productId": product_id, "input": {"description": description, "name": None}, } response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, variables, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] is None assert data["product"]["translation"]["description"] == description assert data["product"]["translation"]["language"]["code"] == "PL" def test_product_create_translation_with_app( app_api_client, product, permission_manage_translations ): product_id = graphene.Node.to_global_id("Product", product.id) response = app_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, {"productId": product_id, "input": {"name": "Produkt PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] == "Produkt PL" assert data["product"]["translation"]["language"]["code"] == "PL" def test_product_create_translation_by_translatable_content_id( staff_api_client, product, permission_manage_translations ): translatable_content_id = graphene.Node.to_global_id( "ProductTranslatableContent", product.id ) response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, {"productId": translatable_content_id, "input": {"name": "Produkt PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] == "Produkt PL" assert data["product"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_product_update_translation( mocked_webhook_trigger, staff_api_client, product, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = product.translations.create(language_code="pl", name="Produkt") product_id = graphene.Node.to_global_id("Product", product.id) response = staff_api_client.post_graphql( PRODUCT_TRANSLATE_MUTATION, {"productId": product_id, "input": {"name": "Produkt PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productTranslate"] assert data["product"]["translation"]["name"] == "Produkt PL" assert data["product"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) PRODUCT_VARIANT_TRANSLATE_MUTATION = """ mutation productVariantTranslate( $productVariantId: ID!, $input: NameTranslationInput! ) { productVariantTranslate( id: $productVariantId, languageCode: PL, input: $input) { productVariant { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_product_variant_create_translation( mocked_webhook_trigger, staff_api_client, variant, channel_USD, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) response = staff_api_client.post_graphql( PRODUCT_VARIANT_TRANSLATE_MUTATION, {"productVariantId": product_variant_id, "input": {"name": "Wariant PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productVariantTranslate"] assert data["productVariant"]["translation"]["name"] == "Wariant PL" assert data["productVariant"]["translation"]["language"]["code"] == "PL" translation = variant.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_product_variant_create_translation_by_translatable_content_id( staff_api_client, variant, channel_USD, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "ProductVariantTranslatableContent", variant.id ) response = staff_api_client.post_graphql( PRODUCT_VARIANT_TRANSLATE_MUTATION, {"productVariantId": translatable_content_id, "input": {"name": "Wariant PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productVariantTranslate"] assert data["productVariant"]["translation"]["name"] == "Wariant PL" assert data["productVariant"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_product_variant_update_translation( mocked_webhook_trigger, staff_api_client, variant, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = variant.translations.create(language_code="pl", name="Wariant") product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) response = staff_api_client.post_graphql( PRODUCT_VARIANT_TRANSLATE_MUTATION, {"productVariantId": product_variant_id, "input": {"name": "Wariant PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["productVariantTranslate"] assert data["productVariant"]["translation"]["name"] == "Wariant PL" assert data["productVariant"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) COLLECTION_TRANSLATE_MUTATION = """ mutation collectionTranslate($collectionId: ID!, $input: TranslationInput!) { collectionTranslate( id: $collectionId, languageCode: PL, input: $input) { collection { translation(languageCode: PL) { name description language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_collection_create_translation( mocked_webhook_trigger, staff_api_client, published_collection, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] collection_id = graphene.Node.to_global_id("Collection", published_collection.id) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, {"collectionId": collection_id, "input": {"name": "Kolekcja PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] == "Kolekcja PL" assert data["collection"]["translation"]["language"]["code"] == "PL" translation = published_collection.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_collection_create_translation_by_translatable_content_id( staff_api_client, published_collection, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "CollectionTranslatableContent", published_collection.id ) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, {"collectionId": translatable_content_id, "input": {"name": "Kolekcja PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] == "Kolekcja PL" assert data["collection"]["translation"]["language"]["code"] == "PL" def test_collection_create_translation_for_description( staff_api_client, published_collection, permission_manage_translations ): collection_id = graphene.Node.to_global_id("Collection", published_collection.id) description = dummy_editorjs("description", True) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, {"collectionId": collection_id, "input": {"description": description}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] is None assert data["collection"]["translation"]["description"] == description assert data["collection"]["translation"]["language"]["code"] == "PL" def test_collection_create_translation_for_description_name_as_null( staff_api_client, published_collection, permission_manage_translations ): collection_id = graphene.Node.to_global_id("Collection", published_collection.id) description = dummy_editorjs("description", True) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, { "collectionId": collection_id, "input": {"description": description, "name": None}, }, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] is None assert data["collection"]["translation"]["description"] == description assert data["collection"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_collection_update_translation( mocked_webhook_trigger, staff_api_client, published_collection, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = published_collection.translations.create( language_code="pl", name="Kolekcja" ) collection_id = graphene.Node.to_global_id("Collection", published_collection.id) response = staff_api_client.post_graphql( COLLECTION_TRANSLATE_MUTATION, {"collectionId": collection_id, "input": {"name": "Kolekcja PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["collectionTranslate"] assert data["collection"]["translation"]["name"] == "Kolekcja PL" assert data["collection"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) CATEGORY_TRANSLATE_MUTATION = """ mutation categoryTranslate($categoryId: ID!, $input: TranslationInput!) { categoryTranslate( id: $categoryId, languageCode: PL, input: $input) { category { translation(languageCode: PL) { name description language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_category_create_translation( mocked_webhook_trigger, staff_api_client, category, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] category_id = graphene.Node.to_global_id("Category", category.id) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, {"categoryId": category_id, "input": {"name": "Kategoria PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] == "Kategoria PL" assert data["category"]["translation"]["language"]["code"] == "PL" translation = category.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_category_create_translation_by_translatable_content_id( staff_api_client, category, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "CategoryTranslatableContent", category.id ) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, {"categoryId": translatable_content_id, "input": {"name": "Kategoria PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] == "Kategoria PL" assert data["category"]["translation"]["language"]["code"] == "PL" def test_category_create_translation_for_description( staff_api_client, category, permission_manage_translations ): category_id = graphene.Node.to_global_id("Category", category.id) description = dummy_editorjs("description", True) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, {"categoryId": category_id, "input": {"description": description}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] is None assert data["category"]["translation"]["description"] == description assert data["category"]["translation"]["language"]["code"] == "PL" def test_category_create_translation_for_description_name_as_null( staff_api_client, category, permission_manage_translations ): category_id = graphene.Node.to_global_id("Category", category.id) description = dummy_editorjs("description", True) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, { "categoryId": category_id, "input": {"name": None, "description": description}, }, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] is None assert data["category"]["translation"]["description"] == description assert data["category"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_category_update_translation( mocked_webhook_trigger, staff_api_client, category, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = category.translations.create(language_code="pl", name="Kategoria") category_id = graphene.Node.to_global_id("Category", category.id) response = staff_api_client.post_graphql( CATEGORY_TRANSLATE_MUTATION, {"categoryId": category_id, "input": {"name": "Kategoria PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["categoryTranslate"] assert data["category"]["translation"]["name"] == "Kategoria PL" assert data["category"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) VOUCHER_TRANSLATE_MUTATION = """ mutation voucherTranslate($voucherId: ID!) { voucherTranslate( id: $voucherId, languageCode: PL, input: {name: "Bon PL"}) { voucher { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_voucher_create_translation( mocked_webhook_trigger, staff_api_client, voucher, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) response = staff_api_client.post_graphql( VOUCHER_TRANSLATE_MUTATION, {"voucherId": voucher_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["voucherTranslate"] assert data["voucher"]["translation"]["name"] == "Bon PL" assert data["voucher"]["translation"]["language"]["code"] == "PL" translation = voucher.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_voucher_create_translation_by_translatable_content_id( staff_api_client, voucher, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "VoucherTranslatableContent", voucher.id ) response = staff_api_client.post_graphql( VOUCHER_TRANSLATE_MUTATION, {"voucherId": translatable_content_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["voucherTranslate"] assert data["voucher"]["translation"]["name"] == "Bon PL" assert data["voucher"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_voucher_update_translation( mocked_webhook_trigger, staff_api_client, voucher, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = voucher.translations.create(language_code="pl", name="Kategoria") voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) response = staff_api_client.post_graphql( VOUCHER_TRANSLATE_MUTATION, {"voucherId": voucher_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["voucherTranslate"] assert data["voucher"]["translation"]["name"] == "Bon PL" assert data["voucher"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) SALE_TRANSLATION_MUTATION = """ mutation saleTranslate($saleId: ID!) { saleTranslate( id: $saleId, languageCode: PL, input: {name: "Wyprz PL"}) { sale { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_sale_create_translation( mocked_webhook_trigger, staff_api_client, sale, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] sale_id = graphene.Node.to_global_id("Sale", sale.id) response = staff_api_client.post_graphql( SALE_TRANSLATION_MUTATION, {"saleId": sale_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["saleTranslate"] assert data["sale"]["translation"]["name"] == "Wyprz PL" assert data["sale"]["translation"]["language"]["code"] == "PL" translation = sale.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_sale_create_translation_by_translatable_content_id( staff_api_client, sale, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "SaleTranslatableContent", sale.id ) response = staff_api_client.post_graphql( SALE_TRANSLATION_MUTATION, {"saleId": translatable_content_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["saleTranslate"] assert data["sale"]["translation"]["name"] == "Wyprz PL" assert data["sale"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_sale_update_translation( mocked_webhook_trigger, staff_api_client, sale, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = sale.translations.create(language_code="pl", name="Sale") sale_id = graphene.Node.to_global_id("Sale", sale.id) response = staff_api_client.post_graphql( SALE_TRANSLATION_MUTATION, {"saleId": sale_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["saleTranslate"] assert data["sale"]["translation"]["name"] == "Wyprz PL" assert data["sale"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) PAGE_TRANSLATE_MUTATION = """ mutation pageTranslate($pageId: ID!, $input: PageTranslationInput!) { pageTranslate( id: $pageId, languageCode: PL, input: $input) { page { translation(languageCode: PL) { title content language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_page_create_translation( mocked_webhook_trigger, staff_api_client, page, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] page_id = graphene.Node.to_global_id("Page", page.id) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": page_id, "input": {"title": "Strona PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] == "Strona PL" assert data["page"]["translation"]["language"]["code"] == "PL" translation = page.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_page_create_translation_for_content( staff_api_client, page, permission_manage_translations ): page_id = graphene.Node.to_global_id("Page", page.id) content = dummy_editorjs("content", True) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": page_id, "input": {"content": content}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] is None assert data["page"]["translation"]["content"] == content assert data["page"]["translation"]["language"]["code"] == "PL" def test_page_create_translation_for_content_title_as_null( staff_api_client, page, permission_manage_translations ): page_id = graphene.Node.to_global_id("Page", page.id) content = dummy_editorjs("content", True) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": page_id, "input": {"title": None, "content": content}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] is None assert data["page"]["translation"]["content"] == content assert data["page"]["translation"]["language"]["code"] == "PL" def test_page_create_translation_by_translatable_content_id( staff_api_client, page, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "PageTranslatableContent", page.id ) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": translatable_content_id, "input": {"title": "Strona PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] == "Strona PL" assert data["page"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_page_update_translation( mocked_webhook_trigger, staff_api_client, page, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = page.translations.create(language_code="pl", title="Strona") page_id = graphene.Node.to_global_id("Page", page.id) response = staff_api_client.post_graphql( PAGE_TRANSLATE_MUTATION, {"pageId": page_id, "input": {"title": "Strona PL"}}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["pageTranslate"] assert data["page"]["translation"]["title"] == "Strona PL" assert data["page"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) ATTRIBUTE_TRANSLATE_MUTATION = """ mutation attributeTranslate($attributeId: ID!) { attributeTranslate( id: $attributeId, languageCode: PL, input: {name: "Kolor PL"} ) { attribute { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_attribute_create_translation( mocked_webhook_trigger, staff_api_client, color_attribute, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id) response = staff_api_client.post_graphql( ATTRIBUTE_TRANSLATE_MUTATION, {"attributeId": attribute_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeTranslate"] assert data["attribute"]["translation"]["name"] == "Kolor PL" assert data["attribute"]["translation"]["language"]["code"] == "PL" translation = color_attribute.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_attribute_create_translation_by_translatable_content_id( staff_api_client, color_attribute, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "Attribute", color_attribute.id ) response = staff_api_client.post_graphql( ATTRIBUTE_TRANSLATE_MUTATION, {"attributeId": translatable_content_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeTranslate"] assert data["attribute"]["translation"]["name"] == "Kolor PL" assert data["attribute"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_attribute_update_translation( mocked_webhook_trigger, staff_api_client, color_attribute, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = color_attribute.translations.create(language_code="pl", name="Kolor") attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id) response = staff_api_client.post_graphql( ATTRIBUTE_TRANSLATE_MUTATION, {"attributeId": attribute_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeTranslate"] assert data["attribute"]["translation"]["name"] == "Kolor PL" assert data["attribute"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) ATTRIBUTE_VALUE_TRANSLATE_MUTATION = """ mutation attributeValueTranslate($attributeValueId: ID!, $name: String) { attributeValueTranslate( id: $attributeValueId, languageCode: PL, input: { name: $name } ) { attributeValue { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_attribute_value_create_translation( mocked_webhook_trigger, staff_api_client, pink_attribute_value, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) response = staff_api_client.post_graphql( ATTRIBUTE_VALUE_TRANSLATE_MUTATION, {"attributeValueId": attribute_value_id, "name": "Róż PL"}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeValueTranslate"] assert data["attributeValue"]["translation"]["name"] == "Róż PL" assert data["attributeValue"]["translation"]["language"]["code"] == "PL" translation = pink_attribute_value.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_attribute_value_create_translation_by_translatable_content_id( staff_api_client, pink_attribute_value, permission_manage_translations ): translatable_content_id = graphene.Node.to_global_id( "AttributeValueTranslatableContent", pink_attribute_value.id ) response = staff_api_client.post_graphql( ATTRIBUTE_VALUE_TRANSLATE_MUTATION, {"attributeValueId": translatable_content_id, "name": "Róż PL"}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeValueTranslate"] assert data["attributeValue"]["translation"]["name"] == "Róż PL" assert data["attributeValue"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_attribute_value_update_translation( mocked_webhook_trigger, staff_api_client, pink_attribute_value, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = pink_attribute_value.translations.create( language_code="pl", name="Różowy" ) attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) response = staff_api_client.post_graphql( ATTRIBUTE_VALUE_TRANSLATE_MUTATION, {"attributeValueId": attribute_value_id, "name": "Róż PL"}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["attributeValueTranslate"] assert data["attributeValue"]["translation"]["name"] == "Róż PL" assert data["attributeValue"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) SHIPPING_PRICE_TRANSLATE = """ mutation shippingPriceTranslate( $shippingMethodId: ID!, $input: ShippingPriceTranslationInput! ) { shippingPriceTranslate( id: $shippingMethodId, languageCode: PL, input: $input ) { shippingMethod { translation(languageCode: PL) { name description language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_shipping_method_create_translation( mocked_webhook_trigger, staff_api_client, shipping_method, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] shipping_method_id = graphene.Node.to_global_id( "ShippingMethod", shipping_method.id ) description = dummy_editorjs("description", True) variables = { "shippingMethodId": shipping_method_id, "input": {"name": "DHL PL", "description": description}, } response = staff_api_client.post_graphql( SHIPPING_PRICE_TRANSLATE, variables, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["shippingPriceTranslate"] assert data["shippingMethod"]["translation"]["name"] == "DHL PL" assert data["shippingMethod"]["translation"]["description"] == description assert data["shippingMethod"]["translation"]["language"]["code"] == "PL" translation = shipping_method.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) def test_shipping_method_create_translation_by_translatable_content_id( staff_api_client, shipping_method, permission_manage_translations, ): translatable_content_id = graphene.Node.to_global_id( "ShippingMethodTranslatableContent", shipping_method.id ) description = dummy_editorjs("description", True) variables = { "shippingMethodId": translatable_content_id, "input": {"name": "DHL PL", "description": description}, } response = staff_api_client.post_graphql( SHIPPING_PRICE_TRANSLATE, variables, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["shippingPriceTranslate"] assert data["shippingMethod"]["translation"]["name"] == "DHL PL" assert data["shippingMethod"]["translation"]["description"] == description assert data["shippingMethod"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_shipping_method_update_translation( mocked_webhook_trigger, staff_api_client, shipping_method, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = shipping_method.translations.create(language_code="pl", name="DHL") query = """ mutation shippingPriceTranslate($shippingMethodId: ID!) { shippingPriceTranslate( id: $shippingMethodId, languageCode: PL, input: {name: "DHL PL"}) { shippingMethod { translation(languageCode: PL) { name language { code } } } } } """ shipping_method_id = graphene.Node.to_global_id( "ShippingMethod", shipping_method.id ) response = staff_api_client.post_graphql( query, {"shippingMethodId": shipping_method_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["shippingPriceTranslate"] assert data["shippingMethod"]["translation"]["name"] == "DHL PL" assert data["shippingMethod"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) MENU_ITEM_TRANSLATE = """ mutation menuItemTranslate($menuItemId: ID!) { menuItemTranslate( id: $menuItemId, languageCode: PL, input: {name: "Odnośnik PL"} ) { menuItem { translation(languageCode: PL) { name language { code } } } } } """ @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_menu_item_update_translation( mocked_webhook_trigger, staff_api_client, menu_item, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = menu_item.translations.create(language_code="pl", name="Odnośnik") translatable_content_id = graphene.Node.to_global_id( "MenuItemTranslatableContent", menu_item.id ) response = staff_api_client.post_graphql( MENU_ITEM_TRANSLATE, {"menuItemId": translatable_content_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["menuItemTranslate"] assert data["menuItem"]["translation"]["name"] == "Odnośnik PL" assert data["menuItem"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) def test_menu_item_create_translation_by_translatable_content_id( staff_api_client, menu_item, permission_manage_translations, ): menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) response = staff_api_client.post_graphql( MENU_ITEM_TRANSLATE, {"menuItemId": menu_item_id}, permissions=[permission_manage_translations], ) data = get_graphql_content(response)["data"]["menuItemTranslate"] assert data["menuItem"]["translation"]["name"] == "Odnośnik PL" assert data["menuItem"]["translation"]["language"]["code"] == "PL" @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_shop_create_translation( mocked_webhook_trigger, staff_api_client, site_settings, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] query = """ mutation shopSettingsTranslate { shopSettingsTranslate( languageCode: PL, input: {headerText: "Nagłówek PL"}) { shop { translation(languageCode: PL) { headerText language { code } } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"]["shopSettingsTranslate"] assert data["shop"]["translation"]["headerText"] == "Nagłówek PL" assert data["shop"]["translation"]["language"]["code"] == "PL" translation = site_settings.translations.first() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_CREATED, expected_payload ) @freeze_time("1914-06-28 10:50") @patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay") def test_shop_update_translation( mocked_webhook_trigger, staff_api_client, site_settings, permission_manage_translations, settings, ): settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"] translation = site_settings.translations.create( language_code="pl", header_text="Nagłówek" ) query = """ mutation shopSettingsTranslate { shopSettingsTranslate( languageCode: PL, input: {headerText: "Nagłówek PL"}) { shop { translation(languageCode: PL) { headerText language { code } } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"]["shopSettingsTranslate"] assert data["shop"]["translation"]["headerText"] == "Nagłówek PL" assert data["shop"]["translation"]["language"]["code"] == "PL" translation.refresh_from_db() expected_payload = generate_translation_payload(translation, staff_api_client.user) mocked_webhook_trigger.assert_called_once_with( WebhookEventAsyncType.TRANSLATION_UPDATED, expected_payload ) @pytest.mark.parametrize( "kind, expected_typename", [ (TranslatableKinds.PRODUCT, "ProductTranslatableContent"), (TranslatableKinds.COLLECTION, "CollectionTranslatableContent"), (TranslatableKinds.CATEGORY, "CategoryTranslatableContent"), (TranslatableKinds.PAGE, "PageTranslatableContent"), (TranslatableKinds.SHIPPING_METHOD, "ShippingMethodTranslatableContent"), (TranslatableKinds.VOUCHER, "VoucherTranslatableContent"), (TranslatableKinds.SALE, "SaleTranslatableContent"), (TranslatableKinds.ATTRIBUTE, "AttributeTranslatableContent"), (TranslatableKinds.ATTRIBUTE_VALUE, "AttributeValueTranslatableContent"), (TranslatableKinds.VARIANT, "ProductVariantTranslatableContent"), (TranslatableKinds.MENU_ITEM, "MenuItemTranslatableContent"), ], ) def test_translations_query( staff_api_client, permission_manage_translations, product, published_collection, voucher, sale, shipping_method, page, menu_item, kind, expected_typename, ): query = """ query TranslationsQuery($kind: TranslatableKinds!) { translations(kind: $kind, first: 1) { edges { node { __typename } } totalCount } } """ response = staff_api_client.post_graphql( query, {"kind": kind.name}, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"]["translations"] assert data["edges"][0]["node"]["__typename"] == expected_typename assert data["totalCount"] > 0 def test_translations_query_inline_fragment( staff_api_client, permission_manage_translations, product ): product.translations.create(language_code="pl", name="Produkt testowy") query = """ { translations(kind: PRODUCT, first: 1) { edges { node { ... on ProductTranslatableContent { name translation(languageCode: PL) { name } } } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"]["translations"]["edges"][0] assert data["node"]["name"] == "Test product" assert data["node"]["translation"]["name"] == "Produkt testowy" QUERY_TRANSLATION_PRODUCT = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on ProductTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_product( staff_api_client, permission_manage_translations, product, product_translation_fr, ): product_id = graphene.Node.to_global_id("Product", product.id) variables = { "id": product_id, "kind": TranslatableKinds.PRODUCT.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_PRODUCT, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == product.name assert data["translation"]["name"] == product_translation_fr.name QUERY_TRANSLATION_COLLECTION = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on CollectionTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_collection( staff_api_client, published_collection, collection_translation_fr, permission_manage_translations, channel_USD, ): channel_listing = published_collection.channel_listings.get() channel_listing.save() collection_id = graphene.Node.to_global_id("Collection", published_collection.id) variables = { "id": collection_id, "kind": TranslatableKinds.COLLECTION.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_COLLECTION, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == published_collection.name assert data["translation"]["name"] == collection_translation_fr.name QUERY_TRANSLATION_CATEGORY = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on CategoryTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_category( staff_api_client, category, category_translation_fr, permission_manage_translations ): category_id = graphene.Node.to_global_id("Category", category.id) variables = { "id": category_id, "kind": TranslatableKinds.CATEGORY.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_CATEGORY, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == category.name assert data["translation"]["name"] == category_translation_fr.name QUERY_TRANSLATION_ATTRIBUTE = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on AttributeTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_attribute( staff_api_client, translated_attribute, permission_manage_translations ): attribute = translated_attribute.attribute attribute_id = graphene.Node.to_global_id("Attribute", attribute.id) variables = { "id": attribute_id, "kind": TranslatableKinds.ATTRIBUTE.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_ATTRIBUTE, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == attribute.name assert data["translation"]["name"] == translated_attribute.name QUERY_TRANSLATION_ATTRIBUTE_VALUE = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on AttributeValueTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_attribute_value( staff_api_client, pink_attribute_value, translated_attribute_value, permission_manage_translations, ): attribute_value_id = graphene.Node.to_global_id( "AttributeValue", pink_attribute_value.id ) variables = { "id": attribute_value_id, "kind": TranslatableKinds.ATTRIBUTE_VALUE.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_ATTRIBUTE_VALUE, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == pink_attribute_value.name assert data["translation"]["name"] == translated_attribute_value.name QUERY_TRANSLATION_VARIANT = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on ProductVariantTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_variant( staff_api_client, permission_manage_translations, product, variant, variant_translation_fr, ): variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) variables = { "id": variant_id, "kind": TranslatableKinds.VARIANT.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_VARIANT, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == variant.name assert data["translation"]["name"] == variant_translation_fr.name QUERY_TRANSLATION_PAGE = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on PageTranslatableContent{ id title translation(languageCode: $languageCode){ title } } } } """ @pytest.mark.parametrize( "is_published, perm_codenames", [ (True, ["manage_translations"]), (False, ["manage_translations"]), (False, ["manage_translations", "manage_pages"]), ], ) def test_translation_query_page( staff_api_client, page, page_translation_fr, is_published, perm_codenames, ): page.is_published = is_published page.save() page_id = graphene.Node.to_global_id("Page", page.id) perms = list(Permission.objects.filter(codename__in=perm_codenames)) variables = { "id": page_id, "kind": TranslatableKinds.PAGE.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_PAGE, variables, permissions=perms ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["title"] == page.title assert data["translation"]["title"] == page_translation_fr.title QUERY_TRANSLATION_SHIPPING_METHOD = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on ShippingMethodTranslatableContent{ id name description translation(languageCode: $languageCode){ name } } } } """ @pytest.mark.parametrize( "perm_codenames, return_shipping_method", [ (["manage_translations"], False), (["manage_translations", "manage_shipping"], True), ], ) def test_translation_query_shipping_method( staff_api_client, shipping_method, shipping_method_translation_fr, perm_codenames, return_shipping_method, ): shipping_method_id = graphene.Node.to_global_id( "ShippingMethod", shipping_method.id ) perms = list(Permission.objects.filter(codename__in=perm_codenames)) variables = { "id": shipping_method_id, "kind": TranslatableKinds.SHIPPING_METHOD.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_SHIPPING_METHOD, variables, permissions=perms ) content = get_graphql_content(response, ignore_errors=True) data = content["data"]["translation"] assert data["name"] == shipping_method.name assert data["description"] == shipping_method.description assert data["translation"]["name"] == shipping_method_translation_fr.name QUERY_TRANSLATION_SALE = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on SaleTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ @pytest.mark.parametrize( "perm_codenames, return_sale", [ (["manage_translations"], False), (["manage_translations", "manage_discounts"], True), ], ) def test_translation_query_sale( staff_api_client, sale, sale_translation_fr, perm_codenames, return_sale ): sale_id = graphene.Node.to_global_id("Sale", sale.id) perms = list(Permission.objects.filter(codename__in=perm_codenames)) variables = { "id": sale_id, "kind": TranslatableKinds.SALE.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_SALE, variables, permissions=perms ) content = get_graphql_content(response, ignore_errors=True) data = content["data"]["translation"] assert data["name"] == sale.name assert data["translation"]["name"] == sale_translation_fr.name QUERY_TRANSLATION_VOUCHER = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on VoucherTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ @pytest.mark.parametrize( "perm_codenames, return_voucher", [ (["manage_translations"], False), (["manage_translations", "manage_discounts"], True), ], ) def test_translation_query_voucher( staff_api_client, voucher, voucher_translation_fr, perm_codenames, return_voucher ): voucher_id = graphene.Node.to_global_id("Voucher", voucher.id) perms = list(Permission.objects.filter(codename__in=perm_codenames)) variables = { "id": voucher_id, "kind": TranslatableKinds.VOUCHER.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_VOUCHER, variables, permissions=perms ) content = get_graphql_content(response, ignore_errors=True) data = content["data"]["translation"] assert data["name"] == voucher.name assert data["translation"]["name"] == voucher_translation_fr.name QUERY_TRANSLATION_MENU_ITEM = """ query translation( $kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum! ){ translation(kind: $kind, id: $id){ __typename ...on MenuItemTranslatableContent{ id name translation(languageCode: $languageCode){ name } } } } """ def test_translation_query_menu_item( staff_api_client, menu_item, menu_item_translation_fr, permission_manage_translations, ): menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) variables = { "id": menu_item_id, "kind": TranslatableKinds.MENU_ITEM.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_MENU_ITEM, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) data = content["data"]["translation"] assert data["name"] == menu_item.name assert data["translation"]["name"] == menu_item_translation_fr.name def test_translation_query_incorrect_kind( staff_api_client, menu_item, permission_manage_translations ): menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) variables = { "id": menu_item_id, "kind": TranslatableKinds.PRODUCT.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql( QUERY_TRANSLATION_MENU_ITEM, variables, permissions=[permission_manage_translations], ) content = get_graphql_content(response) assert not content["data"]["translation"] def test_translation_query_no_permission(staff_api_client, menu_item): menu_item_id = graphene.Node.to_global_id("MenuItem", menu_item.id) variables = { "id": menu_item_id, "kind": TranslatableKinds.MENU_ITEM.name, "languageCode": LanguageCodeEnum.FR.name, } response = staff_api_client.post_graphql(QUERY_TRANSLATION_MENU_ITEM, variables) assert_no_permission(response) def test_product_and_attribute_translation(user_api_client, product, channel_USD): description = dummy_editorjs("test desription") product.translations.create( language_code="pl", name="Produkt", description=description ) assigned_attribute = product.attributes.first() attribute = assigned_attribute.attribute attribute.translations.create(language_code="pl", name="Kolor") query = """ query productById($productId: ID!, $channel: String) { product(id: $productId, channel: $channel) { translation(languageCode: PL) { name description descriptionJson language { code } } attributes{ attribute{ translation(languageCode: PL){ id name language{ code } } } } } } """ product_id = graphene.Node.to_global_id("Product", product.id) response = user_api_client.post_graphql( query, {"productId": product_id, "channel": channel_USD.slug} ) data = get_graphql_content(response)["data"] product_translation_data = data["product"]["translation"] assert product_translation_data["name"] == "Produkt" assert product_translation_data["language"]["code"] == "PL" assert ( product_translation_data["description"] == product_translation_data["descriptionJson"] == dummy_editorjs("test desription", json_format=True) ) attribute_translation_data = data["product"]["attributes"][0]["attribute"][ "translation" ] assert attribute_translation_data["name"] == "Kolor" assert attribute_translation_data["language"]["code"] == "PL" def test_product_attribute_value_rich_text_translation( staff_api_client, product_with_rich_text_attribute, permission_manage_translations, ): rich_text = dummy_editorjs("Test_dummy_data") assigned_attribute = product_with_rich_text_attribute[0].attributes.first() attribute_value = assigned_attribute.attribute.values.first() attribute_value.translations.create(language_code="pl", rich_text=rich_text) product_id = graphene.Node.to_global_id( "Product", product_with_rich_text_attribute[0].id ) query = """ query translation( $kind: TranslatableKinds! $id: ID! $languageCode: LanguageCodeEnum! ) { translation(kind: $kind, id: $id) { ... on ProductTranslatableContent { name attributeValues { name richText translation(languageCode: $languageCode) { name richText } } } } } """ variables = { "id": product_id, "kind": TranslatableKinds.PRODUCT.name, "languageCode": LanguageCodeEnum.PL.name, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"] attribute_value_response = data["translation"]["attributeValues"][0] assert attribute_value_response["name"] == attribute_value.name assert attribute_value_response["richText"] == json.dumps(attribute_value.rich_text) assert attribute_value_response["translation"]["richText"] == json.dumps(rich_text) def test_product_variant_attribute_value_rich_text_translation( staff_api_client, product_with_rich_text_attribute, permission_manage_translations, product_type_with_rich_text_attribute, ): rich_text = dummy_editorjs("Test_dummy_data") variant_attr = product_type_with_rich_text_attribute.variant_attributes.first() attribute_value = variant_attr.values.first() attribute_value.translations.create(language_code="pl", rich_text=rich_text) variant_id = graphene.Node.to_global_id( "ProductVariant", product_with_rich_text_attribute[1].id ) query = """ query translation( $kind: TranslatableKinds! $id: ID! $languageCode: LanguageCodeEnum! ) { translation(kind: $kind, id: $id) { ... on ProductVariantTranslatableContent { name attributeValues { name richText translation(languageCode: $languageCode) { name richText } } } } } """ variables = { "id": variant_id, "kind": TranslatableKinds.VARIANT.name, "languageCode": LanguageCodeEnum.PL.name, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"] translations_response = data["translation"]["attributeValues"][0] assert translations_response["name"] == attribute_value.name assert translations_response["richText"] == json.dumps(attribute_value.rich_text) assert translations_response["translation"]["richText"] == json.dumps(rich_text) def test_page_attribute_value_rich_text_translation( staff_api_client, page_with_rich_text_attribute, permission_manage_translations, page_type_with_rich_text_attribute, permission_manage_pages, ): rich_text = dummy_editorjs("Test_dummy_data") variant_attr = page_type_with_rich_text_attribute.page_attributes.first() attribute_value = variant_attr.values.first() attribute_value.translations.create(language_code="pl", rich_text=rich_text) page_id = graphene.Node.to_global_id("Page", page_with_rich_text_attribute.id) query = """ query translation( $kind: TranslatableKinds! $id: ID! $languageCode: LanguageCodeEnum! ) { translation(kind: $kind, id: $id) { ... on PageTranslatableContent { attributeValues { name richText translation(languageCode: $languageCode) { name richText } } } } } """ variables = { "id": page_id, "kind": TranslatableKinds.PAGE.name, "languageCode": LanguageCodeEnum.PL.name, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_translations] ) data = get_graphql_content(response)["data"] attribute_value_response = data["translation"]["attributeValues"][0] assert attribute_value_response["name"] == attribute_value.name assert attribute_value_response["richText"] == json.dumps(attribute_value.rich_text) assert attribute_value_response["translation"]["richText"] == json.dumps(rich_text)
true
true
1c3721a8501d5daf751b1b30d68f6b31e8b544fe
2,321
py
Python
utilities/CGI-pythons/terrainXYINC.py
sinotec2/Focus-on-Air-Quality
eac84651eaf6300a16f25a4d76b97a7f53454035
[ "MIT" ]
null
null
null
utilities/CGI-pythons/terrainXYINC.py
sinotec2/Focus-on-Air-Quality
eac84651eaf6300a16f25a4d76b97a7f53454035
[ "MIT" ]
null
null
null
utilities/CGI-pythons/terrainXYINC.py
sinotec2/Focus-on-Air-Quality
eac84651eaf6300a16f25a4d76b97a7f53454035
[ "MIT" ]
null
null
null
import twd97 Latitude_Pole, Longitude_Pole = 23.61000, 120.990 Xcent, Ycent = twd97.fromwgs84(Latitude_Pole, Longitude_Pole) def twdIJ1(xv,yv): return (int((xv-Xcent)/1000)+int(83*3/2))*1000+int((yv-Ycent)/1000)+int(137*3/2) def terrainXYINC(pth,STR): from pandas import read_csv, DataFrame import os WEB='/Library/WebServer/Documents/' CGI='/Library/WebServer/CGI-Executables/isc/' OUT='>> '+pth+'isc.out' geninp='/opt/local/bin/gen_inp.py' WAITM='/opt/local/bin/wait_map.cs' CSV=WEB+'terr_results/TWN_1X1REC.csv' reg='GRIDCART' inam=STR.index(reg) inp=STR[(inam+len(reg)):].split() snamo=inp[0] fname=pth+snamo+'.zip' #read the others inc='XYINC' iinc=STR.index(inc) inp=STR[(iinc+len(inc)):].lstrip() x0,nx,dx,y0,ny,dy=(int(float(inp.split()[i])) for i in range(6)) inp0='%s %s %s %s %s %s' %(x0,nx,dx,y0,ny,dy) inp=inp0.replace(' ','_') df=read_csv(CSV) #df['inp']=['%s %s %s %s %s %s' %(i,j,k,l,m,n) for i,j,k,l,m,n in zip(df.x0,df.nx,df.dx,df.y0,df.ny,df.dy)] if inp not in list(df.inp) or not os.path.isfile(WEB+'terr_results/'+inp+'/'+snamo+'.REC'): x0,nx,dx,y0,ny,dy=(int(float(inp.split('_')[i])) for i in range(6)) centIJ=str(twdIJ1(x0+nx*dx/2,y0+ny*dy/2)) pathIJ=centIJ path=snamo DD={} for s in 'pathIJ,centIJ,path,x0,y0,nx,ny,dx,dy,inp'.split(','): eval('DD.update({"'+s+'":['+s+']})',locals()) df=df.append(DataFrame(DD),ignore_index=True,sort=True) df.drop_duplicates(inplace=True) cmd ='cd '+pth+';' cmd+='sed s/test/'+snamo+'/g '+WEB+'trj_results/aermap.inp_template>aermap.inp;' os.system(cmd) cmd ='cd '+pth+';' cmd+= geninp+' '+pth+snamo+' '+inp0+' >>geninp.out & disown' rst=os.system(cmd) n=90 while rst==0 and n<100: cmd='sleep 5s' os.system(cmd) if os.path.isfile(fname):break n+=1 cmd ='cd '+pth+';' cmd+= WAITM+' '+pth+' '+inp+' & disown' rst=os.system(cmd) df.set_index('pathIJ').to_csv(CSV) else: terr_path=list(df.loc[df.inp==inp,'path'])[0] path=WEB+'terr_results/'+inp+'/'+terr_path cmd ='cd '+pth+';' cmd+='for i in $(ls '+path+'*);do j=$(echo $i|cut -d"/" -f7);ln -f ../../terr_results/'+inp+'/$j .;done'+OUT os.system(cmd) snamo=terr_path.split('/')[-1].replace('.REC','') return snamo
31.794521
112
0.605773
import twd97 Latitude_Pole, Longitude_Pole = 23.61000, 120.990 Xcent, Ycent = twd97.fromwgs84(Latitude_Pole, Longitude_Pole) def twdIJ1(xv,yv): return (int((xv-Xcent)/1000)+int(83*3/2))*1000+int((yv-Ycent)/1000)+int(137*3/2) def terrainXYINC(pth,STR): from pandas import read_csv, DataFrame import os WEB='/Library/WebServer/Documents/' CGI='/Library/WebServer/CGI-Executables/isc/' OUT='>> '+pth+'isc.out' geninp='/opt/local/bin/gen_inp.py' WAITM='/opt/local/bin/wait_map.cs' CSV=WEB+'terr_results/TWN_1X1REC.csv' reg='GRIDCART' inam=STR.index(reg) inp=STR[(inam+len(reg)):].split() snamo=inp[0] fname=pth+snamo+'.zip' inc='XYINC' iinc=STR.index(inc) inp=STR[(iinc+len(inc)):].lstrip() x0,nx,dx,y0,ny,dy=(int(float(inp.split()[i])) for i in range(6)) inp0='%s %s %s %s %s %s' %(x0,nx,dx,y0,ny,dy) inp=inp0.replace(' ','_') df=read_csv(CSV) if inp not in list(df.inp) or not os.path.isfile(WEB+'terr_results/'+inp+'/'+snamo+'.REC'): x0,nx,dx,y0,ny,dy=(int(float(inp.split('_')[i])) for i in range(6)) centIJ=str(twdIJ1(x0+nx*dx/2,y0+ny*dy/2)) pathIJ=centIJ path=snamo DD={} for s in 'pathIJ,centIJ,path,x0,y0,nx,ny,dx,dy,inp'.split(','): eval('DD.update({"'+s+'":['+s+']})',locals()) df=df.append(DataFrame(DD),ignore_index=True,sort=True) df.drop_duplicates(inplace=True) cmd ='cd '+pth+';' cmd+='sed s/test/'+snamo+'/g '+WEB+'trj_results/aermap.inp_template>aermap.inp;' os.system(cmd) cmd ='cd '+pth+';' cmd+= geninp+' '+pth+snamo+' '+inp0+' >>geninp.out & disown' rst=os.system(cmd) n=90 while rst==0 and n<100: cmd='sleep 5s' os.system(cmd) if os.path.isfile(fname):break n+=1 cmd ='cd '+pth+';' cmd+= WAITM+' '+pth+' '+inp+' & disown' rst=os.system(cmd) df.set_index('pathIJ').to_csv(CSV) else: terr_path=list(df.loc[df.inp==inp,'path'])[0] path=WEB+'terr_results/'+inp+'/'+terr_path cmd ='cd '+pth+';' cmd+='for i in $(ls '+path+'*);do j=$(echo $i|cut -d"/" -f7);ln -f ../../terr_results/'+inp+'/$j .;done'+OUT os.system(cmd) snamo=terr_path.split('/')[-1].replace('.REC','') return snamo
true
true
1c37220ee62e64d4ce2c17fdbb3b737d9e8b50e4
7,848
py
Python
docs/conf.py
jimmysyss/cookiecutter
945cb4c24b8e1dddded3de98013a6288d5ee056b
[ "MIT" ]
null
null
null
docs/conf.py
jimmysyss/cookiecutter
945cb4c24b8e1dddded3de98013a6288d5ee056b
[ "MIT" ]
null
null
null
docs/conf.py
jimmysyss/cookiecutter
945cb4c24b8e1dddded3de98013a6288d5ee056b
[ "MIT" ]
null
null
null
# CookieCutter documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'CookieCutter' copyright = """2018, Daniel Roy Greenfeld""" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'cookiecutterdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'cookiecutter.tex', 'CookieCutter Documentation', """Daniel Roy Greenfeld""", 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'cookiecutter', 'CookieCutter Documentation', ["""Daniel Roy Greenfeld"""], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'cookiecutter', 'CookieCutter Documentation', """Daniel Roy Greenfeld""", 'CookieCutter', """Behold My Awesome Project!""", 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
32.163934
80
0.707569
import os import sys extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'CookieCutter' copyright = """2018, Daniel Roy Greenfeld""" # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'cookiecutterdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'cookiecutter.tex', 'CookieCutter Documentation', """Daniel Roy Greenfeld""", 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'cookiecutter', 'CookieCutter Documentation', ["""Daniel Roy Greenfeld"""], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'cookiecutter', 'CookieCutter Documentation', """Daniel Roy Greenfeld""", 'CookieCutter', """Behold My Awesome Project!""", 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
true
true
1c372218d7aa5cfffebbb9b7067fe2dd28384c63
486
py
Python
portfolio_main/migrations/0005_auto_20180711_2119.py
lucasLB7/LucasPortfiolio
6579c0622f1e071d41b497561e4261605978ffc6
[ "Unlicense" ]
null
null
null
portfolio_main/migrations/0005_auto_20180711_2119.py
lucasLB7/LucasPortfiolio
6579c0622f1e071d41b497561e4261605978ffc6
[ "Unlicense" ]
4
2020-02-12T01:07:27.000Z
2021-06-08T19:10:47.000Z
portfolio_main/migrations/0005_auto_20180711_2119.py
lucasLB7/LucasPortfiolio
6579c0622f1e071d41b497561e4261605978ffc6
[ "Unlicense" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-07-11 18:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('portfolio_main', '0004_resume_live_app_deployment'), ] operations = [ migrations.AlterField( model_name='resume', name='article_image', field=models.ImageField(blank=True, upload_to=''), ), ]
23.142857
62
0.633745
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('portfolio_main', '0004_resume_live_app_deployment'), ] operations = [ migrations.AlterField( model_name='resume', name='article_image', field=models.ImageField(blank=True, upload_to=''), ), ]
true
true
1c3722f576e3f0b7a472c92e35a478344f09b2bd
26,692
py
Python
src/pymwm/cylinder/__init__.py
mnishida/pymwm
820d0a9056982fd37972b0e10f5dad9d1697ed2f
[ "MIT" ]
3
2020-04-16T14:55:34.000Z
2021-08-04T07:03:31.000Z
src/pymwm/cylinder/__init__.py
mnishida/pymwm
820d0a9056982fd37972b0e10f5dad9d1697ed2f
[ "MIT" ]
1
2021-08-13T04:45:50.000Z
2021-08-18T03:33:08.000Z
src/pymwm/cylinder/__init__.py
mnishida/pymwm
820d0a9056982fd37972b0e10f5dad9d1697ed2f
[ "MIT" ]
2
2021-04-05T07:10:26.000Z
2021-08-04T03:15:43.000Z
from __future__ import annotations import cmath import numpy as np import psutil import ray import scipy.special as ssp from pymwm.utils import cylinder_utils from pymwm.waveguide import Database, Sampling, Waveguide from .samples import Samples, SamplesForRay, SamplesLowLoss, SamplesLowLossForRay class Cylinder(Waveguide): """A class defining a cylindrical waveguide.""" def __init__(self, params): """Init Cylinder class. Args: params: A dict whose keys and values are as follows: 'core': A dict of the setting parameters of the core: 'shape': A string indicating the shape of the core. 'size': A float indicating the radius of the circular cross section [um]. 'fill': A dict of the parameters of the core Material. 'clad': A dict of the parameters of the clad Material. 'bounds': A dict indicating the bounds of database.interpolation and its keys and values are as follows: 'wl_max': A float indicating the maximum wavelength [um] 'wl_min': A float indicating the minimum wavelength [um] 'wl_imag': A float indicating the maximum value of abs(c / f_imag) [um] where f_imag is the imaginary part of the frequency. 'modes': A dict of the settings for calculating modes: 'wl_max': A float indicating the maximum wavelength [um] (default: 5.0) 'wl_min': A float indicating the minimum wavelength [um] (default: 0.4) 'wl_imag': A float indicating the maximum value of abs(c / f_imag) [um] where f_imag is the imaginary part of the frequency. (default: 5.0) 'dw': A float indicating frequency interval [rad c / 1um]=[2.99792458e14 rad / s] (default: 1 / 64). 'num_n': An integer indicating the number of orders of modes. 'num_m': An integer indicating the number of modes in each order and polarization. 'ls': A list of characters chosen from "h" (horizontal polarization) and "v" (vertical polarization). """ super().__init__(params) self.u_pec, self.jnu_pec, self.jnpu_pec = self.u_jnu_jnpu_pec( self.num_n, self.num_m ) def get_alphas(self, alpha_list: list[tuple[str, int, int]]) -> dict: alphas: dict = {"h": [], "v": []} for alpha in [("E", 0, m) for m in range(1, self.num_m + 1)]: if alpha in alpha_list: alphas["v"].append(alpha) for alpha in [ ("E", n, m) for n in range(1, self.num_n) for m in range(1, self.num_m + 1) ]: if alpha in alpha_list: alphas["h"].append(alpha) alphas["v"].append(alpha) for alpha in [("M", 0, m) for m in range(1, self.num_m + 1)]: if alpha in alpha_list: alphas["h"].append(alpha) for alpha in [ ("M", n, m) for n in range(1, self.num_n) for m in range(1, self.num_m + 1) ]: if alpha in alpha_list: alphas["h"].append(alpha) alphas["v"].append(alpha) return alphas def betas_convs_samples(self, params: dict) -> tuple[dict, dict, Samples]: im_factor = self.clad.im_factor self.clad.im_factor = 1.0 self.clad_params["im_factor"] = 1.0 p_modes = params["modes"].copy() num_n_0 = p_modes["num_n"] num_m_0 = p_modes["num_m"] betas: dict = {} convs: dict = {} success = False catalog = Database().load_catalog() num_n_max = catalog["num_n"].max() num_m_max = catalog["num_m"].max() if not np.isnan(num_n_max): for num_n, num_m in [ (n, m) for n in range(num_n_0, num_n_max + 1) for m in range(num_m_0, num_m_max + 1) ]: p_modes["num_n"] = num_n p_modes["num_m"] = num_m smp = Samples(self.r, self.fill_params, self.clad_params, p_modes) try: betas, convs = smp.database.load() success = True break except IndexError: continue if not success: p_modes["num_n"] = num_n_0 p_modes["num_m"] = num_m_0 betas, convs, smp = self.do_sampling(p_modes) if im_factor != 1.0: self.clad.im_factor = im_factor self.clad_params["im_factor"] = im_factor betas, convs, smp = self.do_sampling_for_im_factor(betas, convs, p_modes) return betas, convs, smp def do_sampling(self, p_modes: dict) -> tuple[dict, dict, Samples]: num_n_0 = p_modes["num_n"] num_m_0 = p_modes["num_m"] smp = Samples(self.r, self.fill_params, self.clad_params, p_modes) ray.shutdown() try: ray.init() p_modes_id = ray.put(p_modes) pool = ray.util.ActorPool( SamplesForRay.remote( self.r, self.fill_params, self.clad_params, p_modes_id ) for _ in range(psutil.cpu_count()) ) xs_success_wr_list: list[tuple[np.ndarray, np.ndarray]] = list( pool.map(lambda a, arg: a.wr_sampling.remote(arg), range(num_n_0)) ) num_wr = xs_success_wr_list[0][0].shape[0] args = [] for n in range(num_n_0): xs_array, _ = xs_success_wr_list[n] for iwr in range(num_wr): args.append((n, iwr, xs_array[iwr])) xs_success_wi_list: list[tuple[np.ndarray, np.ndarray]] = list( pool.map(lambda a, arg: a.wi_sampling.remote(arg), args) ) num_wi = xs_success_wi_list[0][0].shape[0] xs_success_list: list[tuple[np.ndarray, np.ndarray]] = [] for n in range(num_n_0): xs_array = np.zeros((num_wr, num_wi, 2 * num_m_0 + 1), dtype=complex) success_array = np.zeros((num_wr, num_wi, 2 * num_m_0 + 1), dtype=bool) for iwr in range(num_wr): i = num_wr * n + iwr xs_i, success_i = xs_success_wi_list[i] xs_array[iwr] = xs_i success_array[iwr] = success_i xs_success_list.append((xs_array, success_array)) finally: ray.shutdown() betas, convs = smp.betas_convs(xs_success_list) smp.database.save(betas, convs) return betas, convs, smp def do_sampling_for_im_factor( self, betas: dict, convs: dict, p_modes: dict ) -> tuple[dict, dict, SamplesLowLoss]: smp = SamplesLowLoss(self.r, self.fill_params, self.clad_params, p_modes) try: betas, convs = smp.database.load() except IndexError: num_n = p_modes["num_n"] num_m = p_modes["num_m"] args = [] for iwr in range(len(smp.ws)): for iwi in range(len(smp.wis)): xis_list = [] for n in range(num_n): xis = [] for i in range(num_m + 1): xis.append(betas[("M", n, i + 1)][iwr, iwi] ** 2) for i in range(num_m): xis.append(betas[("E", n, i + 1)][iwr, iwi] ** 2) xis_list.append(xis) args.append((iwr, iwi, xis_list)) try: ray.init() p_modes_id = ray.put(p_modes) pool = ray.util.ActorPool( SamplesLowLossForRay.remote( self.r, self.fill_params, self.clad_params, p_modes_id ) for _ in range(psutil.cpu_count()) ) xs_success_list = list( pool.map(lambda a, arg: a.task.remote(arg), args) ) finally: ray.shutdown() betas, convs = smp.betas_convs(xs_success_list) smp.database.save(betas, convs) return betas, convs, smp def beta(self, w: complex, alpha: tuple[str, int, int]) -> complex: """Return phase constant Args: w: A complex indicating the angular frequency alpha: (pol, n, m) pol: 'M' (TM-like mode) or 'E' (TE-like mode) n: The order of the mode m: The sub order of the mode. Returns: h: The phase constant. """ if self.clad.label == "PEC": return self.beta_pec(w, alpha) wr = w.real wi = w.imag hr: float = self.beta_funcs[(alpha, "real")](wr, wi)[0, 0] hi: float = self.beta_funcs[(alpha, "imag")](wr, wi)[0, 0] # if hr < 0: # hr = 1e-16 # if hi < 0: # hi = 1e-16 return hr + 1j * hi def beta_pec(self, w: complex, alpha: tuple[str, int, int]) -> complex: """Return phase constant of PEC waveguide Args: w: A complex indicating the angular frequency alpha: A tuple (pol, n, m) where pol is 'M' for TM mode or 'E' for TE mode, n is the order of the mode, and m is the number of modes in the order and the polarization. Returns: h: A complex indicating the phase constant. """ w_comp = w.real + 1j * w.imag pol, n, m = alpha if pol == "E": chi = ssp.jnp_zeros(n, m)[-1] elif pol == "M": chi = ssp.jn_zeros(n, m)[-1] else: raise ValueError("pol must be 'E' or 'M") val = cmath.sqrt(self.fill(w_comp) * w_comp ** 2 - chi ** 2 / self.r ** 2) if abs(val.real) > abs(val.imag): if val.real < 0: val *= -1 else: if val.imag < 0: val *= -1 return val def coef(self, h, w, alpha): """Return the coefficients of TE- and TM- components which compose the hybrid mode. Args: h: A complex indicating the phase constant. w: A complex indicating the angular frequency alpha: A tuple (pol, n, m) where pol is 'M' for TM-like mode or 'E' for TE-like mode, n is the order of the mode, and m is the number of modes in the order and the polarization. Returns: a: A complex indicating the coefficient of TE-component b: A complex indicating the coefficient of TM-component """ e1 = self.fill(w) e2 = self.clad(w) pol, n, m = alpha w = w.real + 1j * w.imag h = h.real + 1j * h.imag if e2.real < -1e6: if pol == "E": norm = self.norm(w, h, alpha, 1.0 + 0.0j, 0.0j) ai, bi = 1.0 / norm, 0.0 else: norm = self.norm(w, h, alpha, 0.0j, 1.0 + 0.0j) ai, bi = 0.0, 1.0 / norm else: u = self.samples.u(h ** 2, w, e1) v = self.samples.v(h ** 2, w, e2) knv = ssp.kv(n, v) knpv = ssp.kvp(n, v) jnu = ssp.jv(n, u) jnpu = ssp.jvp(n, u) ci = -n * (u ** 2 + v ** 2) * jnu * knv / (u * v) if pol == "E": ci *= (h / w) ** 2 ci /= e1 * jnpu * v * knv + e2 * knpv * u * jnu norm = self.norm(w, h, alpha, 1.0 + 0.0j, ci) ai = 1.0 / norm bi = ci / norm else: ci /= jnpu * v * knv + knpv * u * jnu norm = self.norm(w, h, alpha, ci, 1.0 + 0.0j) bi = 1.0 / norm ai = ci / norm return ai, bi def norm(self, w, h, alpha, a, b): pol, n, m = alpha en = 1 if n == 0 else 2 if self.clad(w).real < -1e6: radius = self.r if pol == "E": u = ssp.jnp_zeros(n, m)[-1] jnu = ssp.jv(n, u) jnpu = 0.0 else: u = ssp.jn_zeros(n, m)[-1] jnu = 0.0 jnpu = ssp.jvp(n, u) return cmath.sqrt( a ** 2 * np.pi * radius ** 2 / en * (1 - n ** 2 / u ** 2) * jnu ** 2 + b ** 2 * np.pi * radius ** 2 / en * jnpu ** 2 ) u = self.samples.u(h ** 2, w, self.fill(w)) jnu = ssp.jv(n, u) jnpu = ssp.jvp(n, u) v = self.samples.v(h ** 2, w, self.clad(w)) knv = ssp.kv(n, v) knpv = ssp.kvp(n, v) val_u = 2 * np.pi * self.r ** 2 / en val_v = val_u * ((u * jnu) / (v * knv)) ** 2 upart_diag = self.upart_diag(n, u, jnu, jnpu) vpart_diag = self.vpart_diag(n, v, knv, knpv) upart_off = self.upart_off(n, u, jnu) vpart_off = self.vpart_off(n, v, knv) return cmath.sqrt( val_u * ( a * (a * upart_diag + b * upart_off) + b * (b * upart_diag + a * upart_off) ) - val_v * ( a * (a * vpart_diag + b * vpart_off) + b * (b * vpart_diag + a * vpart_off) ) ) @staticmethod def upart_diag(n, u, jnu, jnpu): return jnu * jnpu / u + (jnpu ** 2 + (1 - n ** 2 / u ** 2) * jnu ** 2) / 2 @staticmethod def upart_off(n, u, jnu): return n * (jnu / u) ** 2 @staticmethod def vpart_diag(n, v, knv, knpv): return knv * knpv / v + (knpv ** 2 - (1 + n ** 2 / v ** 2) * knv ** 2) / 2 @staticmethod def vpart_off(n, v, knv): return n * (knv / v) ** 2 def Y( self, w: complex, h: complex, alpha: tuple[str, int, int], a: complex, b: complex, ) -> complex: """Return the effective admittance of the waveguide mode Args: w: A complex indicating the angular frequency h: A complex indicating the phase constant. alpha: A tuple (pol, n, m) where pol is 'M' for TM-like mode or 'E' for TE-like mode, n is the order of the mode, and m is the number of modes in the order and the polarization. a: A complex indicating the coefficient of TE-component b: A complex indicating the coefficient of TM-component Returns: y: A complex indicating the effective admittance """ pol, n, m = alpha e1 = self.fill(w) e2 = self.clad(w) en = 1 if n == 0 else 2 if e2.real < -1e6: if pol == "E": val = h / w else: val = e1 * w / h else: u = self.samples.u(h ** 2, w, e1) jnu = ssp.jv(n, u) jnpu = ssp.jvp(n, u) v = self.samples.v(h ** 2, w, e2) knv = ssp.kv(n, v) knpv = ssp.kvp(n, v) val_u = 2 * np.pi * self.r ** 2 / en val_v = val_u * ((u * jnu) / (v * knv)) ** 2 upart_diag = self.upart_diag(n, u, jnu, jnpu) vpart_diag = self.vpart_diag(n, v, knv, knpv) upart_off = self.upart_off(n, u, jnu) vpart_off = self.vpart_off(n, v, knv) val = val_u * ( h / w * a * (a * upart_diag + b * upart_off) + e1 * w / h * b * (b * upart_diag + a * upart_off) ) - val_v * ( h / w * a * (a * vpart_diag + b * vpart_off) + e2 * w / h * b * (b * vpart_diag + a * vpart_off) ) return val @staticmethod def y_te(w, h): return h / w def y_tm_inner(self, w, h): e = self.fill(w) return e * w / h def y_tm_outer(self, w, h): e = self.clad(w) return e * w / h def fields(self, x, y, w, dir, alpha, h, coef): """Return the electromagnetic field vectors for the specified mode and point Args: x: A float indicating the x coordinate [um] y: A float indicating the y coordinate [um] w: A complex indicating the angular frequency dir: "h" (horizontal polarization) or "v" (vertical polarization) alpha: A tuple (pol, n, m) where pol is 'M' for TM-like mode or 'E' for TE-like mode, n is the order of the mode, and m is the number of modes in the order and the polarization. h: A complex indicating the phase constant. coef: The coefficients of TE- and TM- components Returns: f_vec: An array of complexes [ex, ey, ez, hx, hy, hz]. """ pol, n, m = alpha a, b = coef r = np.hypot(x, y) p = np.arctan2(y, x) u = self.samples.u(h ** 2, w, self.fill(w)) v = self.samples.v(h ** 2, w, self.clad(w)) ur = u * r / self.r vr = v * r / self.r if dir == "h": fr = np.cos(n * p) fp = -np.sin(n * p) else: fr = np.sin(n * p) fp = np.cos(n * p) y_te = Cylinder.y_te(w, h) if r <= self.r: y_tm = self.y_tm_inner(w, h) er_te = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fr er_tm = ssp.jvp(n, ur) * fr er = a * er_te + b * er_tm ep_te = ssp.jvp(n, ur) * fp ep_tm = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fp ep = a * ep_te + b * ep_tm ez = u / (1j * h * self.r) * b * ssp.jv(n, ur) * fr hr = -y_te * a * ep_te - y_tm * b * ep_tm hp = y_te * a * er_te + y_tm * b * er_tm hz = -u / (1j * h * self.r) * y_te * a * ssp.jv(n, ur) * fp else: y_tm = self.y_tm_outer(w, h) val = -u * ssp.jv(n, u) / (v * ssp.kv(n, v)) er_te = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fr * val er_tm = ssp.kvp(n, vr) * fr * val er = a * er_te + b * er_tm ep_te = ssp.kvp(n, vr) * fp * val ep_tm = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fp * val ep = a * ep_te + b * ep_tm ez = -v / (1j * h * self.r) * b * ssp.kv(n, vr) * fr * val hr = -y_te * a * ep_te - y_tm * b * ep_tm hp = y_te * a * er_te + y_tm * b * er_tm hz = v / (1j * h * self.r) * y_te * a * ssp.kv(n, vr) * fp * val ex = er * np.cos(p) - ep * np.sin(p) ey = er * np.sin(p) + ep * np.cos(p) hx = hr * np.cos(p) - hp * np.sin(p) hy = hr * np.sin(p) + hp * np.cos(p) return np.array([ex, ey, ez, hx, hy, hz]) def e_field(self, x, y, w, dir, alpha, h, coef): """Return the electric field vector for the specified mode and point Args: x: A float indicating the x coordinate [um] y: A float indicating the y coordinate [um] w: A complex indicating the angular frequency dir: "h" (horizontal polarization) or "v" (vertical polarization) alpha: A tuple (pol, n, m) where pol is 'M' for TM-like mode or 'E' for TE-like mode, n is the order of the mode, and m is the number of modes in the order and the polarization. h: A complex indicating the phase constant. coef: The coefficients of TE- and TM- components Returns: e_vec: An array of complexes [ex, ey, ez]. """ pol, n, m = alpha a, b = coef r = np.hypot(x, y) p = np.arctan2(y, x) u = self.samples.u(h ** 2, w, self.fill(w)) v = self.samples.v(h ** 2, w, self.clad(w)) ur = u * r / self.r vr = v * r / self.r if dir == "h": fr = np.cos(n * p) fp = -np.sin(n * p) else: fr = np.sin(n * p) fp = np.cos(n * p) if r <= self.r: er_te = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fr er_tm = ssp.jvp(n, ur) * fr er = a * er_te + b * er_tm ep_te = ssp.jvp(n, ur) * fp ep_tm = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fp ep = a * ep_te + b * ep_tm ez = u / (1j * h * self.r) * b * ssp.jv(n, ur) * fr else: val = -u * ssp.jv(n, u) / (v * ssp.kv(n, v)) er_te = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fr * val er_tm = ssp.kvp(n, vr) * fr * val er = a * er_te + b * er_tm ep_te = ssp.kvp(n, vr) * fp * val ep_tm = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fp * val ep = a * ep_te + b * ep_tm ez = -v / (1j * h * self.r) * b * ssp.kv(n, vr) * fr * val ex = er * np.cos(p) - ep * np.sin(p) ey = er * np.sin(p) + ep * np.cos(p) return np.array([ex, ey, ez]) def h_field(self, x, y, w, dir, alpha, h, coef): """Return the magnetic field vectors for the specified mode and point Args: x: A float indicating the x coordinate [um] y: A float indicating the y coordinate [um] w: A complex indicating the angular frequency dir: "h" (horizontal polarization) or "v" (vertical polarization) alpha: A tuple (pol, n, m) where pol is 'M' for TM-like mode or 'E' for TE-like mode, n is the order of the mode, and m is the number of modes in the order and the polarization. h: A complex indicating the phase constant. coef: The coefficients of TE- and TM- components Returns: h_vec: An array of complexes [hx, hy, hz]. """ pol, n, m = alpha a, b = coef r = np.hypot(x, y) p = np.arctan2(y, x) u = self.samples.u(h ** 2, w, self.fill(w)) v = self.samples.v(h ** 2, w, self.clad(w)) ur = u * r / self.r vr = v * r / self.r if dir == "h": fr = np.cos(n * p) fp = -np.sin(n * p) else: fr = np.sin(n * p) fp = np.cos(n * p) y_te = Cylinder.y_te(w, h) if r <= self.r: y_tm = self.y_tm_inner(w, h) er_te = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fr er_tm = ssp.jvp(n, ur) * fr ep_te = ssp.jvp(n, ur) * fp ep_tm = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fp hr = -y_te * a * ep_te - y_tm * b * ep_tm hp = y_te * a * er_te + y_tm * b * er_tm hz = -u / (1j * h * self.r) * y_te * a * ssp.jv(n, ur) * fp else: y_tm = self.y_tm_outer(w, h) val = -u * ssp.jv(n, u) / (v * ssp.kv(n, v)) er_te = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fr * val er_tm = ssp.kvp(n, vr) * fr * val ep_te = ssp.kvp(n, vr) * fp * val ep_tm = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fp * val hr = -y_te * a * ep_te - y_tm * b * ep_tm hp = y_te * a * er_te + y_tm * b * er_tm hz = v / (1j * h * self.r) * y_te * a * ssp.kv(n, vr) * fp * val hx = hr * np.cos(p) - hp * np.sin(p) hy = hr * np.sin(p) + hp * np.cos(p) return np.array([hx, hy, hz]) @staticmethod def u_jnu_jnpu_pec(num_n, num_m): us = np.empty((2, num_n, num_m)) jnus = np.empty((2, num_n, num_m)) jnpus = np.empty((2, num_n, num_m)) for n in range(num_n): us[0, n] = ssp.jnp_zeros(n, num_m) us[1, n] = ssp.jn_zeros(n, num_m) jnus[0, n] = ssp.jv(n, us[0, n]) jnus[1, n] = np.zeros(num_m) jnpus[0, n] = np.zeros(num_m) jnpus[1, n] = ssp.jvp(n, us[1, n]) return us, jnus, jnpus def coefs(self, hs, w): As = [] Bs = [] for h, s, n, m in zip(hs, self.s_all, self.n_all, self.m_all): pol = "E" if s == 0 else "M" ai, bi = self.coef(h, w, (pol, n, m)) As.append(ai) Bs.append(bi) return np.ascontiguousarray(As), np.ascontiguousarray(Bs) def Ys(self, w, hs, As, Bs): vals = [] for h, s, n, a, b in zip(hs, self.s_all, self.n_all, As, Bs): pol = "E" if s == 0 else "M" vals.append(self.Y(w, h, (pol, n, 1), a, b)) return np.array(vals) def props_numpy(self, w): e1 = self.fill(w) e2 = self.clad(w) hs = np.array([self.beta(w, alpha) for alpha in self.alpha_all]) As, Bs = self.coefs(hs, w) Ys = self.Ys(w, hs, As, Bs) if e2.real < -1e6: us = np.zeros_like(hs, dtype=complex) jus = np.zeros_like(hs, dtype=complex) jpus = np.zeros_like(hs, dtype=complex) for i, (h, s, n, m) in enumerate( zip(hs, self.s_all, self.n_all, self.m_all) ): us[i] = self.u_pec[s, n, m - 1] jus[i] = self.jnu_pec[s, n, m - 1] jpus[i] = self.jnpu_pec[s, n, m - 1] vs = (1 - 1j) * np.sqrt(0.5j * (-e2 * w ** 2 + hs ** 2)) * self.r kvs = np.zeros_like(vs) kpvs = np.zeros_like(vs) else: us = self.samples.u(hs ** 2, w, e1) vs = self.samples.v(hs ** 2, w, e2) jus = ssp.jv(self.n_all, us) jpus = ssp.jvp(self.n_all, us) kvs = ssp.kv(self.n_all, vs) kpvs = ssp.kvp(self.n_all, vs) return hs, us, vs, jus, jpus, kvs, kpvs, As, Bs, Ys def props(self, w): e1 = self.fill(w) e2 = self.clad(w) hs = np.array([self.beta(w, alpha) for alpha in self.alpha_all]) us, vs, jus, jpus, kvs, kpvs, As, Bs, Ys = cylinder_utils.props_cython( w, self.r, self.s_all, self.n_all, self.m_all, hs, e1, e2, self.u_pec, self.jnu_pec, self.jnpu_pec, ) return hs, us, vs, jus, jpus, kvs, kpvs, As, Bs, Ys
39.838806
87
0.469804
from __future__ import annotations import cmath import numpy as np import psutil import ray import scipy.special as ssp from pymwm.utils import cylinder_utils from pymwm.waveguide import Database, Sampling, Waveguide from .samples import Samples, SamplesForRay, SamplesLowLoss, SamplesLowLossForRay class Cylinder(Waveguide): def __init__(self, params): super().__init__(params) self.u_pec, self.jnu_pec, self.jnpu_pec = self.u_jnu_jnpu_pec( self.num_n, self.num_m ) def get_alphas(self, alpha_list: list[tuple[str, int, int]]) -> dict: alphas: dict = {"h": [], "v": []} for alpha in [("E", 0, m) for m in range(1, self.num_m + 1)]: if alpha in alpha_list: alphas["v"].append(alpha) for alpha in [ ("E", n, m) for n in range(1, self.num_n) for m in range(1, self.num_m + 1) ]: if alpha in alpha_list: alphas["h"].append(alpha) alphas["v"].append(alpha) for alpha in [("M", 0, m) for m in range(1, self.num_m + 1)]: if alpha in alpha_list: alphas["h"].append(alpha) for alpha in [ ("M", n, m) for n in range(1, self.num_n) for m in range(1, self.num_m + 1) ]: if alpha in alpha_list: alphas["h"].append(alpha) alphas["v"].append(alpha) return alphas def betas_convs_samples(self, params: dict) -> tuple[dict, dict, Samples]: im_factor = self.clad.im_factor self.clad.im_factor = 1.0 self.clad_params["im_factor"] = 1.0 p_modes = params["modes"].copy() num_n_0 = p_modes["num_n"] num_m_0 = p_modes["num_m"] betas: dict = {} convs: dict = {} success = False catalog = Database().load_catalog() num_n_max = catalog["num_n"].max() num_m_max = catalog["num_m"].max() if not np.isnan(num_n_max): for num_n, num_m in [ (n, m) for n in range(num_n_0, num_n_max + 1) for m in range(num_m_0, num_m_max + 1) ]: p_modes["num_n"] = num_n p_modes["num_m"] = num_m smp = Samples(self.r, self.fill_params, self.clad_params, p_modes) try: betas, convs = smp.database.load() success = True break except IndexError: continue if not success: p_modes["num_n"] = num_n_0 p_modes["num_m"] = num_m_0 betas, convs, smp = self.do_sampling(p_modes) if im_factor != 1.0: self.clad.im_factor = im_factor self.clad_params["im_factor"] = im_factor betas, convs, smp = self.do_sampling_for_im_factor(betas, convs, p_modes) return betas, convs, smp def do_sampling(self, p_modes: dict) -> tuple[dict, dict, Samples]: num_n_0 = p_modes["num_n"] num_m_0 = p_modes["num_m"] smp = Samples(self.r, self.fill_params, self.clad_params, p_modes) ray.shutdown() try: ray.init() p_modes_id = ray.put(p_modes) pool = ray.util.ActorPool( SamplesForRay.remote( self.r, self.fill_params, self.clad_params, p_modes_id ) for _ in range(psutil.cpu_count()) ) xs_success_wr_list: list[tuple[np.ndarray, np.ndarray]] = list( pool.map(lambda a, arg: a.wr_sampling.remote(arg), range(num_n_0)) ) num_wr = xs_success_wr_list[0][0].shape[0] args = [] for n in range(num_n_0): xs_array, _ = xs_success_wr_list[n] for iwr in range(num_wr): args.append((n, iwr, xs_array[iwr])) xs_success_wi_list: list[tuple[np.ndarray, np.ndarray]] = list( pool.map(lambda a, arg: a.wi_sampling.remote(arg), args) ) num_wi = xs_success_wi_list[0][0].shape[0] xs_success_list: list[tuple[np.ndarray, np.ndarray]] = [] for n in range(num_n_0): xs_array = np.zeros((num_wr, num_wi, 2 * num_m_0 + 1), dtype=complex) success_array = np.zeros((num_wr, num_wi, 2 * num_m_0 + 1), dtype=bool) for iwr in range(num_wr): i = num_wr * n + iwr xs_i, success_i = xs_success_wi_list[i] xs_array[iwr] = xs_i success_array[iwr] = success_i xs_success_list.append((xs_array, success_array)) finally: ray.shutdown() betas, convs = smp.betas_convs(xs_success_list) smp.database.save(betas, convs) return betas, convs, smp def do_sampling_for_im_factor( self, betas: dict, convs: dict, p_modes: dict ) -> tuple[dict, dict, SamplesLowLoss]: smp = SamplesLowLoss(self.r, self.fill_params, self.clad_params, p_modes) try: betas, convs = smp.database.load() except IndexError: num_n = p_modes["num_n"] num_m = p_modes["num_m"] args = [] for iwr in range(len(smp.ws)): for iwi in range(len(smp.wis)): xis_list = [] for n in range(num_n): xis = [] for i in range(num_m + 1): xis.append(betas[("M", n, i + 1)][iwr, iwi] ** 2) for i in range(num_m): xis.append(betas[("E", n, i + 1)][iwr, iwi] ** 2) xis_list.append(xis) args.append((iwr, iwi, xis_list)) try: ray.init() p_modes_id = ray.put(p_modes) pool = ray.util.ActorPool( SamplesLowLossForRay.remote( self.r, self.fill_params, self.clad_params, p_modes_id ) for _ in range(psutil.cpu_count()) ) xs_success_list = list( pool.map(lambda a, arg: a.task.remote(arg), args) ) finally: ray.shutdown() betas, convs = smp.betas_convs(xs_success_list) smp.database.save(betas, convs) return betas, convs, smp def beta(self, w: complex, alpha: tuple[str, int, int]) -> complex: if self.clad.label == "PEC": return self.beta_pec(w, alpha) wr = w.real wi = w.imag hr: float = self.beta_funcs[(alpha, "real")](wr, wi)[0, 0] hi: float = self.beta_funcs[(alpha, "imag")](wr, wi)[0, 0] return hr + 1j * hi def beta_pec(self, w: complex, alpha: tuple[str, int, int]) -> complex: w_comp = w.real + 1j * w.imag pol, n, m = alpha if pol == "E": chi = ssp.jnp_zeros(n, m)[-1] elif pol == "M": chi = ssp.jn_zeros(n, m)[-1] else: raise ValueError("pol must be 'E' or 'M") val = cmath.sqrt(self.fill(w_comp) * w_comp ** 2 - chi ** 2 / self.r ** 2) if abs(val.real) > abs(val.imag): if val.real < 0: val *= -1 else: if val.imag < 0: val *= -1 return val def coef(self, h, w, alpha): e1 = self.fill(w) e2 = self.clad(w) pol, n, m = alpha w = w.real + 1j * w.imag h = h.real + 1j * h.imag if e2.real < -1e6: if pol == "E": norm = self.norm(w, h, alpha, 1.0 + 0.0j, 0.0j) ai, bi = 1.0 / norm, 0.0 else: norm = self.norm(w, h, alpha, 0.0j, 1.0 + 0.0j) ai, bi = 0.0, 1.0 / norm else: u = self.samples.u(h ** 2, w, e1) v = self.samples.v(h ** 2, w, e2) knv = ssp.kv(n, v) knpv = ssp.kvp(n, v) jnu = ssp.jv(n, u) jnpu = ssp.jvp(n, u) ci = -n * (u ** 2 + v ** 2) * jnu * knv / (u * v) if pol == "E": ci *= (h / w) ** 2 ci /= e1 * jnpu * v * knv + e2 * knpv * u * jnu norm = self.norm(w, h, alpha, 1.0 + 0.0j, ci) ai = 1.0 / norm bi = ci / norm else: ci /= jnpu * v * knv + knpv * u * jnu norm = self.norm(w, h, alpha, ci, 1.0 + 0.0j) bi = 1.0 / norm ai = ci / norm return ai, bi def norm(self, w, h, alpha, a, b): pol, n, m = alpha en = 1 if n == 0 else 2 if self.clad(w).real < -1e6: radius = self.r if pol == "E": u = ssp.jnp_zeros(n, m)[-1] jnu = ssp.jv(n, u) jnpu = 0.0 else: u = ssp.jn_zeros(n, m)[-1] jnu = 0.0 jnpu = ssp.jvp(n, u) return cmath.sqrt( a ** 2 * np.pi * radius ** 2 / en * (1 - n ** 2 / u ** 2) * jnu ** 2 + b ** 2 * np.pi * radius ** 2 / en * jnpu ** 2 ) u = self.samples.u(h ** 2, w, self.fill(w)) jnu = ssp.jv(n, u) jnpu = ssp.jvp(n, u) v = self.samples.v(h ** 2, w, self.clad(w)) knv = ssp.kv(n, v) knpv = ssp.kvp(n, v) val_u = 2 * np.pi * self.r ** 2 / en val_v = val_u * ((u * jnu) / (v * knv)) ** 2 upart_diag = self.upart_diag(n, u, jnu, jnpu) vpart_diag = self.vpart_diag(n, v, knv, knpv) upart_off = self.upart_off(n, u, jnu) vpart_off = self.vpart_off(n, v, knv) return cmath.sqrt( val_u * ( a * (a * upart_diag + b * upart_off) + b * (b * upart_diag + a * upart_off) ) - val_v * ( a * (a * vpart_diag + b * vpart_off) + b * (b * vpart_diag + a * vpart_off) ) ) @staticmethod def upart_diag(n, u, jnu, jnpu): return jnu * jnpu / u + (jnpu ** 2 + (1 - n ** 2 / u ** 2) * jnu ** 2) / 2 @staticmethod def upart_off(n, u, jnu): return n * (jnu / u) ** 2 @staticmethod def vpart_diag(n, v, knv, knpv): return knv * knpv / v + (knpv ** 2 - (1 + n ** 2 / v ** 2) * knv ** 2) / 2 @staticmethod def vpart_off(n, v, knv): return n * (knv / v) ** 2 def Y( self, w: complex, h: complex, alpha: tuple[str, int, int], a: complex, b: complex, ) -> complex: pol, n, m = alpha e1 = self.fill(w) e2 = self.clad(w) en = 1 if n == 0 else 2 if e2.real < -1e6: if pol == "E": val = h / w else: val = e1 * w / h else: u = self.samples.u(h ** 2, w, e1) jnu = ssp.jv(n, u) jnpu = ssp.jvp(n, u) v = self.samples.v(h ** 2, w, e2) knv = ssp.kv(n, v) knpv = ssp.kvp(n, v) val_u = 2 * np.pi * self.r ** 2 / en val_v = val_u * ((u * jnu) / (v * knv)) ** 2 upart_diag = self.upart_diag(n, u, jnu, jnpu) vpart_diag = self.vpart_diag(n, v, knv, knpv) upart_off = self.upart_off(n, u, jnu) vpart_off = self.vpart_off(n, v, knv) val = val_u * ( h / w * a * (a * upart_diag + b * upart_off) + e1 * w / h * b * (b * upart_diag + a * upart_off) ) - val_v * ( h / w * a * (a * vpart_diag + b * vpart_off) + e2 * w / h * b * (b * vpart_diag + a * vpart_off) ) return val @staticmethod def y_te(w, h): return h / w def y_tm_inner(self, w, h): e = self.fill(w) return e * w / h def y_tm_outer(self, w, h): e = self.clad(w) return e * w / h def fields(self, x, y, w, dir, alpha, h, coef): pol, n, m = alpha a, b = coef r = np.hypot(x, y) p = np.arctan2(y, x) u = self.samples.u(h ** 2, w, self.fill(w)) v = self.samples.v(h ** 2, w, self.clad(w)) ur = u * r / self.r vr = v * r / self.r if dir == "h": fr = np.cos(n * p) fp = -np.sin(n * p) else: fr = np.sin(n * p) fp = np.cos(n * p) y_te = Cylinder.y_te(w, h) if r <= self.r: y_tm = self.y_tm_inner(w, h) er_te = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fr er_tm = ssp.jvp(n, ur) * fr er = a * er_te + b * er_tm ep_te = ssp.jvp(n, ur) * fp ep_tm = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fp ep = a * ep_te + b * ep_tm ez = u / (1j * h * self.r) * b * ssp.jv(n, ur) * fr hr = -y_te * a * ep_te - y_tm * b * ep_tm hp = y_te * a * er_te + y_tm * b * er_tm hz = -u / (1j * h * self.r) * y_te * a * ssp.jv(n, ur) * fp else: y_tm = self.y_tm_outer(w, h) val = -u * ssp.jv(n, u) / (v * ssp.kv(n, v)) er_te = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fr * val er_tm = ssp.kvp(n, vr) * fr * val er = a * er_te + b * er_tm ep_te = ssp.kvp(n, vr) * fp * val ep_tm = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fp * val ep = a * ep_te + b * ep_tm ez = -v / (1j * h * self.r) * b * ssp.kv(n, vr) * fr * val hr = -y_te * a * ep_te - y_tm * b * ep_tm hp = y_te * a * er_te + y_tm * b * er_tm hz = v / (1j * h * self.r) * y_te * a * ssp.kv(n, vr) * fp * val ex = er * np.cos(p) - ep * np.sin(p) ey = er * np.sin(p) + ep * np.cos(p) hx = hr * np.cos(p) - hp * np.sin(p) hy = hr * np.sin(p) + hp * np.cos(p) return np.array([ex, ey, ez, hx, hy, hz]) def e_field(self, x, y, w, dir, alpha, h, coef): pol, n, m = alpha a, b = coef r = np.hypot(x, y) p = np.arctan2(y, x) u = self.samples.u(h ** 2, w, self.fill(w)) v = self.samples.v(h ** 2, w, self.clad(w)) ur = u * r / self.r vr = v * r / self.r if dir == "h": fr = np.cos(n * p) fp = -np.sin(n * p) else: fr = np.sin(n * p) fp = np.cos(n * p) if r <= self.r: er_te = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fr er_tm = ssp.jvp(n, ur) * fr er = a * er_te + b * er_tm ep_te = ssp.jvp(n, ur) * fp ep_tm = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fp ep = a * ep_te + b * ep_tm ez = u / (1j * h * self.r) * b * ssp.jv(n, ur) * fr else: val = -u * ssp.jv(n, u) / (v * ssp.kv(n, v)) er_te = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fr * val er_tm = ssp.kvp(n, vr) * fr * val er = a * er_te + b * er_tm ep_te = ssp.kvp(n, vr) * fp * val ep_tm = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fp * val ep = a * ep_te + b * ep_tm ez = -v / (1j * h * self.r) * b * ssp.kv(n, vr) * fr * val ex = er * np.cos(p) - ep * np.sin(p) ey = er * np.sin(p) + ep * np.cos(p) return np.array([ex, ey, ez]) def h_field(self, x, y, w, dir, alpha, h, coef): pol, n, m = alpha a, b = coef r = np.hypot(x, y) p = np.arctan2(y, x) u = self.samples.u(h ** 2, w, self.fill(w)) v = self.samples.v(h ** 2, w, self.clad(w)) ur = u * r / self.r vr = v * r / self.r if dir == "h": fr = np.cos(n * p) fp = -np.sin(n * p) else: fr = np.sin(n * p) fp = np.cos(n * p) y_te = Cylinder.y_te(w, h) if r <= self.r: y_tm = self.y_tm_inner(w, h) er_te = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fr er_tm = ssp.jvp(n, ur) * fr ep_te = ssp.jvp(n, ur) * fp ep_tm = (ssp.jv(n - 1, ur) + ssp.jv(n + 1, ur)) / 2 * fp hr = -y_te * a * ep_te - y_tm * b * ep_tm hp = y_te * a * er_te + y_tm * b * er_tm hz = -u / (1j * h * self.r) * y_te * a * ssp.jv(n, ur) * fp else: y_tm = self.y_tm_outer(w, h) val = -u * ssp.jv(n, u) / (v * ssp.kv(n, v)) er_te = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fr * val er_tm = ssp.kvp(n, vr) * fr * val ep_te = ssp.kvp(n, vr) * fp * val ep_tm = -(ssp.kv(n - 1, vr) - ssp.kv(n + 1, vr)) / 2 * fp * val hr = -y_te * a * ep_te - y_tm * b * ep_tm hp = y_te * a * er_te + y_tm * b * er_tm hz = v / (1j * h * self.r) * y_te * a * ssp.kv(n, vr) * fp * val hx = hr * np.cos(p) - hp * np.sin(p) hy = hr * np.sin(p) + hp * np.cos(p) return np.array([hx, hy, hz]) @staticmethod def u_jnu_jnpu_pec(num_n, num_m): us = np.empty((2, num_n, num_m)) jnus = np.empty((2, num_n, num_m)) jnpus = np.empty((2, num_n, num_m)) for n in range(num_n): us[0, n] = ssp.jnp_zeros(n, num_m) us[1, n] = ssp.jn_zeros(n, num_m) jnus[0, n] = ssp.jv(n, us[0, n]) jnus[1, n] = np.zeros(num_m) jnpus[0, n] = np.zeros(num_m) jnpus[1, n] = ssp.jvp(n, us[1, n]) return us, jnus, jnpus def coefs(self, hs, w): As = [] Bs = [] for h, s, n, m in zip(hs, self.s_all, self.n_all, self.m_all): pol = "E" if s == 0 else "M" ai, bi = self.coef(h, w, (pol, n, m)) As.append(ai) Bs.append(bi) return np.ascontiguousarray(As), np.ascontiguousarray(Bs) def Ys(self, w, hs, As, Bs): vals = [] for h, s, n, a, b in zip(hs, self.s_all, self.n_all, As, Bs): pol = "E" if s == 0 else "M" vals.append(self.Y(w, h, (pol, n, 1), a, b)) return np.array(vals) def props_numpy(self, w): e1 = self.fill(w) e2 = self.clad(w) hs = np.array([self.beta(w, alpha) for alpha in self.alpha_all]) As, Bs = self.coefs(hs, w) Ys = self.Ys(w, hs, As, Bs) if e2.real < -1e6: us = np.zeros_like(hs, dtype=complex) jus = np.zeros_like(hs, dtype=complex) jpus = np.zeros_like(hs, dtype=complex) for i, (h, s, n, m) in enumerate( zip(hs, self.s_all, self.n_all, self.m_all) ): us[i] = self.u_pec[s, n, m - 1] jus[i] = self.jnu_pec[s, n, m - 1] jpus[i] = self.jnpu_pec[s, n, m - 1] vs = (1 - 1j) * np.sqrt(0.5j * (-e2 * w ** 2 + hs ** 2)) * self.r kvs = np.zeros_like(vs) kpvs = np.zeros_like(vs) else: us = self.samples.u(hs ** 2, w, e1) vs = self.samples.v(hs ** 2, w, e2) jus = ssp.jv(self.n_all, us) jpus = ssp.jvp(self.n_all, us) kvs = ssp.kv(self.n_all, vs) kpvs = ssp.kvp(self.n_all, vs) return hs, us, vs, jus, jpus, kvs, kpvs, As, Bs, Ys def props(self, w): e1 = self.fill(w) e2 = self.clad(w) hs = np.array([self.beta(w, alpha) for alpha in self.alpha_all]) us, vs, jus, jpus, kvs, kpvs, As, Bs, Ys = cylinder_utils.props_cython( w, self.r, self.s_all, self.n_all, self.m_all, hs, e1, e2, self.u_pec, self.jnu_pec, self.jnpu_pec, ) return hs, us, vs, jus, jpus, kvs, kpvs, As, Bs, Ys
true
true
1c372394c43365cc6edb330992a413a6145abc03
15,760
py
Python
homeassistant/setup.py
tafehe/ha-core
2478ec887aba87842bf52969b7ab1137826f7b98
[ "Apache-2.0" ]
5
2020-10-08T12:59:44.000Z
2021-12-28T06:46:25.000Z
homeassistant/setup.py
tafehe/ha-core
2478ec887aba87842bf52969b7ab1137826f7b98
[ "Apache-2.0" ]
75
2020-08-05T07:22:42.000Z
2022-03-23T21:54:57.000Z
homeassistant/setup.py
winning1120xx/home-assistant
53d4c0ce2d374b5e97bbdc37742656c27adf8eea
[ "Apache-2.0" ]
1
2021-08-01T06:12:13.000Z
2021-08-01T06:12:13.000Z
"""All methods needed to bootstrap a Home Assistant instance.""" from __future__ import annotations import asyncio from collections.abc import Awaitable, Generator, Iterable import contextlib import logging.handlers from timeit import default_timer as timer from types import ModuleType from typing import Callable from homeassistant import config as conf_util, core, loader, requirements from homeassistant.config import async_notify_setup_error from homeassistant.const import ( EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START, PLATFORM_FORMAT, ) from homeassistant.core import CALLBACK_TYPE from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.typing import ConfigType from homeassistant.util import dt as dt_util, ensure_unique_string # mypy: disallow-any-generics _LOGGER = logging.getLogger(__name__) ATTR_COMPONENT = "component" BASE_PLATFORMS = { "air_quality", "alarm_control_panel", "binary_sensor", "camera", "climate", "cover", "device_tracker", "fan", "humidifier", "image_processing", "light", "lock", "media_player", "notify", "number", "remote", "scene", "select", "sensor", "siren", "switch", "tts", "vacuum", "water_heater", "weather", } DATA_SETUP_DONE = "setup_done" DATA_SETUP_STARTED = "setup_started" DATA_SETUP_TIME = "setup_time" DATA_SETUP = "setup_tasks" DATA_DEPS_REQS = "deps_reqs_processed" SLOW_SETUP_WARNING = 10 SLOW_SETUP_MAX_WAIT = 300 @core.callback def async_set_domains_to_be_loaded(hass: core.HomeAssistant, domains: set[str]) -> None: """Set domains that are going to be loaded from the config. This will allow us to properly handle after_dependencies. """ hass.data[DATA_SETUP_DONE] = {domain: asyncio.Event() for domain in domains} def setup_component(hass: core.HomeAssistant, domain: str, config: ConfigType) -> bool: """Set up a component and all its dependencies.""" return asyncio.run_coroutine_threadsafe( async_setup_component(hass, domain, config), hass.loop ).result() async def async_setup_component( hass: core.HomeAssistant, domain: str, config: ConfigType ) -> bool: """Set up a component and all its dependencies. This method is a coroutine. """ if domain in hass.config.components: return True setup_tasks = hass.data.setdefault(DATA_SETUP, {}) if domain in setup_tasks: return await setup_tasks[domain] # type: ignore task = setup_tasks[domain] = hass.async_create_task( _async_setup_component(hass, domain, config) ) try: return await task # type: ignore finally: if domain in hass.data.get(DATA_SETUP_DONE, {}): hass.data[DATA_SETUP_DONE].pop(domain).set() async def _async_process_dependencies( hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration ) -> bool: """Ensure all dependencies are set up.""" dependencies_tasks = { dep: hass.loop.create_task(async_setup_component(hass, dep, config)) for dep in integration.dependencies if dep not in hass.config.components } after_dependencies_tasks = {} to_be_loaded = hass.data.get(DATA_SETUP_DONE, {}) for dep in integration.after_dependencies: if ( dep not in dependencies_tasks and dep in to_be_loaded and dep not in hass.config.components ): after_dependencies_tasks[dep] = hass.loop.create_task( to_be_loaded[dep].wait() ) if not dependencies_tasks and not after_dependencies_tasks: return True if dependencies_tasks: _LOGGER.debug( "Dependency %s will wait for dependencies %s", integration.domain, list(dependencies_tasks), ) if after_dependencies_tasks: _LOGGER.debug( "Dependency %s will wait for after dependencies %s", integration.domain, list(after_dependencies_tasks), ) async with hass.timeout.async_freeze(integration.domain): results = await asyncio.gather( *dependencies_tasks.values(), *after_dependencies_tasks.values() ) failed = [ domain for idx, domain in enumerate(dependencies_tasks) if not results[idx] ] if failed: _LOGGER.error( "Unable to set up dependencies of %s. Setup failed for dependencies: %s", integration.domain, ", ".join(failed), ) return False return True async def _async_setup_component( hass: core.HomeAssistant, domain: str, config: ConfigType ) -> bool: """Set up a component for Home Assistant. This method is a coroutine. """ def log_error(msg: str, link: str | None = None) -> None: """Log helper.""" _LOGGER.error("Setup failed for %s: %s", domain, msg) async_notify_setup_error(hass, domain, link) try: integration = await loader.async_get_integration(hass, domain) except loader.IntegrationNotFound: log_error("Integration not found.") return False if integration.disabled: log_error(f"Dependency is disabled - {integration.disabled}") return False # Validate all dependencies exist and there are no circular dependencies if not await integration.resolve_dependencies(): return False # Process requirements as soon as possible, so we can import the component # without requiring imports to be in functions. try: await async_process_deps_reqs(hass, config, integration) except HomeAssistantError as err: log_error(str(err), integration.documentation) return False # Some integrations fail on import because they call functions incorrectly. # So we do it before validating config to catch these errors. try: component = integration.get_component() except ImportError as err: log_error(f"Unable to import component: {err}", integration.documentation) return False except Exception: # pylint: disable=broad-except _LOGGER.exception("Setup failed for %s: unknown error", domain) return False processed_config = await conf_util.async_process_component_config( hass, config, integration ) if processed_config is None: log_error("Invalid config.", integration.documentation) return False start = timer() _LOGGER.info("Setting up %s", domain) with async_start_setup(hass, [domain]): if hasattr(component, "PLATFORM_SCHEMA"): # Entity components have their own warning warn_task = None else: warn_task = hass.loop.call_later( SLOW_SETUP_WARNING, _LOGGER.warning, "Setup of %s is taking over %s seconds.", domain, SLOW_SETUP_WARNING, ) task = None result = True try: if hasattr(component, "async_setup"): task = component.async_setup(hass, processed_config) # type: ignore elif hasattr(component, "setup"): # This should not be replaced with hass.async_add_executor_job because # we don't want to track this task in case it blocks startup. task = hass.loop.run_in_executor( None, component.setup, hass, processed_config # type: ignore ) elif not hasattr(component, "async_setup_entry"): log_error("No setup or config entry setup function defined.") return False if task: async with hass.timeout.async_timeout(SLOW_SETUP_MAX_WAIT, domain): result = await task except asyncio.TimeoutError: _LOGGER.error( "Setup of %s is taking longer than %s seconds." " Startup will proceed without waiting any longer", domain, SLOW_SETUP_MAX_WAIT, ) return False except Exception: # pylint: disable=broad-except _LOGGER.exception("Error during setup of component %s", domain) async_notify_setup_error(hass, domain, integration.documentation) return False finally: end = timer() if warn_task: warn_task.cancel() _LOGGER.info("Setup of domain %s took %.1f seconds", domain, end - start) if result is False: log_error("Integration failed to initialize.") return False if result is not True: log_error( f"Integration {domain!r} did not return boolean if setup was " "successful. Disabling component." ) return False # Flush out async_setup calling create_task. Fragile but covered by test. await asyncio.sleep(0) await hass.config_entries.flow.async_wait_init_flow_finish(domain) await asyncio.gather( *( entry.async_setup(hass, integration=integration) for entry in hass.config_entries.async_entries(domain) ) ) hass.config.components.add(domain) # Cleanup if domain in hass.data[DATA_SETUP]: hass.data[DATA_SETUP].pop(domain) hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: domain}) return True async def async_prepare_setup_platform( hass: core.HomeAssistant, hass_config: ConfigType, domain: str, platform_name: str ) -> ModuleType | None: """Load a platform and makes sure dependencies are setup. This method is a coroutine. """ platform_path = PLATFORM_FORMAT.format(domain=domain, platform=platform_name) def log_error(msg: str) -> None: """Log helper.""" _LOGGER.error("Unable to prepare setup for platform %s: %s", platform_path, msg) async_notify_setup_error(hass, platform_path) try: integration = await loader.async_get_integration(hass, platform_name) except loader.IntegrationNotFound: log_error("Integration not found") return None # Process deps and reqs as soon as possible, so that requirements are # available when we import the platform. try: await async_process_deps_reqs(hass, hass_config, integration) except HomeAssistantError as err: log_error(str(err)) return None try: platform = integration.get_platform(domain) except ImportError as exc: log_error(f"Platform not found ({exc}).") return None # Already loaded if platform_path in hass.config.components: return platform # Platforms cannot exist on their own, they are part of their integration. # If the integration is not set up yet, and can be set up, set it up. if integration.domain not in hass.config.components: try: component = integration.get_component() except ImportError as exc: log_error(f"Unable to import the component ({exc}).") return None if ( hasattr(component, "setup") or hasattr(component, "async_setup") ) and not await async_setup_component(hass, integration.domain, hass_config): log_error("Unable to set up component.") return None return platform async def async_process_deps_reqs( hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration ) -> None: """Process all dependencies and requirements for a module. Module is a Python module of either a component or platform. """ if (processed := hass.data.get(DATA_DEPS_REQS)) is None: processed = hass.data[DATA_DEPS_REQS] = set() elif integration.domain in processed: return if not await _async_process_dependencies(hass, config, integration): raise HomeAssistantError("Could not set up all dependencies.") if not hass.config.skip_pip and integration.requirements: async with hass.timeout.async_freeze(integration.domain): await requirements.async_get_integration_with_requirements( hass, integration.domain ) processed.add(integration.domain) @core.callback def async_when_setup( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], ) -> None: """Call a method when a component is setup.""" _async_when_setup(hass, component, when_setup_cb, False) @core.callback def async_when_setup_or_start( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], ) -> None: """Call a method when a component is setup or state is fired.""" _async_when_setup(hass, component, when_setup_cb, True) @core.callback def _async_when_setup( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], start_event: bool, ) -> None: """Call a method when a component is setup or the start event fires.""" async def when_setup() -> None: """Call the callback.""" try: await when_setup_cb(hass, component) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error handling when_setup callback for %s", component) if component in hass.config.components: hass.async_create_task(when_setup()) return listeners: list[CALLBACK_TYPE] = [] async def _matched_event(event: core.Event) -> None: """Call the callback when we matched an event.""" for listener in listeners: listener() await when_setup() async def _loaded_event(event: core.Event) -> None: """Call the callback if we loaded the expected component.""" if event.data[ATTR_COMPONENT] == component: await _matched_event(event) listeners.append(hass.bus.async_listen(EVENT_COMPONENT_LOADED, _loaded_event)) if start_event: listeners.append( hass.bus.async_listen(EVENT_HOMEASSISTANT_START, _matched_event) ) @core.callback def async_get_loaded_integrations(hass: core.HomeAssistant) -> set[str]: """Return the complete list of loaded integrations.""" integrations = set() for component in hass.config.components: if "." not in component: integrations.add(component) continue domain, platform = component.split(".", 1) if domain in BASE_PLATFORMS: integrations.add(platform) return integrations @contextlib.contextmanager def async_start_setup( hass: core.HomeAssistant, components: Iterable[str] ) -> Generator[None, None, None]: """Keep track of when setup starts and finishes.""" setup_started = hass.data.setdefault(DATA_SETUP_STARTED, {}) started = dt_util.utcnow() unique_components = {} for domain in components: unique = ensure_unique_string(domain, setup_started) unique_components[unique] = domain setup_started[unique] = started yield setup_time = hass.data.setdefault(DATA_SETUP_TIME, {}) time_taken = dt_util.utcnow() - started for unique, domain in unique_components.items(): del setup_started[unique] if "." in domain: _, integration = domain.split(".", 1) else: integration = domain if integration in setup_time: setup_time[integration] += time_taken else: setup_time[integration] = time_taken
32.361396
88
0.656789
from __future__ import annotations import asyncio from collections.abc import Awaitable, Generator, Iterable import contextlib import logging.handlers from timeit import default_timer as timer from types import ModuleType from typing import Callable from homeassistant import config as conf_util, core, loader, requirements from homeassistant.config import async_notify_setup_error from homeassistant.const import ( EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START, PLATFORM_FORMAT, ) from homeassistant.core import CALLBACK_TYPE from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.typing import ConfigType from homeassistant.util import dt as dt_util, ensure_unique_string _LOGGER = logging.getLogger(__name__) ATTR_COMPONENT = "component" BASE_PLATFORMS = { "air_quality", "alarm_control_panel", "binary_sensor", "camera", "climate", "cover", "device_tracker", "fan", "humidifier", "image_processing", "light", "lock", "media_player", "notify", "number", "remote", "scene", "select", "sensor", "siren", "switch", "tts", "vacuum", "water_heater", "weather", } DATA_SETUP_DONE = "setup_done" DATA_SETUP_STARTED = "setup_started" DATA_SETUP_TIME = "setup_time" DATA_SETUP = "setup_tasks" DATA_DEPS_REQS = "deps_reqs_processed" SLOW_SETUP_WARNING = 10 SLOW_SETUP_MAX_WAIT = 300 @core.callback def async_set_domains_to_be_loaded(hass: core.HomeAssistant, domains: set[str]) -> None: hass.data[DATA_SETUP_DONE] = {domain: asyncio.Event() for domain in domains} def setup_component(hass: core.HomeAssistant, domain: str, config: ConfigType) -> bool: return asyncio.run_coroutine_threadsafe( async_setup_component(hass, domain, config), hass.loop ).result() async def async_setup_component( hass: core.HomeAssistant, domain: str, config: ConfigType ) -> bool: if domain in hass.config.components: return True setup_tasks = hass.data.setdefault(DATA_SETUP, {}) if domain in setup_tasks: return await setup_tasks[domain] task = setup_tasks[domain] = hass.async_create_task( _async_setup_component(hass, domain, config) ) try: return await task finally: if domain in hass.data.get(DATA_SETUP_DONE, {}): hass.data[DATA_SETUP_DONE].pop(domain).set() async def _async_process_dependencies( hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration ) -> bool: dependencies_tasks = { dep: hass.loop.create_task(async_setup_component(hass, dep, config)) for dep in integration.dependencies if dep not in hass.config.components } after_dependencies_tasks = {} to_be_loaded = hass.data.get(DATA_SETUP_DONE, {}) for dep in integration.after_dependencies: if ( dep not in dependencies_tasks and dep in to_be_loaded and dep not in hass.config.components ): after_dependencies_tasks[dep] = hass.loop.create_task( to_be_loaded[dep].wait() ) if not dependencies_tasks and not after_dependencies_tasks: return True if dependencies_tasks: _LOGGER.debug( "Dependency %s will wait for dependencies %s", integration.domain, list(dependencies_tasks), ) if after_dependencies_tasks: _LOGGER.debug( "Dependency %s will wait for after dependencies %s", integration.domain, list(after_dependencies_tasks), ) async with hass.timeout.async_freeze(integration.domain): results = await asyncio.gather( *dependencies_tasks.values(), *after_dependencies_tasks.values() ) failed = [ domain for idx, domain in enumerate(dependencies_tasks) if not results[idx] ] if failed: _LOGGER.error( "Unable to set up dependencies of %s. Setup failed for dependencies: %s", integration.domain, ", ".join(failed), ) return False return True async def _async_setup_component( hass: core.HomeAssistant, domain: str, config: ConfigType ) -> bool: def log_error(msg: str, link: str | None = None) -> None: _LOGGER.error("Setup failed for %s: %s", domain, msg) async_notify_setup_error(hass, domain, link) try: integration = await loader.async_get_integration(hass, domain) except loader.IntegrationNotFound: log_error("Integration not found.") return False if integration.disabled: log_error(f"Dependency is disabled - {integration.disabled}") return False if not await integration.resolve_dependencies(): return False try: await async_process_deps_reqs(hass, config, integration) except HomeAssistantError as err: log_error(str(err), integration.documentation) return False try: component = integration.get_component() except ImportError as err: log_error(f"Unable to import component: {err}", integration.documentation) return False except Exception: _LOGGER.exception("Setup failed for %s: unknown error", domain) return False processed_config = await conf_util.async_process_component_config( hass, config, integration ) if processed_config is None: log_error("Invalid config.", integration.documentation) return False start = timer() _LOGGER.info("Setting up %s", domain) with async_start_setup(hass, [domain]): if hasattr(component, "PLATFORM_SCHEMA"): warn_task = None else: warn_task = hass.loop.call_later( SLOW_SETUP_WARNING, _LOGGER.warning, "Setup of %s is taking over %s seconds.", domain, SLOW_SETUP_WARNING, ) task = None result = True try: if hasattr(component, "async_setup"): task = component.async_setup(hass, processed_config) elif hasattr(component, "setup"): task = hass.loop.run_in_executor( None, component.setup, hass, processed_config # type: ignore ) elif not hasattr(component, "async_setup_entry"): log_error("No setup or config entry setup function defined.") return False if task: async with hass.timeout.async_timeout(SLOW_SETUP_MAX_WAIT, domain): result = await task except asyncio.TimeoutError: _LOGGER.error( "Setup of %s is taking longer than %s seconds." " Startup will proceed without waiting any longer", domain, SLOW_SETUP_MAX_WAIT, ) return False except Exception: # pylint: disable=broad-except _LOGGER.exception("Error during setup of component %s", domain) async_notify_setup_error(hass, domain, integration.documentation) return False finally: end = timer() if warn_task: warn_task.cancel() _LOGGER.info("Setup of domain %s took %.1f seconds", domain, end - start) if result is False: log_error("Integration failed to initialize.") return False if result is not True: log_error( f"Integration {domain!r} did not return boolean if setup was " "successful. Disabling component." ) return False # Flush out async_setup calling create_task. Fragile but covered by test. await asyncio.sleep(0) await hass.config_entries.flow.async_wait_init_flow_finish(domain) await asyncio.gather( *( entry.async_setup(hass, integration=integration) for entry in hass.config_entries.async_entries(domain) ) ) hass.config.components.add(domain) # Cleanup if domain in hass.data[DATA_SETUP]: hass.data[DATA_SETUP].pop(domain) hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: domain}) return True async def async_prepare_setup_platform( hass: core.HomeAssistant, hass_config: ConfigType, domain: str, platform_name: str ) -> ModuleType | None: platform_path = PLATFORM_FORMAT.format(domain=domain, platform=platform_name) def log_error(msg: str) -> None: _LOGGER.error("Unable to prepare setup for platform %s: %s", platform_path, msg) async_notify_setup_error(hass, platform_path) try: integration = await loader.async_get_integration(hass, platform_name) except loader.IntegrationNotFound: log_error("Integration not found") return None # Process deps and reqs as soon as possible, so that requirements are # available when we import the platform. try: await async_process_deps_reqs(hass, hass_config, integration) except HomeAssistantError as err: log_error(str(err)) return None try: platform = integration.get_platform(domain) except ImportError as exc: log_error(f"Platform not found ({exc}).") return None # Already loaded if platform_path in hass.config.components: return platform # Platforms cannot exist on their own, they are part of their integration. # If the integration is not set up yet, and can be set up, set it up. if integration.domain not in hass.config.components: try: component = integration.get_component() except ImportError as exc: log_error(f"Unable to import the component ({exc}).") return None if ( hasattr(component, "setup") or hasattr(component, "async_setup") ) and not await async_setup_component(hass, integration.domain, hass_config): log_error("Unable to set up component.") return None return platform async def async_process_deps_reqs( hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration ) -> None: if (processed := hass.data.get(DATA_DEPS_REQS)) is None: processed = hass.data[DATA_DEPS_REQS] = set() elif integration.domain in processed: return if not await _async_process_dependencies(hass, config, integration): raise HomeAssistantError("Could not set up all dependencies.") if not hass.config.skip_pip and integration.requirements: async with hass.timeout.async_freeze(integration.domain): await requirements.async_get_integration_with_requirements( hass, integration.domain ) processed.add(integration.domain) @core.callback def async_when_setup( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], ) -> None: _async_when_setup(hass, component, when_setup_cb, False) @core.callback def async_when_setup_or_start( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], ) -> None: _async_when_setup(hass, component, when_setup_cb, True) @core.callback def _async_when_setup( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], start_event: bool, ) -> None: async def when_setup() -> None: try: await when_setup_cb(hass, component) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error handling when_setup callback for %s", component) if component in hass.config.components: hass.async_create_task(when_setup()) return listeners: list[CALLBACK_TYPE] = [] async def _matched_event(event: core.Event) -> None: for listener in listeners: listener() await when_setup() async def _loaded_event(event: core.Event) -> None: if event.data[ATTR_COMPONENT] == component: await _matched_event(event) listeners.append(hass.bus.async_listen(EVENT_COMPONENT_LOADED, _loaded_event)) if start_event: listeners.append( hass.bus.async_listen(EVENT_HOMEASSISTANT_START, _matched_event) ) @core.callback def async_get_loaded_integrations(hass: core.HomeAssistant) -> set[str]: integrations = set() for component in hass.config.components: if "." not in component: integrations.add(component) continue domain, platform = component.split(".", 1) if domain in BASE_PLATFORMS: integrations.add(platform) return integrations @contextlib.contextmanager def async_start_setup( hass: core.HomeAssistant, components: Iterable[str] ) -> Generator[None, None, None]: setup_started = hass.data.setdefault(DATA_SETUP_STARTED, {}) started = dt_util.utcnow() unique_components = {} for domain in components: unique = ensure_unique_string(domain, setup_started) unique_components[unique] = domain setup_started[unique] = started yield setup_time = hass.data.setdefault(DATA_SETUP_TIME, {}) time_taken = dt_util.utcnow() - started for unique, domain in unique_components.items(): del setup_started[unique] if "." in domain: _, integration = domain.split(".", 1) else: integration = domain if integration in setup_time: setup_time[integration] += time_taken else: setup_time[integration] = time_taken
true
true
1c3723b9d06e9defea155a9527cedb42fac01add
975
py
Python
tests/integration/test_catboost_model_first_evaluate/test.py
uniquechao/ClickHouse
1533f9b9aad3e8e6135179f11b4d8fdc99ce4be6
[ "Apache-2.0" ]
18
2021-05-29T01:12:33.000Z
2021-11-18T12:34:48.000Z
tests/integration/test_catboost_model_first_evaluate/test.py
uniquechao/ClickHouse
1533f9b9aad3e8e6135179f11b4d8fdc99ce4be6
[ "Apache-2.0" ]
13
2019-06-06T09:45:53.000Z
2020-05-15T12:03:45.000Z
tests/integration/test_catboost_model_first_evaluate/test.py
uniquechao/ClickHouse
1533f9b9aad3e8e6135179f11b4d8fdc99ce4be6
[ "Apache-2.0" ]
22
2019-06-14T10:31:51.000Z
2020-10-12T14:57:44.000Z
import os import sys import time import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node = cluster.add_instance('node', stay_alive=True, main_configs=['config/models_config.xml']) def copy_file_to_container(local_path, dist_path, container_id): os.system("docker cp {local} {cont_id}:{dist}".format(local=local_path, cont_id=container_id, dist=dist_path)) @pytest.fixture(scope="module") def started_cluster(): try: cluster.start() copy_file_to_container(os.path.join(SCRIPT_DIR, 'model/.'), '/etc/clickhouse-server/model', node.docker_id) node.restart_clickhouse() yield cluster finally: cluster.shutdown() def test(started_cluster): node.query("select modelEvaluate('titanic', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);")
26.351351
115
0.718974
import os import sys import time import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node = cluster.add_instance('node', stay_alive=True, main_configs=['config/models_config.xml']) def copy_file_to_container(local_path, dist_path, container_id): os.system("docker cp {local} {cont_id}:{dist}".format(local=local_path, cont_id=container_id, dist=dist_path)) @pytest.fixture(scope="module") def started_cluster(): try: cluster.start() copy_file_to_container(os.path.join(SCRIPT_DIR, 'model/.'), '/etc/clickhouse-server/model', node.docker_id) node.restart_clickhouse() yield cluster finally: cluster.shutdown() def test(started_cluster): node.query("select modelEvaluate('titanic', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);")
true
true
1c372400c2ae24bca1f8114ea4e25800791a55a6
1,663
py
Python
src/test_wrapped_jira_connection_stub.py
riptano/argus
df1f7e772cdaa78632faff8198a12f8947f1dc6d
[ "Apache-2.0" ]
2
2018-02-05T18:13:32.000Z
2018-04-23T17:08:20.000Z
src/test_wrapped_jira_connection_stub.py
riptano/argus
df1f7e772cdaa78632faff8198a12f8947f1dc6d
[ "Apache-2.0" ]
119
2018-02-20T21:15:43.000Z
2019-03-08T20:43:10.000Z
src/test_wrapped_jira_connection_stub.py
riptano/argus
df1f7e772cdaa78632faff8198a12f8947f1dc6d
[ "Apache-2.0" ]
6
2018-02-01T23:01:20.000Z
2019-12-26T15:35:32.000Z
# Copyright 2018 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List from jira import Issue from jira.client import Project, ResultList class TestWrappedJiraConnectionStub: """ Test class used in place of JiraConnection for unit tests or other offline testing purposes """ name_prefix = 1 def __init__(self) -> None: self.prefix = TestWrappedJiraConnectionStub.name_prefix TestWrappedJiraConnectionStub.name_prefix += 1 def projects(self) -> List[Project]: result = list() for x in range(0, 10, 1): temp_project = Project(None, None) name = '{}_{}'.format(self.name_prefix, x) temp_project.name = name temp_project.key = name result.append(temp_project) return result @staticmethod def search_issues() -> ResultList: result = ResultList() for x in range(0, 10, 1): temp_issue = Issue(None, None) temp_issue.key = 'Test-{}'.format(x) temp_issue.updated = '2014-01-01 00:00:01' result.append(temp_issue) return result
31.377358
95
0.667468
from typing import List from jira import Issue from jira.client import Project, ResultList class TestWrappedJiraConnectionStub: name_prefix = 1 def __init__(self) -> None: self.prefix = TestWrappedJiraConnectionStub.name_prefix TestWrappedJiraConnectionStub.name_prefix += 1 def projects(self) -> List[Project]: result = list() for x in range(0, 10, 1): temp_project = Project(None, None) name = '{}_{}'.format(self.name_prefix, x) temp_project.name = name temp_project.key = name result.append(temp_project) return result @staticmethod def search_issues() -> ResultList: result = ResultList() for x in range(0, 10, 1): temp_issue = Issue(None, None) temp_issue.key = 'Test-{}'.format(x) temp_issue.updated = '2014-01-01 00:00:01' result.append(temp_issue) return result
true
true
1c37250c9fe8592bfe185b5e47473cb8c7e53064
263
py
Python
src/utoolbox/io/dataset/__init__.py
thhsieh00/utoolbox-core
e46704348d60985c205a16f41788d2c185e11fb6
[ "Apache-2.0" ]
3
2020-08-21T02:34:32.000Z
2021-04-06T06:56:46.000Z
src/utoolbox/io/dataset/__init__.py
liuyenting/utoolbox-core
d1430967458204b99780c547eaca60d066490946
[ "Apache-2.0" ]
null
null
null
src/utoolbox/io/dataset/__init__.py
liuyenting/utoolbox-core
d1430967458204b99780c547eaca60d066490946
[ "Apache-2.0" ]
null
null
null
from .base import ( MultiChannelDatasetIterator, MultiViewDatasetIterator, TiledDatasetIterator, TimeSeriesDatasetIterator, ) from .bdv import * from .latticescope import * from .mm import * from .smartspim import * from .zarr import *
21.916667
33
0.722433
from .base import ( MultiChannelDatasetIterator, MultiViewDatasetIterator, TiledDatasetIterator, TimeSeriesDatasetIterator, ) from .bdv import * from .latticescope import * from .mm import * from .smartspim import * from .zarr import *
true
true
1c3726518d310309c85699905ba246185a641c02
9,110
py
Python
buildingspy/tests/test_simulate_Dymola.py
lbl-srg/BuildingsPy
27d3c76a0974a70f06fc477cdb7d90f19f8f4552
[ "BSD-3-Clause-LBNL" ]
66
2015-01-26T15:57:05.000Z
2022-03-24T18:43:01.000Z
buildingspy/tests/test_simulate_Dymola.py
lbl-srg/BuildingsPy
27d3c76a0974a70f06fc477cdb7d90f19f8f4552
[ "BSD-3-Clause-LBNL" ]
259
2015-01-06T21:37:52.000Z
2022-03-07T18:02:38.000Z
buildingspy/tests/test_simulate_Dymola.py
lbl-srg/BuildingsPy
27d3c76a0974a70f06fc477cdb7d90f19f8f4552
[ "BSD-3-Clause-LBNL" ]
34
2015-01-14T11:35:57.000Z
2022-03-15T22:10:25.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # import unittest import os from buildingspy.simulate.Dymola import Simulator def _simulate(cas): """ Class to simulate models. This needs to be at the top-level for multiprocessing to be able to serialize it. """ from buildingspy.simulate.Dymola import Simulator packagePath = os.path.abspath(os.path.join("buildingspy", "tests")) s = Simulator(cas['model'], outputDirectory=f"out-{cas['tol']}", packagePath=packagePath) s.setTolerance(cas['tol']) s.simulate() class Test_simulate_Simulator(unittest.TestCase): """ This class contains the unit tests for :mod:`buildingspy.simulate.Dymola`. """ def setUp(self): """ This method creates a variable that points to an existing folder that contains a Modelica package. """ self._packagePath = os.path.abspath(os.path.join( "buildingspy", "tests")) def test_Constructor(self): """ Tests the :mod:`buildingspy.simulate.Dymola` constructor. """ Simulator( modelName="MyModelicaLibrary.myModel", outputDirectory="notSupported", packagePath=self._packagePath) # Check that this path does not exists with self.assertRaises(ValueError): Simulator( modelName="MyModelicaLibrary.myModel", outputDirectory="notSupported", packagePath="ThisIsAWrongPath") def test_setPackagePath(self): """ Tests the ``setPackagePath'' method. """ s = Simulator("MyModelicaLibrary.MyModel", packagePath=self._packagePath) # Try to load an existing path. p = os.path.abspath(os.path.join("buildingspy", "tests", "MyModelicaLibrary")) s.setPackagePath(p) # Try to load a not existing path. self.assertRaises(ValueError, s.setPackagePath, "ThisIsAWrongPath") def test_wrong_package_path_simulation(self): """ Tests reporting the exception if a simulation fails. """ with self.assertRaises(ValueError): Simulator( modelName="MyModelicaLibrary.MyModel", outputDirectory=".", packagePath="THIS IS NOT A VALID PACKAGE PATH") def test_translate(self): """ Tests the various add methods. """ s = Simulator("MyModelicaLibrary.MyModel", packagePath=self._packagePath) s.translate() def test_addMethods(self): """ Tests the various add methods. """ import numpy as np from buildingspy.io.outputfile import Reader s = Simulator("MyModelicaLibrary.MyModel", packagePath=self._packagePath) s.addPreProcessingStatement("Advanced.StoreProtectedVariables:= true;") s.addPostProcessingStatement("Advanced.StoreProtectedVariables:= false;") s.addModelModifier( "redeclare Modelica.Blocks.Sources.Step source(offset=-0.1, height=1.1, startTime=0.5)") s.setStartTime(-1) s.setStopTime(5) s.setTimeOut(600) s.setTolerance(1e-4) s.setSolver("dassl") s.setNumberOfIntervals(50) s.setResultFile("myResults") s.exitSimulator(True) # s.deleteOutputFiles() s.showGUI(False) # s.printModelAndTime() s.showProgressBar(False) s.simulate() # Read the result and test their validity outDir = s.getOutputDirectory() resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat")) r = Reader(resultFile, "dymola") np.testing.assert_allclose(1.0, r.max('source.y')) np.testing.assert_allclose(0.725, r.mean('source.y')) np.testing.assert_allclose(0.725 * 6, r.integral('source.y')) np.testing.assert_allclose(-0.1, r.min('source.y')) # Delete output files s.deleteOutputFiles() def test_addGetParameters(self): """ Tests the :mod:`buildingspy.simulate.Dymola.addParameters` and the :mod:`buildingspy.simulate.Dymola.getParameters` functions. """ s = Simulator("myPackage.myModel", packagePath=self._packagePath) # Make sure values are added correctly s.addParameters({'PID.k': 1.0, 'valve.m_flow_nominal': 0.1}) self.assertEqual(sorted(s.getParameters()), [('PID.k', 1.0), ('valve.m_flow_nominal', 0.1)]) # Add one more parameter s.addParameters({'PID.t': 10.0}) self.assertEqual(sorted(s.getParameters()), [ ('PID.k', 1.0), ('PID.t', 10.0), ('valve.m_flow_nominal', 0.1)]) # Arguments must be a dictionary self.assertRaises(ValueError, s.addParameters, ["aaa", "bbb"]) def test_addVectorOfParameterValues(self): """ Tests the :mod:`buildingspy.simulate.Dymola.addParameters` function for the situation where values for a parameter that is a vector is added. """ import numpy as np from buildingspy.io.outputfile import Reader # Delete output file resultFile = os.path.join("Constants.mat") if os.path.exists(resultFile): os.remove(resultFile) s = Simulator("MyModelicaLibrary.Examples.Constants", packagePath=self._packagePath) s.addParameters({'const1.k': [2, 3]}) s.addParameters({'const2.k': [[1.1, 1.2], [2.1, 2.2], [3.1, 3.2]]}) s.addParameters({'const3.k': 0}) s.simulate() r = Reader(resultFile, "dymola") np.testing.assert_allclose(2, r.max('const1[1].y')) np.testing.assert_allclose(3, r.max('const1[2].y')) np.testing.assert_allclose(1.1, r.max('const2[1, 1].y')) np.testing.assert_allclose(1.2, r.max('const2[1, 2].y')) np.testing.assert_allclose(2.1, r.max('const2[2, 1].y')) np.testing.assert_allclose(2.2, r.max('const2[2, 2].y')) np.testing.assert_allclose(3.1, r.max('const2[3, 1].y')) np.testing.assert_allclose(3.2, r.max('const2[3, 2].y')) np.testing.assert_allclose(0, r.max('const3.y')) # Delete output files s.deleteOutputFiles() def test_setBooleanParameterValues(self): """ Tests the :mod:`buildingspy.simulate.Dymola.addParameters` function for boolean parameters. """ from buildingspy.io.outputfile import Reader # Delete output file resultFile = os.path.join("BooleanParameters.mat") if os.path.exists(resultFile): os.remove(resultFile) s = Simulator("MyModelicaLibrary.Examples.BooleanParameters", packagePath=self._packagePath) s.addParameters({'p1': True}) s.addParameters({'p2': False}) s.simulate() r = Reader(resultFile, "dymola") (_, p) = r.values('p1') self.assertEqual(p[0], 1.0) (_, p) = r.values('p2') self.assertEqual(p[0], 0.0) # Delete output files s.deleteOutputFiles() def test_timeout(self, timeout=3): model = 'MyModelicaLibrary.MyModelTimeOut' s = Simulator( model, packagePath=self._packagePath ) s._deleteTemporaryDirectory = False outDir = os.path.abspath(s.getOutputDirectory()) s.setTimeOut(timeout) with self.assertRaises(TimeoutError): s.simulate() with open(os.path.join(outDir, s._reporter._logFil)) as fh: log = fh.read() self.assertTrue('Terminating simulation' in log and 'Process timeout' in log) s.setTimeOut(-1) s.simulate() with open(os.path.join(outDir, 'dslog.txt')) as fh: log = fh.read() self.assertTrue('Integration terminated successfully' in log) def test_multiprocessing(self): import os import shutil from multiprocessing import Pool import json def _deleteDirs(cases): for cas in cases: output_dir = f"out-{cas['tol']}" shutil.rmtree(output_dir, ignore_errors=True) cases = [ {"model": "MyModelicaLibrary.Examples.MyStep", "tol": 1E-6}, {"model": "MyModelicaLibrary.Examples.MyStep", "tol": 1E-7} ] # Delete old directories _deleteDirs(cases) p = Pool() p.map(_simulate, cases) # Check output for success for cas in cases: resultFile = os.path.join(f"out-{cas['tol']}", "dslog.txt") self.assertTrue( os.path.exists(resultFile), f"File {resultFile} does not exist.") with open(resultFile) as f: con = f.read() self.assertTrue("Integration terminated successfully" in con, f"Expected string 'Integration terminated successfully' in {resultFile}") # Delete working directories _deleteDirs(cases) return if __name__ == '__main__': unittest.main()
34.770992
101
0.602086
import unittest import os from buildingspy.simulate.Dymola import Simulator def _simulate(cas): from buildingspy.simulate.Dymola import Simulator packagePath = os.path.abspath(os.path.join("buildingspy", "tests")) s = Simulator(cas['model'], outputDirectory=f"out-{cas['tol']}", packagePath=packagePath) s.setTolerance(cas['tol']) s.simulate() class Test_simulate_Simulator(unittest.TestCase): def setUp(self): self._packagePath = os.path.abspath(os.path.join( "buildingspy", "tests")) def test_Constructor(self): Simulator( modelName="MyModelicaLibrary.myModel", outputDirectory="notSupported", packagePath=self._packagePath) with self.assertRaises(ValueError): Simulator( modelName="MyModelicaLibrary.myModel", outputDirectory="notSupported", packagePath="ThisIsAWrongPath") def test_setPackagePath(self): s = Simulator("MyModelicaLibrary.MyModel", packagePath=self._packagePath) p = os.path.abspath(os.path.join("buildingspy", "tests", "MyModelicaLibrary")) s.setPackagePath(p) self.assertRaises(ValueError, s.setPackagePath, "ThisIsAWrongPath") def test_wrong_package_path_simulation(self): with self.assertRaises(ValueError): Simulator( modelName="MyModelicaLibrary.MyModel", outputDirectory=".", packagePath="THIS IS NOT A VALID PACKAGE PATH") def test_translate(self): s = Simulator("MyModelicaLibrary.MyModel", packagePath=self._packagePath) s.translate() def test_addMethods(self): import numpy as np from buildingspy.io.outputfile import Reader s = Simulator("MyModelicaLibrary.MyModel", packagePath=self._packagePath) s.addPreProcessingStatement("Advanced.StoreProtectedVariables:= true;") s.addPostProcessingStatement("Advanced.StoreProtectedVariables:= false;") s.addModelModifier( "redeclare Modelica.Blocks.Sources.Step source(offset=-0.1, height=1.1, startTime=0.5)") s.setStartTime(-1) s.setStopTime(5) s.setTimeOut(600) s.setTolerance(1e-4) s.setSolver("dassl") s.setNumberOfIntervals(50) s.setResultFile("myResults") s.exitSimulator(True) s.showGUI(False) s.showProgressBar(False) s.simulate() outDir = s.getOutputDirectory() resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat")) r = Reader(resultFile, "dymola") np.testing.assert_allclose(1.0, r.max('source.y')) np.testing.assert_allclose(0.725, r.mean('source.y')) np.testing.assert_allclose(0.725 * 6, r.integral('source.y')) np.testing.assert_allclose(-0.1, r.min('source.y')) s.deleteOutputFiles() def test_addGetParameters(self): s = Simulator("myPackage.myModel", packagePath=self._packagePath) s.addParameters({'PID.k': 1.0, 'valve.m_flow_nominal': 0.1}) self.assertEqual(sorted(s.getParameters()), [('PID.k', 1.0), ('valve.m_flow_nominal', 0.1)]) s.addParameters({'PID.t': 10.0}) self.assertEqual(sorted(s.getParameters()), [ ('PID.k', 1.0), ('PID.t', 10.0), ('valve.m_flow_nominal', 0.1)]) self.assertRaises(ValueError, s.addParameters, ["aaa", "bbb"]) def test_addVectorOfParameterValues(self): import numpy as np from buildingspy.io.outputfile import Reader resultFile = os.path.join("Constants.mat") if os.path.exists(resultFile): os.remove(resultFile) s = Simulator("MyModelicaLibrary.Examples.Constants", packagePath=self._packagePath) s.addParameters({'const1.k': [2, 3]}) s.addParameters({'const2.k': [[1.1, 1.2], [2.1, 2.2], [3.1, 3.2]]}) s.addParameters({'const3.k': 0}) s.simulate() r = Reader(resultFile, "dymola") np.testing.assert_allclose(2, r.max('const1[1].y')) np.testing.assert_allclose(3, r.max('const1[2].y')) np.testing.assert_allclose(1.1, r.max('const2[1, 1].y')) np.testing.assert_allclose(1.2, r.max('const2[1, 2].y')) np.testing.assert_allclose(2.1, r.max('const2[2, 1].y')) np.testing.assert_allclose(2.2, r.max('const2[2, 2].y')) np.testing.assert_allclose(3.1, r.max('const2[3, 1].y')) np.testing.assert_allclose(3.2, r.max('const2[3, 2].y')) np.testing.assert_allclose(0, r.max('const3.y')) s.deleteOutputFiles() def test_setBooleanParameterValues(self): from buildingspy.io.outputfile import Reader resultFile = os.path.join("BooleanParameters.mat") if os.path.exists(resultFile): os.remove(resultFile) s = Simulator("MyModelicaLibrary.Examples.BooleanParameters", packagePath=self._packagePath) s.addParameters({'p1': True}) s.addParameters({'p2': False}) s.simulate() r = Reader(resultFile, "dymola") (_, p) = r.values('p1') self.assertEqual(p[0], 1.0) (_, p) = r.values('p2') self.assertEqual(p[0], 0.0) s.deleteOutputFiles() def test_timeout(self, timeout=3): model = 'MyModelicaLibrary.MyModelTimeOut' s = Simulator( model, packagePath=self._packagePath ) s._deleteTemporaryDirectory = False outDir = os.path.abspath(s.getOutputDirectory()) s.setTimeOut(timeout) with self.assertRaises(TimeoutError): s.simulate() with open(os.path.join(outDir, s._reporter._logFil)) as fh: log = fh.read() self.assertTrue('Terminating simulation' in log and 'Process timeout' in log) s.setTimeOut(-1) s.simulate() with open(os.path.join(outDir, 'dslog.txt')) as fh: log = fh.read() self.assertTrue('Integration terminated successfully' in log) def test_multiprocessing(self): import os import shutil from multiprocessing import Pool import json def _deleteDirs(cases): for cas in cases: output_dir = f"out-{cas['tol']}" shutil.rmtree(output_dir, ignore_errors=True) cases = [ {"model": "MyModelicaLibrary.Examples.MyStep", "tol": 1E-6}, {"model": "MyModelicaLibrary.Examples.MyStep", "tol": 1E-7} ] _deleteDirs(cases) p = Pool() p.map(_simulate, cases) for cas in cases: resultFile = os.path.join(f"out-{cas['tol']}", "dslog.txt") self.assertTrue( os.path.exists(resultFile), f"File {resultFile} does not exist.") with open(resultFile) as f: con = f.read() self.assertTrue("Integration terminated successfully" in con, f"Expected string 'Integration terminated successfully' in {resultFile}") _deleteDirs(cases) return if __name__ == '__main__': unittest.main()
true
true
1c3727033a8d05e6d0f8cdbbab323598d378be11
9,487
py
Python
Shear_Ratio_Test/cosmology.py
KiDS-WL/Cat_to_Obs_K1000_P1
0de7f79cab150416859ffe58ac2d0f5659aedb5d
[ "MIT" ]
7
2020-11-18T12:58:03.000Z
2021-07-01T08:54:29.000Z
Shear_Ratio_Test/cosmology.py
KiDS-WL/Cat_to_Obs_K1000_P1
0de7f79cab150416859ffe58ac2d0f5659aedb5d
[ "MIT" ]
null
null
null
Shear_Ratio_Test/cosmology.py
KiDS-WL/Cat_to_Obs_K1000_P1
0de7f79cab150416859ffe58ac2d0f5659aedb5d
[ "MIT" ]
3
2020-12-09T13:30:22.000Z
2022-03-02T01:40:13.000Z
#!/usr/bin/env python # From Hendrik import math, string, sys, os import scipy import scipy.integrate def norm(k_vec): # the norm of a 3d vector return math.sqrt(k_vec[0]**2+k_vec[1]**2+k_vec[2]**2) def W_k(k_vec): # the Fourier transform of the survey volume a=k_vec[0]*l[0]/2 b=k_vec[1]*l[1]/2 c=k_vec[2]**2*l[2]**2/2 return exp(-c)*math.sin(a)/a*math.sin(b)/b def f_k(k,R): # the Fourier transform of a spherical top-hat with radius R y=R*k return 3/y**3*(math.sin(y)-y*math.cos(y)) class Cosmology: """This class computes various cosmological quantities like comoving, angular diameter, luminosity distance, lookback time etc.. Distance definitions are from Hogg 1999, astro-ph/9905116. """ def __init__(self, omega_m=0.27, omega_l=0.73, h=0.7, Gamma=0.2, n_s=1.0, sigma_8=0.81): self.omega_m = omega_m self.omega_l = omega_l self.omega_k = 1. - self.omega_m - self.omega_l self.h = h self.c = 2.99792458E8 # speed of light in m/s self.pc = 3.085678E16 # parsec in metres self.G = 6.673E-11 # Gravitational constant self.M_sun = 1.98892E30 # solar mass in kg self.H_0 = self.h * 100. * 1.E3 / 1.E6 / self.pc # Hubble constant in SI units self.dh = 3000./self.h # Hubble distance (Hogg eq. 4) in Mpc. self.th = 9.78e9/self.h # Hubble time in years self.th_sec = 3.09e17/self.h # Hubble time in seconds self.Gamma=Gamma # should be calculated by gamma=omega_m*h*exp(-omega_b*(1 + sqrt(2*h)/omega_m)) self.n_s=n_s self.sigma_8=sigma_8 self.norm_int=1/(2*math.pi)**3 * 4*math.pi * scipy.integrate.quad(lambda k: k**2*self.P_L(k)*f_k(k,8.0)**2, 0, scipy.Inf)[0] self.A=self.sigma_8**2/self.norm_int self.ro_0=2.77786E11 # critical density in M_sun/Mpc**3 self.dlnsigma_dlnM=(math.log(self.sigma_M(10.**15))-math.log(self.sigma_M(10.**5)))/(math.log(15)-math.log(5)) return def Ez(self, z): """E(z) function of Hogg's equation 14""" e = math.sqrt(self.omega_m*(1+z)**3 + self.omega_k*(1+z)**2 \ + self.omega_l) return e def ooEz(self, z): """Returns 1/E(z), E(z) being Hogg's eq. 14.""" return 1./self.Ez(z) def ooEzopz(self, z): """Returns 1/(E(z)*(1+z)), E(z) being Hogg's eq. 14.""" return 1./(self.Ez(z)*(1+z)) def dcom_los(self, z1, z2): """Returns the line of sight comoving distance between objects at redshifts z1 and z2, z2>z1. Value is in Mpc/h""" if z1>=z2: print("z2 must be greater than z1") return -1 dclos = self.dh * scipy.integrate.quad(self.ooEz, z1, z2)[0] return dclos def dcom_tra(self, z1, z2): """Returns the transverse comoving distance (proper motion distance) between objects at redshift z1 and z2.""" dcl = self.dcom_los(z1, z2) if self.omega_k == 0.0: dct = dcl elif self.omega_k > 0: dct = self.dh / math.sqrt(self.omega_k) \ * math.sinh(math.sqrt(self.omega_k)*dcl/self.dh) else: dct = self.dh / math.sqrt(math.fabs(self.omega_k)) \ * math.sin(math.sqrt(math.fabs(self.omega_k))*dcl/self.dh) return dct def dang(self, z1, z2): """Returns the angular diameter distance between objects at redshift z1 and z2.""" dct = self.dcom_tra(z1, z2) return dct/(1+z2) def dlum(self, z1, z2): """Returns the luminosity distance between objects at redshift z1 and z2. WARNING! WARNING! This function is untested for z1>0! WARNING! WARNING! """ dct = self.dcom_tra(z1, z2) return (1+z2)/(1+z1) * dct def covol(self, z): """Returns the comoving volume element d V_c in a solid angle d Omaga at redshift z.""" da = self.dang(0, z) return self.dh * (1+z)**2 * da**2 / self.Ez(z) def tlook(self, z): """This function returns the lookback time in units of the Hubble time. The Hubble time can be accessed as the attributes th (in years) or th_sec (in seconds).""" tl = scipy.integrate.quad(self.ooEzopz, 0, z)[0] return tl def DM(self, z1, z2): """Returns the distance modulus between objects at redshift z1 and z2. """ x=self.dlum(z1,z2) return 5*math.log(x/1.e-5)/math.log(10) def rho_crit(self, z1): """Returns the critical density at z1 in SI units. """ return 3*(self.Ez(z1)*self.H_0)**2/(8*math.pi*self.G) def Sigma_crit(self, z1, z2): """Returns the critical surface mass density for lenses at z1 and sources at z2 in SI units. """ return self.c**2/(4*math.pi*self.G)*self.dang(0.,z2)/(self.dang(0.,z1)*self.dang(z1,z2))/(1.E6*self.pc)*self.h ########## Power spectrum and mass function ############# def T_k(self, k): # the Transfer function q=k/self.Gamma T=math.log(1+2.34*q)/(2.34*q)*(1+3.89*q+(16.1*q)**2+(5.46*q)**3+(6.71*q)**4)**(-0.25) return T def H_sqd(self, a1): # the Hubble parameter H=(100.*self.h)**2*(self.omega_m/(a1**3)+self.omega_l) return H def D_plus(self, a2): # the growth factor def func(x): return 1/(self.omega_m/x+self.omega_l*x**2)**1.5 integral=scipy.integrate.quad(func,0,a2) integral_0=scipy.integrate.quad(func,0,1) D_a=math.sqrt(self.H_sqd(a2))/100.*integral[0] D_0=math.sqrt(self.H_sqd(1))/100.*integral_0[0] return D_a/D_0 def D_plus2(self, a2): # the growth factor om = self.omega_m/(a2+self.omega_m*(1.-a2)+self.omega_l*a2*(a2*a2-1.)) ol = self.omega_l*a2*a2*a2/(a2+self.omega_m*(1.-a2)+self.omega_l*a2*(a2*a2-1.)) g1 = 5./2.*self.omega_m/(self.omega_m**(4./7.)-self.omega_l+(1+self.omega_m/2.0)*(1.0+self.omega_l/70.0)) g = 5./2.*om/(om**(4./7.)-ol+(1+om/2.0)*(1.0+ol/70.0)) return a2*g/g1 def P_L(self, k): # the linear CDM power spectrum P=self.T_k(k)**2*k**self.n_s return P def P_L_norm(self, k): # the normalised, linear CDM power spectrum P=self.A*self.T_k(k)**2*k**self.n_s return P def P_L_norm_z(self, k, z): # the normalised, linear CDM power spectrum P=self.A*self.T_k(k)**2*k**self.n_s*self.D_plus(1/(1+z)) return P def d_ln_P_L_norm(self, k): # derivative of the normalised, linear CDM power spectrum P=(math.log(self.P_L_norm(k+k/1000.))-math.log(self.P_L_norm(k-k/1000.)))/(math.log(k+k/1000.)-math.log(k-k/1000.)) return P def d_ln_P_L_norm_z(self, k,z): # derivative of the normalised, linear CDM power spectrum P=(math.log(self.P_L_norm_z(k+k/1000.,z))-math.log(self.P_L_norm_z(k-k/1000.,z)))/(math.log(k+k/1000.)-math.log(k-k/1000.)) return P def Delta_sq_L_norm(self, k): # the normalised, linear, dimensionless CDM power spectrum P=self.A*self.T_k(k)**2*k**self.n_s*k**3/(2*math.pi**2) return P def Delta_sq_L_norm_z(self, k,z): # the normalised, linear, dimensionless CDM power spectrum P=self.A*self.T_k(k)**2*k**self.n_s*k**3/(2*math.pi**2)*self.D_plus(1/(1+z)) return P def sigma_M(self, M): def func(k,R): return k**2*self.P_L_norm(k)*f_k(k,R) R=(M/self.ro_0*3/4/math.pi)**(1/3.) integrand=scipy.integrate.quad(func, 0, scipy.Inf, args=(R), limit=50000)[0] return R #1/(2*math.pi**2)*integrand def Jenkins(self, M): return 0.315*self.ro_0/M**2*self.dlnsigma_dlnM*math.exp(-math.sqrt((0.61-math.log(self.sigma_M(M)))**2)**3.8) def f96(self, x, n_eff): # Peacock and Dodds 1996 fitting formula A_c=0.482*(1.+n_eff/3.)**(-0.947) B_c=0.226*(1.+n_eff/3.)**(-1.778) alpha_c=3.310*(1.+n_eff/3.)**(-0.244) beta_c=0.862*(1.+n_eff/3.)**(-0.287) V_c=11.55*(1.+n_eff/3.)**(-0.423) g=5./2.*self.omega_m*(self.omega_m**(4./7.)-self.omega_l+(1+self.omega_m/2)*(1+self.omega_l/70))**(-1) return x*((1+B_c*beta_c*x+(A_c*x)**(alpha_c*beta_c))/(1+((A_c*x)**alpha_c*g**3/(V_c*x**0.5))**beta_c))**(1/beta_c) def Delta_sq_NL_PD96_norm(self, k_L): # the normalised, non-linear, dimensionless CDM power spectrum from Peacock and Dodds 1996 n_eff=self.d_ln_P_L_norm(k_L/2.) return self.f96(self.Delta_sq_L_norm(k_L), n_eff) def Delta_sq_NL_PD96_norm_z(self, k_L,z): # the normalised, non-linear, dimensionless CDM power spectrum from Peacock and Dodds 1996 n_eff=self.d_ln_P_L_norm_z(k_L/2.,z) return self.f96(self.Delta_sq_L_norm_z(k_L,z), n_eff) def P_NL_PD96_norm(self, k): # the normalised, non-linear CDM power spectrum from Peacock and Dodds 1996 return self.Delta_sq_NL_PD96_norm(k)*((k/self.k_L_over_k_NL_PD96(self.Delta_sq_NL_PD96_norm(k)))**3/(2*math.pi**2))**(-1) def P_NL_PD96_norm_z(self, k, z): # the normalised, non-linear CDM power spectrum from Peacock and Dodds 1996 return self.Delta_sq_NL_PD96_norm_z(k,z)*((k/self.k_L_over_k_NL_PD96(self.Delta_sq_NL_PD96_norm_z(k,z)))**3/(2*math.pi**2))**(-1) def k_L_over_k_NL_PD96(self, Delta): return (1+Delta)**(-1./3.)
41.069264
137
0.592495
import math, string, sys, os import scipy import scipy.integrate def norm(k_vec): return math.sqrt(k_vec[0]**2+k_vec[1]**2+k_vec[2]**2) def W_k(k_vec): a=k_vec[0]*l[0]/2 b=k_vec[1]*l[1]/2 c=k_vec[2]**2*l[2]**2/2 return exp(-c)*math.sin(a)/a*math.sin(b)/b def f_k(k,R): y=R*k return 3/y**3*(math.sin(y)-y*math.cos(y)) class Cosmology: def __init__(self, omega_m=0.27, omega_l=0.73, h=0.7, Gamma=0.2, n_s=1.0, sigma_8=0.81): self.omega_m = omega_m self.omega_l = omega_l self.omega_k = 1. - self.omega_m - self.omega_l self.h = h self.c = 2.99792458E8 self.pc = 3.085678E16 self.G = 6.673E-11 self.M_sun = 1.98892E30 self.H_0 = self.h * 100. * 1.E3 / 1.E6 / self.pc self.dh = 3000./self.h self.th = 9.78e9/self.h self.th_sec = 3.09e17/self.h self.Gamma=Gamma self.n_s=n_s self.sigma_8=sigma_8 self.norm_int=1/(2*math.pi)**3 * 4*math.pi * scipy.integrate.quad(lambda k: k**2*self.P_L(k)*f_k(k,8.0)**2, 0, scipy.Inf)[0] self.A=self.sigma_8**2/self.norm_int self.ro_0=2.77786E11 self.dlnsigma_dlnM=(math.log(self.sigma_M(10.**15))-math.log(self.sigma_M(10.**5)))/(math.log(15)-math.log(5)) return def Ez(self, z): e = math.sqrt(self.omega_m*(1+z)**3 + self.omega_k*(1+z)**2 \ + self.omega_l) return e def ooEz(self, z): return 1./self.Ez(z) def ooEzopz(self, z): return 1./(self.Ez(z)*(1+z)) def dcom_los(self, z1, z2): if z1>=z2: print("z2 must be greater than z1") return -1 dclos = self.dh * scipy.integrate.quad(self.ooEz, z1, z2)[0] return dclos def dcom_tra(self, z1, z2): dcl = self.dcom_los(z1, z2) if self.omega_k == 0.0: dct = dcl elif self.omega_k > 0: dct = self.dh / math.sqrt(self.omega_k) \ * math.sinh(math.sqrt(self.omega_k)*dcl/self.dh) else: dct = self.dh / math.sqrt(math.fabs(self.omega_k)) \ * math.sin(math.sqrt(math.fabs(self.omega_k))*dcl/self.dh) return dct def dang(self, z1, z2): dct = self.dcom_tra(z1, z2) return dct/(1+z2) def dlum(self, z1, z2): dct = self.dcom_tra(z1, z2) return (1+z2)/(1+z1) * dct def covol(self, z): da = self.dang(0, z) return self.dh * (1+z)**2 * da**2 / self.Ez(z) def tlook(self, z): tl = scipy.integrate.quad(self.ooEzopz, 0, z)[0] return tl def DM(self, z1, z2): x=self.dlum(z1,z2) return 5*math.log(x/1.e-5)/math.log(10) def rho_crit(self, z1): return 3*(self.Ez(z1)*self.H_0)**2/(8*math.pi*self.G) def Sigma_crit(self, z1, z2): return self.c**2/(4*math.pi*self.G)*self.dang(0.,z2)/(self.dang(0.,z1)*self.dang(z1,z2))/(1.E6*self.pc)*self.h sqd(1))/100.*integral_0[0] return D_a/D_0 def D_plus2(self, a2): om = self.omega_m/(a2+self.omega_m*(1.-a2)+self.omega_l*a2*(a2*a2-1.)) ol = self.omega_l*a2*a2*a2/(a2+self.omega_m*(1.-a2)+self.omega_l*a2*(a2*a2-1.)) g1 = 5./2.*self.omega_m/(self.omega_m**(4./7.)-self.omega_l+(1+self.omega_m/2.0)*(1.0+self.omega_l/70.0)) g = 5./2.*om/(om**(4./7.)-ol+(1+om/2.0)*(1.0+ol/70.0)) return a2*g/g1 def P_L(self, k): P=self.T_k(k)**2*k**self.n_s return P def P_L_norm(self, k): P=self.A*self.T_k(k)**2*k**self.n_s return P def P_L_norm_z(self, k, z): P=self.A*self.T_k(k)**2*k**self.n_s*self.D_plus(1/(1+z)) return P def d_ln_P_L_norm(self, k): P=(math.log(self.P_L_norm(k+k/1000.))-math.log(self.P_L_norm(k-k/1000.)))/(math.log(k+k/1000.)-math.log(k-k/1000.)) return P def d_ln_P_L_norm_z(self, k,z): P=(math.log(self.P_L_norm_z(k+k/1000.,z))-math.log(self.P_L_norm_z(k-k/1000.,z)))/(math.log(k+k/1000.)-math.log(k-k/1000.)) return P def Delta_sq_L_norm(self, k): P=self.A*self.T_k(k)**2*k**self.n_s*k**3/(2*math.pi**2) return P def Delta_sq_L_norm_z(self, k,z): P=self.A*self.T_k(k)**2*k**self.n_s*k**3/(2*math.pi**2)*self.D_plus(1/(1+z)) return P def sigma_M(self, M): def func(k,R): return k**2*self.P_L_norm(k)*f_k(k,R) R=(M/self.ro_0*3/4/math.pi)**(1/3.) integrand=scipy.integrate.quad(func, 0, scipy.Inf, args=(R), limit=50000)[0] return R def Jenkins(self, M): return 0.315*self.ro_0/M**2*self.dlnsigma_dlnM*math.exp(-math.sqrt((0.61-math.log(self.sigma_M(M)))**2)**3.8) def f96(self, x, n_eff): A_c=0.482*(1.+n_eff/3.)**(-0.947) B_c=0.226*(1.+n_eff/3.)**(-1.778) alpha_c=3.310*(1.+n_eff/3.)**(-0.244) beta_c=0.862*(1.+n_eff/3.)**(-0.287) V_c=11.55*(1.+n_eff/3.)**(-0.423) g=5./2.*self.omega_m*(self.omega_m**(4./7.)-self.omega_l+(1+self.omega_m/2)*(1+self.omega_l/70))**(-1) return x*((1+B_c*beta_c*x+(A_c*x)**(alpha_c*beta_c))/(1+((A_c*x)**alpha_c*g**3/(V_c*x**0.5))**beta_c))**(1/beta_c) def Delta_sq_NL_PD96_norm(self, k_L): n_eff=self.d_ln_P_L_norm(k_L/2.) return self.f96(self.Delta_sq_L_norm(k_L), n_eff) def Delta_sq_NL_PD96_norm_z(self, k_L,z): n_eff=self.d_ln_P_L_norm_z(k_L/2.,z) return self.f96(self.Delta_sq_L_norm_z(k_L,z), n_eff) def P_NL_PD96_norm(self, k): return self.Delta_sq_NL_PD96_norm(k)*((k/self.k_L_over_k_NL_PD96(self.Delta_sq_NL_PD96_norm(k)))**3/(2*math.pi**2))**(-1) def P_NL_PD96_norm_z(self, k, z): return self.Delta_sq_NL_PD96_norm_z(k,z)*((k/self.k_L_over_k_NL_PD96(self.Delta_sq_NL_PD96_norm_z(k,z)))**3/(2*math.pi**2))**(-1) def k_L_over_k_NL_PD96(self, Delta): return (1+Delta)**(-1./3.)
true
true
1c37285a602b682b314ecd6fd1b1d5a9221fd720
2,215
py
Python
coeusfactory/ConnectorFactory.py
mamerisawesome/coeusfactory
73530e118a9354b8b91f8d4a59f7f025008f366d
[ "MIT" ]
1
2020-02-19T03:03:32.000Z
2020-02-19T03:03:32.000Z
coeusfactory/ConnectorFactory.py
mamerisawesome/coeusfactory
73530e118a9354b8b91f8d4a59f7f025008f366d
[ "MIT" ]
null
null
null
coeusfactory/ConnectorFactory.py
mamerisawesome/coeusfactory
73530e118a9354b8b91f8d4a59f7f025008f366d
[ "MIT" ]
null
null
null
import logging logger = logging.getLogger(__name__) class ConnectorFactory(): def __init__(self, interface=None, raw_name=False, **kwargs): if not interface: logger.warning("No database interface selected") self.handler = None return None from pubsub import pub self.event = pub self.interface = interface self.raw_name = raw_name self.handler = self._set_connector(**kwargs) self._set_events(['initialized', 'connected', 'disconnected']) def initialized(self): logger.info("Database initialized") def connected(self): logger.info("Database connected") def disconnected(self): self.handler = None logger.info("Database disconnected") def get_model(self, model): interface = self.interface if not model or not model[0].isalpha(): return None if self.raw_name: self.handler.model = model else: model_name = model[0].upper() if len(model) > 1: model_name = model_name + model[1:].lower() self.handler.model = model_name module_prefix = interface[0].upper() + interface.lower()[1:] connectors = __import__("coeusfactory.repositories") connectors = getattr(connectors, "repositories") module = getattr(connectors, "{}Repository".format(module_prefix)) return module(model=self.handler.model, database=self.handler.db) def _set_events(self, events_array): for event in events_array: self.event.subscribe(getattr(self, event), event) def _set_connector(self, **kwargs): interface = self.interface try: module_prefix = interface[0].upper() + interface.lower()[1:] connectors = __import__("coeusfactory.connectors") connectors = getattr(connectors, "connectors") module = getattr(connectors, "{}Connector".format(module_prefix)) return module(event=self.event, **kwargs) except (ImportError, AttributeError): logger.error("{}Connector not available".format(module_prefix)) return None
35.15873
77
0.623025
import logging logger = logging.getLogger(__name__) class ConnectorFactory(): def __init__(self, interface=None, raw_name=False, **kwargs): if not interface: logger.warning("No database interface selected") self.handler = None return None from pubsub import pub self.event = pub self.interface = interface self.raw_name = raw_name self.handler = self._set_connector(**kwargs) self._set_events(['initialized', 'connected', 'disconnected']) def initialized(self): logger.info("Database initialized") def connected(self): logger.info("Database connected") def disconnected(self): self.handler = None logger.info("Database disconnected") def get_model(self, model): interface = self.interface if not model or not model[0].isalpha(): return None if self.raw_name: self.handler.model = model else: model_name = model[0].upper() if len(model) > 1: model_name = model_name + model[1:].lower() self.handler.model = model_name module_prefix = interface[0].upper() + interface.lower()[1:] connectors = __import__("coeusfactory.repositories") connectors = getattr(connectors, "repositories") module = getattr(connectors, "{}Repository".format(module_prefix)) return module(model=self.handler.model, database=self.handler.db) def _set_events(self, events_array): for event in events_array: self.event.subscribe(getattr(self, event), event) def _set_connector(self, **kwargs): interface = self.interface try: module_prefix = interface[0].upper() + interface.lower()[1:] connectors = __import__("coeusfactory.connectors") connectors = getattr(connectors, "connectors") module = getattr(connectors, "{}Connector".format(module_prefix)) return module(event=self.event, **kwargs) except (ImportError, AttributeError): logger.error("{}Connector not available".format(module_prefix)) return None
true
true
1c3728df0c54b1c7cd720de32f058a8438ed26a4
4,103
py
Python
pinax/apps/signup_codes/views.py
peiwei/pinax
34f95b1df4318655fe9bd90dcda8fe824e0c4117
[ "MIT" ]
1
2019-02-12T04:45:09.000Z
2019-02-12T04:45:09.000Z
pinax/apps/signup_codes/views.py
peiwei/pinax
34f95b1df4318655fe9bd90dcda8fe824e0c4117
[ "MIT" ]
null
null
null
pinax/apps/signup_codes/views.py
peiwei/pinax
34f95b1df4318655fe9bd90dcda8fe824e0c4117
[ "MIT" ]
1
2019-02-12T04:45:40.000Z
2019-02-12T04:45:40.000Z
from django.conf import settings from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.translation import ugettext from django.contrib import messages from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth import authenticate from django.contrib.auth import login as auth_login from account.utils import get_default_redirect, user_display from signup_codes.models import check_signup_code from signup_codes.forms import SignupForm, InviteUserForm def group_and_bridge(kwargs): """ Given kwargs from the view (with view specific keys popped) pull out the bridge and fetch group from database. """ bridge = kwargs.pop("bridge", None) if bridge: try: group = bridge.get_group(**kwargs) except ObjectDoesNotExist: raise Http404 else: group = None return group, bridge def group_context(group, bridge): # @@@ use bridge return { "group": group, } def signup(request, **kwargs): form_class = kwargs.pop("form_class", SignupForm) template_name = kwargs.pop("template_name", "account/signup.html") template_name_failure = kwargs.pop("template_name_failure", "signup_codes/failure.html") success_url = kwargs.pop("success_url", None) group, bridge = group_and_bridge(kwargs) ctx = group_context(group, bridge) if success_url is None: success_url = get_default_redirect(request) code = request.GET.get("code") if request.method == "POST": form = form_class(request.POST, group=group) if form.is_valid(): username, password = form.save() user = authenticate(username=username, password=password) signup_code = form.cleaned_data["signup_code"] signup_code.use(user) auth_login(request, user) messages.add_message(request, messages.SUCCESS, ugettext("Successfully logged in as %(username)s.") % { "username": user_display(user), } ) return HttpResponseRedirect(success_url) else: signup_code = check_signup_code(code) if signup_code: form = form_class(initial={"signup_code": code}, group=group) else: if not settings.ACCOUNT_OPEN_SIGNUP: ctx.update({ "code": code, }) ctx = RequestContext(request, ctx) # if account signup is not open we want to fail when there is # no sign up code or what was provided failed. return render_to_response(template_name_failure, ctx) else: form = form_class(group=group) ctx.update({ "code": code, "form": form, }) return render_to_response(template_name, RequestContext(request, ctx)) @staff_member_required def admin_invite_user(request, **kwargs): """ This view, by default, works inside the Django admin. """ form_class = kwargs.pop("form_class", InviteUserForm) template_name = kwargs.pop("template_name", "signup_codes/admin_invite_user.html") group, bridge = group_and_bridge(kwargs) if request.method == "POST": form = form_class(request.POST, group=group) if form.is_valid(): email = form.cleaned_data["email"] form.send_signup_code() messages.add_message(request, messages.INFO, ugettext("An e-mail has been sent to %(email)s.") % { "email": email } ) form = form_class() # reset else: form = form_class(group=group) ctx = group_context(group, bridge) ctx.update({ "title": ugettext("Invite user"), "form": form, }) return render_to_response(template_name, RequestContext(request, ctx))
31.320611
92
0.62369
from django.conf import settings from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.translation import ugettext from django.contrib import messages from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth import authenticate from django.contrib.auth import login as auth_login from account.utils import get_default_redirect, user_display from signup_codes.models import check_signup_code from signup_codes.forms import SignupForm, InviteUserForm def group_and_bridge(kwargs): bridge = kwargs.pop("bridge", None) if bridge: try: group = bridge.get_group(**kwargs) except ObjectDoesNotExist: raise Http404 else: group = None return group, bridge def group_context(group, bridge): return { "group": group, } def signup(request, **kwargs): form_class = kwargs.pop("form_class", SignupForm) template_name = kwargs.pop("template_name", "account/signup.html") template_name_failure = kwargs.pop("template_name_failure", "signup_codes/failure.html") success_url = kwargs.pop("success_url", None) group, bridge = group_and_bridge(kwargs) ctx = group_context(group, bridge) if success_url is None: success_url = get_default_redirect(request) code = request.GET.get("code") if request.method == "POST": form = form_class(request.POST, group=group) if form.is_valid(): username, password = form.save() user = authenticate(username=username, password=password) signup_code = form.cleaned_data["signup_code"] signup_code.use(user) auth_login(request, user) messages.add_message(request, messages.SUCCESS, ugettext("Successfully logged in as %(username)s.") % { "username": user_display(user), } ) return HttpResponseRedirect(success_url) else: signup_code = check_signup_code(code) if signup_code: form = form_class(initial={"signup_code": code}, group=group) else: if not settings.ACCOUNT_OPEN_SIGNUP: ctx.update({ "code": code, }) ctx = RequestContext(request, ctx) return render_to_response(template_name_failure, ctx) else: form = form_class(group=group) ctx.update({ "code": code, "form": form, }) return render_to_response(template_name, RequestContext(request, ctx)) @staff_member_required def admin_invite_user(request, **kwargs): form_class = kwargs.pop("form_class", InviteUserForm) template_name = kwargs.pop("template_name", "signup_codes/admin_invite_user.html") group, bridge = group_and_bridge(kwargs) if request.method == "POST": form = form_class(request.POST, group=group) if form.is_valid(): email = form.cleaned_data["email"] form.send_signup_code() messages.add_message(request, messages.INFO, ugettext("An e-mail has been sent to %(email)s.") % { "email": email } ) form = form_class() else: form = form_class(group=group) ctx = group_context(group, bridge) ctx.update({ "title": ugettext("Invite user"), "form": form, }) return render_to_response(template_name, RequestContext(request, ctx))
true
true
1c3729e83c584d1e74615514deac2b24c5a0a105
627
py
Python
python-lib/dku_model_accessor/constants.py
dataiku/dss-plugin-model-fairness-report
a1405aa5790083a90565c897e91c156ad1f23ab9
[ "Apache-2.0" ]
1
2021-02-26T20:03:27.000Z
2021-02-26T20:03:27.000Z
python-lib/dku_model_accessor/constants.py
dataiku/dss-plugin-model-fairness-report
a1405aa5790083a90565c897e91c156ad1f23ab9
[ "Apache-2.0" ]
2
2020-11-12T09:26:56.000Z
2021-05-20T08:32:04.000Z
python-lib/dku_model_accessor/constants.py
dataiku/dss-plugin-model-fairness-report
a1405aa5790083a90565c897e91c156ad1f23ab9
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- class DkuModelAccessorConstants(object): MODEL_ID = 'model_id' VERSION_ID = 'version_id' REGRRSSION_TYPE = 'REGRESSION' CLASSIFICATION_TYPE = 'CLASSIFICATION' CLUSTERING_TYPE = 'CLUSTERING' ORIGINAL_DATASET = 'original_dataset' NEW_DATASET = 'new_dataset' MIN_NUM_ROWS = 500 MAX_NUM_ROW = 100000 CUMULATIVE_PERCENTAGE_THRESHOLD = 90 FEAT_IMP_CUMULATIVE_PERCENTAGE_THRESHOLD = 95 CUMULATIVE_IMPORTANCE = 'cumulative_importance' FEATURE = 'feature' IMPORTANCE = 'importance' RANK = 'rank' CLASS = 'class' PERCENTAGE = 'percentage'
24.115385
51
0.701754
class DkuModelAccessorConstants(object): MODEL_ID = 'model_id' VERSION_ID = 'version_id' REGRRSSION_TYPE = 'REGRESSION' CLASSIFICATION_TYPE = 'CLASSIFICATION' CLUSTERING_TYPE = 'CLUSTERING' ORIGINAL_DATASET = 'original_dataset' NEW_DATASET = 'new_dataset' MIN_NUM_ROWS = 500 MAX_NUM_ROW = 100000 CUMULATIVE_PERCENTAGE_THRESHOLD = 90 FEAT_IMP_CUMULATIVE_PERCENTAGE_THRESHOLD = 95 CUMULATIVE_IMPORTANCE = 'cumulative_importance' FEATURE = 'feature' IMPORTANCE = 'importance' RANK = 'rank' CLASS = 'class' PERCENTAGE = 'percentage'
true
true
1c372a0d5049c595b66a0fb7771aacf845d485f5
8,994
py
Python
quadruplet_utils.py
ikathuria/SignatureVerification
4d0f26eb2652ecdf8cd5a679c6d3468046ab0d88
[ "MIT" ]
4
2021-07-07T21:59:01.000Z
2022-01-24T09:37:40.000Z
quadruplet_utils.py
ikathuria/SignatureVerification
4d0f26eb2652ecdf8cd5a679c6d3468046ab0d88
[ "MIT" ]
null
null
null
quadruplet_utils.py
ikathuria/SignatureVerification
4d0f26eb2652ecdf8cd5a679c6d3468046ab0d88
[ "MIT" ]
null
null
null
"""Quadruplet loss utility functions. embedding_net build_metric_network QuadrupletLossLayer build_quadruplet_model compute_l2_dist compute_probs compute_metrics find_nearest draw_roc draw_eval_quadruplets """ import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import math import numpy as np from tqdm import tqdm import keras.backend as K from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Input, concatenate, Layer from tensorflow.keras.layers import Conv2D, MaxPooling2D, Lambda, Flatten, Dense, Concatenate from tensorflow.keras.initializers import glorot_uniform from tensorflow.keras.regularizers import l2 from sklearn.metrics import roc_curve, roc_auc_score import matplotlib.pyplot as plt # Model ################################################################################## def embedding_net(embeddingsize, input_shape=(224, 224, 1)): """Embedding network. Args: embeddingsize -- int : embedding size. input_shape -- tuple : input shape of (224, 224, 1). Returns: embedding -- keras.models.Sequential : embedding sequential network. """ # Convolutional Neural Network network = Sequential(name="sequential_network") # 1 Conv2D network.add(Conv2D(128, (7, 7), activation='relu', padding='same', input_shape=input_shape, kernel_initializer='he_uniform', kernel_regularizer=l2(2e-4))) network.add(MaxPooling2D()) # 2 Conv2D network.add(Conv2D(128, (5, 5), activation='relu', padding='same', kernel_initializer='he_uniform', kernel_regularizer=l2(2e-4))) network.add(MaxPooling2D()) # 3 Conv2D network.add(Conv2D(64, (5, 5), activation='relu', padding='same', kernel_initializer='he_uniform', kernel_regularizer=l2(2e-4))) # flatten the output to 1D network.add(Flatten()) # 1 Dense network.add(Dense(2048, activation='relu', kernel_regularizer=l2(1e-3), kernel_initializer='he_uniform')) # 2 Dense network.add(Dense(embeddingsize, activation=None, kernel_regularizer=l2(1e-3), kernel_initializer='he_uniform')) # Force the encoding to live on the d-dimentional hypershpere network.add(Lambda(lambda x: K.l2_normalize(x, axis=-1))) return network def build_metric_network(single_embedding_shape): ''' Define the neural network to learn the metric Input : single_embedding_shape : shape of input embeddings or feature map. Must be an array ''' # compute shape for input input_shape = single_embedding_shape # the two input embeddings will be concatenated input_shape[0] = input_shape[0]*2 # Neural Network network = Sequential(name="learned_metric") network.add(Dense(10, activation='relu', input_shape=input_shape, kernel_regularizer=l2(1e-3), kernel_initializer='he_uniform')) network.add(Dense(10, activation='relu', kernel_regularizer=l2(1e-3), kernel_initializer='he_uniform')) network.add(Dense(10, activation='relu', kernel_regularizer=l2(1e-3), kernel_initializer='he_uniform')) # Last layer : binary softmax network.add(Dense(2, activation='softmax')) # Select only one output value from the softmax network.add(Lambda(lambda x: x[:, 0])) return network class QuadrupletLossLayer(Layer): def __init__(self, alpha=1, beta=0.5, **kwargs): self.alpha = alpha self.beta = beta self.debugeric = 1 super(QuadrupletLossLayer, self).__init__(**kwargs) def quadruplet_loss(self, inputs): ap_dist, an_dist, nn_dist = inputs # square ap_dist2 = K.square(ap_dist) an_dist2 = K.square(an_dist) nn_dist2 = K.square(nn_dist) return K.sum(K.maximum(ap_dist2 - an_dist2 + self.alpha, 0), axis=0) + K.sum(K.maximum(ap_dist2 - nn_dist2 + self.beta, 0), axis=0) def call(self, inputs): loss = self.quadruplet_loss(inputs) self.add_loss(loss) return loss def build_quadruplet_model(input_shape, network, metricnetwork, margin=1, margin2=0.5): ''' Define the Keras Model for training Input : input_shape : shape of input images network : Neural network to train outputing embeddings metricnetwork : Neural network to train the learned metric margin : minimal distance between Anchor-Positive and Anchor-Negative for the lossfunction (alpha1) margin2 : minimal distance between Anchor-Positive and Negative-Negative2 for the lossfunction (alpha2) ''' # Define the tensors for the four input images anchor_input = Input(input_shape, name="anchor_input") positive_input = Input(input_shape, name="positive_input") negative_input = Input(input_shape, name="negative_input") negative2_input = Input(input_shape, name="negative2_input") # Generate the encodings (feature vectors) for the four images encoded_a = network(anchor_input) encoded_p = network(positive_input) encoded_n = network(negative_input) encoded_n2 = network(negative2_input) # compute the concatenated pairs encoded_ap = Concatenate( axis=-1, name="Anchor-Positive")([encoded_a, encoded_p]) encoded_an = Concatenate( axis=-1, name="Anchor-Negative")([encoded_a, encoded_n]) encoded_nn = Concatenate( axis=-1, name="Negative-Negative2")([encoded_n, encoded_n2]) # compute the distances AP, AN, NN ap_dist = metricnetwork(encoded_ap) an_dist = metricnetwork(encoded_an) nn_dist = metricnetwork(encoded_nn) # QuadrupletLoss Layer loss_layer = QuadrupletLossLayer(alpha=margin, beta=margin2, name='4xLoss')([ ap_dist, an_dist, nn_dist]) # Connect the inputs with the outputs network_train = Model( inputs=[anchor_input, positive_input, negative_input, negative2_input], outputs=loss_layer) # return the model return network_train # EVALUATION ################################################################################## def compute_l2_dist(a, b): return np.sum(np.square(a-b)) def compute_probs(network, X): ''' Input network : current NN to compute embeddings. X : tensor of shape (m, w, h, 1) containing pics to evaluate. Y : tensor of shape (m,) containing true class. Returns probs : array of shape (m, m) containing distances. ''' left = X[0] right = X[1] m = left.shape[0] probs = np.zeros((m)) for i in tqdm(range(m), desc='QUADRUPLETS PROBS'): emb_left = network.predict(left[m].reshape(1, 224, 224, 1)) emb_right = network.predict(right[m].reshape(1, 224, 224, 1)) probs[i] = -compute_l2_dist(emb_left, emb_right) return probs def compute_metrics(yprobs, probs): ''' Returns fpr : Increasing false positive rates such that element i is the false positive rate of predictions with score >= thresholds[i] tpr : Increasing true positive rates such that element i is the true positive rate of predictions with score >= thresholds[i]. thresholds : Decreasing thresholds on the decision function used to compute fpr and tpr. thresholds[0] represents no instances being predicted and is arbitrarily set to max(y_score) + 1 auc : Area Under the ROC Curve metric ''' # calculate AUC auc = roc_auc_score(yprobs, probs) # calculate roc curve fpr, tpr, thresholds = roc_curve(yprobs, probs) return fpr, tpr, thresholds, auc def find_nearest(array, value): idx = np.searchsorted(array, value, side="left") if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])): return array[idx-1], idx-1 else: return array[idx], idx def draw_roc(fpr, tpr, thresholds, auc, n_iteration): # find threshold targetfpr = 1e-3 _, idx = find_nearest(fpr, targetfpr) threshold = thresholds[idx] recall = tpr[idx] # plot no skill plt.plot([0, 1], [0, 1], linestyle='--') # plot the roc curve for the model plt.plot(fpr, tpr, marker='.') plt.title('AUC: {0:.3f} @ {4} iterations\nSensitivity : {2:.1%} @FPR={1:.0e}\nThreshold={3})'.format( auc, targetfpr, recall, abs(threshold), n_iteration )) # show the plot plt.show() def draw_eval_quadruplets(network, n_iteration, X, Y): yprobs = Y probs = compute_probs(network, X) fpr, tpr, thresholds, auc = compute_metrics(yprobs, probs) draw_roc(fpr, tpr, thresholds, auc, n_iteration)
32.824818
193
0.642095
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import math import numpy as np from tqdm import tqdm import keras.backend as K from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Input, concatenate, Layer from tensorflow.keras.layers import Conv2D, MaxPooling2D, Lambda, Flatten, Dense, Concatenate from tensorflow.keras.initializers import glorot_uniform from tensorflow.keras.regularizers import l2 from sklearn.metrics import roc_curve, roc_auc_score import matplotlib.pyplot as plt tive")([encoded_a, encoded_p]) encoded_an = Concatenate( axis=-1, name="Anchor-Negative")([encoded_a, encoded_n]) encoded_nn = Concatenate( axis=-1, name="Negative-Negative2")([encoded_n, encoded_n2]) ap_dist = metricnetwork(encoded_ap) an_dist = metricnetwork(encoded_an) nn_dist = metricnetwork(encoded_nn) loss_layer = QuadrupletLossLayer(alpha=margin, beta=margin2, name='4xLoss')([ ap_dist, an_dist, nn_dist]) network_train = Model( inputs=[anchor_input, positive_input, negative_input, negative2_input], outputs=loss_layer) return network_train
true
true
1c372a84d0c0a66c44b636fe394d8e5f211640fb
8,612
py
Python
test.py
sile16/purerackdiagram
e97b64dc7cd4e0309c01f252225b5639977df00f
[ "MIT" ]
2
2019-01-17T15:59:42.000Z
2020-02-25T03:45:51.000Z
test.py
sile16/purerackdiagram
e97b64dc7cd4e0309c01f252225b5639977df00f
[ "MIT" ]
null
null
null
test.py
sile16/purerackdiagram
e97b64dc7cd4e0309c01f252225b5639977df00f
[ "MIT" ]
3
2019-01-17T15:59:46.000Z
2020-10-29T18:11:21.000Z
from pprint import pprint import logging import base64 from multiprocessing import Pool import hashlib import io import os import lambdaentry from purerackdiagram.utils import global_config import purerackdiagram import json import traceback logger = logging.getLogger() ch = logging.StreamHandler() ch.setLevel(logging.INFO) logger.addHandler(ch) save_dir = 'test_results/' # 38/38-31/63-127/0 # 0/38-0/45-0/45-0/63 more_tests = [ { "queryStringParameters": { "model": "fa-xl130", "datapacks": "91/91/91", "chassis": 2, "addoncards": "", "face": "front", "fm_label": True, "dp_label": True, "mezz": "smezz", "local_delay": 0, "ports": True } }, { "queryStringParameters": { "model": "fa-xl130", "datapacks": "63/0", "chassis": 2, "addoncards": "", "face": "back", "fm_label": True, "dp_label": True, "mezz": "smezz", "local_delay": 0, "ports": True } }, { "queryStringParameters": { "model": "fb", "chassis": 2, "face": "back", 'direction': 'up', 'efm': "efm310", 'local_delay': 0, 'blades': '17:0-6,52:23-29', 'ports': True } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "91/91-45/45", "addoncards": "", "face": "back", "fm_label": "FALSE", "dp_label": "FALSE", "bezel": "FALSE", "local_delay": 3 } }, { "queryStringParameters": { "model": "fa-c60", "protocol": "eth", "direction": "up", "datapacks": "91/91-45/45", "csize": '879', "addoncards": "", "face": "back", "fm_label": "True", "dp_label": "Ture", "bezel": "FALSE" } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "292-45/45", "addoncards": "", "face": "front", "fm_label": "True", "dp_label": "FALSE" } }, { "queryStringParameters": { "model": "fb", "chassis": 10, "face": "back", 'direction': 'up', 'efm': "efm310", 'blades': '17:0-6,52:23-29' } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "0/127", "addoncards": "", "face": "front", "fm_label": "True", "dp_label": "FALSE" } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "127/0", "addoncards": "", "face": "front", "fm_label": "True", "dp_label": "FALSE" } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "3/127", "addoncards": "", "face": "front", "fm_label": "True", "dp_label": "True" } } ] def test_lambda(): # Single test functions results = lambdaentry.handler(more_tests[0], None) if results['headers'].get("Content-Type") == 'image/png': if 'body' in results: img_str = base64.b64decode(results['body'].encode('utf-8')) with open('tmp.png', 'wb') as outfile: outfile.write(img_str) del results['body'] elif results['headers'].get("Content-Type") == 'application/vnd.ms-visio.stencil': if 'body' in results: img_str = base64.b64decode(results['body'].encode('utf-8')) with open('stencil.vssx', 'wb') as outfile: outfile.write(img_str) del results['body'] pprint(results) def create_test_image(item, count, total): file_name = "" for n in ['model', 'addoncards', 'face', 'dp_label', 'fm_label', 'datapacks']: if n in item: if n == 'datapacks': file_name += str(item[n]).replace('/', '-') + "_" else: file_name += str(item[n]) + "_" file_name += '.png' try: img = purerackdiagram.get_image_sync(item) except Exception as e: print(f"Caught exeption in image: {file_name} ") traceback.print_exc() print() raise e h = hashlib.sha256() with io.BytesIO() as memf: img.save(memf, 'PNG') data = memf.getvalue() h.update(data) img.save(os.path.join(save_dir, file_name)) # result_q.put({file_name: h.hexdigest()}) print(f"{count} of {total} {file_name}") return({file_name: h.hexdigest()}) def get_all_tests(): models = global_config['pci_config_lookup'] dps = ['45/45-31/63-45', '3/127-24'] csizes = ['366', '879', '1390'] count = 0 # front: for model in models: model = model[:8] for dp_label in [True, False]: if 'c' in model: for csize in csizes: count += 1 params = {"model": model, "fm_label": True, "dp_label": dp_label, "csize": csize} yield params else: for dp in dps: # if count > 3: # break count += 1 params = {"model": model, "fm_label": True, "dp_label": dp_label, "datapacks": dp} yield params # back: addon_cards = global_config['pci_valid_cards'] for model in models: model = model[:8] for card in addon_cards: if 'c' in model: for csize in csizes: params = {"model": model, "addoncards": card, "face": "back", "csize": csize} yield params else: for dp in dps: params = {"model": model, "datapacks": dp, "addoncards": card, "face": "back"} yield params for test in more_tests: yield test['queryStringParameters'] def test_all(args): if not os.path.exists(save_dir): os.makedirs(save_dir) # Create amultiprocessing pool pool = Pool(processes=args.t) futures = [] total_count = 0 all_items = list(get_all_tests()) count = 0 for item in all_items: futures.append(pool.apply_async(create_test_image, args=(item, count, len(all_items), ))) count += 1 pool.close() pool.join() results = {} for f in futures: result = f.get() results.update(result) with open("test_results.json", "w") as f: json.dump(results, f) with open("test_validation.json") as f: validation = json.load(f) errors = 0 warnings = 0 for key in results: if key not in validation: warnings += 1 print("WARNING missing key:{}".format(key)) elif results[key] != validation[key]: errors += 1 print("Error Image Changed!!:{}".format(key)) print("Test Complete {} Errors Found {} Warning".format(errors, warnings)) def main(args): if args.testtype == 'all': test_all(args) else: test_lambda() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('testtype', choices=['all', 'lambda'], default='all', nargs='?', help="Test all options, or test through lamdba entry") parser.add_argument('-t', type=int, help="number of threads", default=8) main(parser.parse_args())
26.176292
97
0.458895
from pprint import pprint import logging import base64 from multiprocessing import Pool import hashlib import io import os import lambdaentry from purerackdiagram.utils import global_config import purerackdiagram import json import traceback logger = logging.getLogger() ch = logging.StreamHandler() ch.setLevel(logging.INFO) logger.addHandler(ch) save_dir = 'test_results/' more_tests = [ { "queryStringParameters": { "model": "fa-xl130", "datapacks": "91/91/91", "chassis": 2, "addoncards": "", "face": "front", "fm_label": True, "dp_label": True, "mezz": "smezz", "local_delay": 0, "ports": True } }, { "queryStringParameters": { "model": "fa-xl130", "datapacks": "63/0", "chassis": 2, "addoncards": "", "face": "back", "fm_label": True, "dp_label": True, "mezz": "smezz", "local_delay": 0, "ports": True } }, { "queryStringParameters": { "model": "fb", "chassis": 2, "face": "back", 'direction': 'up', 'efm': "efm310", 'local_delay': 0, 'blades': '17:0-6,52:23-29', 'ports': True } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "91/91-45/45", "addoncards": "", "face": "back", "fm_label": "FALSE", "dp_label": "FALSE", "bezel": "FALSE", "local_delay": 3 } }, { "queryStringParameters": { "model": "fa-c60", "protocol": "eth", "direction": "up", "datapacks": "91/91-45/45", "csize": '879', "addoncards": "", "face": "back", "fm_label": "True", "dp_label": "Ture", "bezel": "FALSE" } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "292-45/45", "addoncards": "", "face": "front", "fm_label": "True", "dp_label": "FALSE" } }, { "queryStringParameters": { "model": "fb", "chassis": 10, "face": "back", 'direction': 'up', 'efm': "efm310", 'blades': '17:0-6,52:23-29' } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "0/127", "addoncards": "", "face": "front", "fm_label": "True", "dp_label": "FALSE" } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "127/0", "addoncards": "", "face": "front", "fm_label": "True", "dp_label": "FALSE" } }, { "queryStringParameters": { "model": "fa-x70r1", "protocol": "fc", "direction": "up", "datapacks": "3/127", "addoncards": "", "face": "front", "fm_label": "True", "dp_label": "True" } } ] def test_lambda(): results = lambdaentry.handler(more_tests[0], None) if results['headers'].get("Content-Type") == 'image/png': if 'body' in results: img_str = base64.b64decode(results['body'].encode('utf-8')) with open('tmp.png', 'wb') as outfile: outfile.write(img_str) del results['body'] elif results['headers'].get("Content-Type") == 'application/vnd.ms-visio.stencil': if 'body' in results: img_str = base64.b64decode(results['body'].encode('utf-8')) with open('stencil.vssx', 'wb') as outfile: outfile.write(img_str) del results['body'] pprint(results) def create_test_image(item, count, total): file_name = "" for n in ['model', 'addoncards', 'face', 'dp_label', 'fm_label', 'datapacks']: if n in item: if n == 'datapacks': file_name += str(item[n]).replace('/', '-') + "_" else: file_name += str(item[n]) + "_" file_name += '.png' try: img = purerackdiagram.get_image_sync(item) except Exception as e: print(f"Caught exeption in image: {file_name} ") traceback.print_exc() print() raise e h = hashlib.sha256() with io.BytesIO() as memf: img.save(memf, 'PNG') data = memf.getvalue() h.update(data) img.save(os.path.join(save_dir, file_name)) print(f"{count} of {total} {file_name}") return({file_name: h.hexdigest()}) def get_all_tests(): models = global_config['pci_config_lookup'] dps = ['45/45-31/63-45', '3/127-24'] csizes = ['366', '879', '1390'] count = 0 for model in models: model = model[:8] for dp_label in [True, False]: if 'c' in model: for csize in csizes: count += 1 params = {"model": model, "fm_label": True, "dp_label": dp_label, "csize": csize} yield params else: for dp in dps: count += 1 params = {"model": model, "fm_label": True, "dp_label": dp_label, "datapacks": dp} yield params addon_cards = global_config['pci_valid_cards'] for model in models: model = model[:8] for card in addon_cards: if 'c' in model: for csize in csizes: params = {"model": model, "addoncards": card, "face": "back", "csize": csize} yield params else: for dp in dps: params = {"model": model, "datapacks": dp, "addoncards": card, "face": "back"} yield params for test in more_tests: yield test['queryStringParameters'] def test_all(args): if not os.path.exists(save_dir): os.makedirs(save_dir) pool = Pool(processes=args.t) futures = [] total_count = 0 all_items = list(get_all_tests()) count = 0 for item in all_items: futures.append(pool.apply_async(create_test_image, args=(item, count, len(all_items), ))) count += 1 pool.close() pool.join() results = {} for f in futures: result = f.get() results.update(result) with open("test_results.json", "w") as f: json.dump(results, f) with open("test_validation.json") as f: validation = json.load(f) errors = 0 warnings = 0 for key in results: if key not in validation: warnings += 1 print("WARNING missing key:{}".format(key)) elif results[key] != validation[key]: errors += 1 print("Error Image Changed!!:{}".format(key)) print("Test Complete {} Errors Found {} Warning".format(errors, warnings)) def main(args): if args.testtype == 'all': test_all(args) else: test_lambda() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('testtype', choices=['all', 'lambda'], default='all', nargs='?', help="Test all options, or test through lamdba entry") parser.add_argument('-t', type=int, help="number of threads", default=8) main(parser.parse_args())
true
true
1c372b939922eff63ff1df763d408ff650b3920b
2,063
py
Python
app/cache/lock.py
TouchPal/guldan
74cc0bf687109d16c3eb94010b4cc25bd5c5bcc0
[ "BSD-3-Clause" ]
43
2017-12-27T13:20:15.000Z
2021-04-15T03:02:03.000Z
app/cache/lock.py
TouchPal/guldan
74cc0bf687109d16c3eb94010b4cc25bd5c5bcc0
[ "BSD-3-Clause" ]
null
null
null
app/cache/lock.py
TouchPal/guldan
74cc0bf687109d16c3eb94010b4cc25bd5c5bcc0
[ "BSD-3-Clause" ]
4
2018-03-28T08:46:07.000Z
2018-10-12T09:33:38.000Z
# -*- coding: utf-8 -*- import logging import time logger = logging.getLogger(__name__) NOT_REGENERATED = object() class Lock(object): def __init__( self, mutex, creator, value_and_created_fn, expiretime, ): self.mutex = mutex self.creator = creator self.value_and_created_fn = value_and_created_fn self.expiretime = expiretime def _is_expired(self, createdtime): """Return true if the expiration time is reached, or no value is available.""" return not self._has_value(createdtime) or \ ( self.expiretime is not None and time.time() - createdtime > self.expiretime ) def _has_value(self, createdtime): """Return true if the creation function has proceeded at least once.""" return createdtime > 0 def _enter(self): value_fn = self.value_and_created_fn try: value = value_fn() value, createdtime = value except: value = NOT_REGENERATED createdtime = -1 generated = self._enter_create(createdtime) if generated is not NOT_REGENERATED: value, createdtime = generated return value elif value is NOT_REGENERATED: try: value, createdtime = value_fn() return value except: raise Exception("Generation function should " "have just been called by a concurrent " "thread.") return value def _enter_create(self, createdtime): if not self._is_expired(createdtime): return NOT_REGENERATED self.mutex.acquire() try: created, createdtime = self.creator() finally: self.mutex.release() return created, createdtime def __enter__(self): return self._enter() def __exit__(self, type, value, traceback): pass
25.469136
68
0.564712
import logging import time logger = logging.getLogger(__name__) NOT_REGENERATED = object() class Lock(object): def __init__( self, mutex, creator, value_and_created_fn, expiretime, ): self.mutex = mutex self.creator = creator self.value_and_created_fn = value_and_created_fn self.expiretime = expiretime def _is_expired(self, createdtime): return not self._has_value(createdtime) or \ ( self.expiretime is not None and time.time() - createdtime > self.expiretime ) def _has_value(self, createdtime): return createdtime > 0 def _enter(self): value_fn = self.value_and_created_fn try: value = value_fn() value, createdtime = value except: value = NOT_REGENERATED createdtime = -1 generated = self._enter_create(createdtime) if generated is not NOT_REGENERATED: value, createdtime = generated return value elif value is NOT_REGENERATED: try: value, createdtime = value_fn() return value except: raise Exception("Generation function should " "have just been called by a concurrent " "thread.") return value def _enter_create(self, createdtime): if not self._is_expired(createdtime): return NOT_REGENERATED self.mutex.acquire() try: created, createdtime = self.creator() finally: self.mutex.release() return created, createdtime def __enter__(self): return self._enter() def __exit__(self, type, value, traceback): pass
true
true
1c372c30b6cb770005e3148b8bb715b36a15c0f5
230
py
Python
pages/views.py
irahulgulati/Cryptoic
bd4a6e3d8dd9c383b350ca3496c4144c9a5f7200
[ "MIT" ]
1
2020-02-29T23:38:46.000Z
2020-02-29T23:38:46.000Z
pages/views.py
irahulgulati/Cryptoic
bd4a6e3d8dd9c383b350ca3496c4144c9a5f7200
[ "MIT" ]
1
2020-03-23T00:00:41.000Z
2020-03-23T00:00:41.000Z
pages/views.py
irahulgulati/Cryptoic
bd4a6e3d8dd9c383b350ca3496c4144c9a5f7200
[ "MIT" ]
null
null
null
from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home_view(request, *args, **kwargs): # return HttpResponse("<h1>Hello World</h1>") return render(request,"home.html", {})
23
46
0.73913
from django.http import HttpResponse from django.shortcuts import render def home_view(request, *args, **kwargs): return render(request,"home.html", {})
true
true
1c372c90ee71850a70ae21000a9def3d42186ef1
7,624
py
Python
flask_appbuilder/upload.py
zchencq/Flask-AppBuilder
06dc6f85493ff75db21fb5f19e0a40be1b1172b0
[ "BSD-3-Clause" ]
1
2020-10-31T19:11:44.000Z
2020-10-31T19:11:44.000Z
flask_appbuilder/upload.py
zchencq/Flask-AppBuilder
06dc6f85493ff75db21fb5f19e0a40be1b1172b0
[ "BSD-3-Clause" ]
null
null
null
flask_appbuilder/upload.py
zchencq/Flask-AppBuilder
06dc6f85493ff75db21fb5f19e0a40be1b1172b0
[ "BSD-3-Clause" ]
1
2020-04-14T19:32:31.000Z
2020-04-14T19:32:31.000Z
from flask_babel import gettext from werkzeug.datastructures import FileStorage from wtforms import fields, ValidationError from wtforms.widgets import html_params, HTMLString from .filemanager import FileManager, ImageManager try: from wtforms.fields.core import _unset_value as unset_value except ImportError: from wtforms.utils import unset_value """ Based and thanks to https://github.com/mrjoes/flask-admin/blob/master/flask_admin/form/upload.py """ class BS3FileUploadFieldWidget(object): empty_template = ( '<div class="input-group">' '<span class="input-group-addon"><i class="fa fa-upload"></i>' "</span>" '<input class="form-control" %(file)s/>' "</div>" ) data_template = ( "<div>" " <input %(text)s>" ' <input type="checkbox" name="%(marker)s">Delete</input>' "</div>" '<div class="input-group">' '<span class="input-group-addon"><i class="fa fa-upload"></i>' "</span>" '<input class="form-control" %(file)s/>' "</div>" ) def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) kwargs.setdefault("name", field.name) template = self.data_template if field.data else self.empty_template return HTMLString( template % { "text": html_params(type="text", value=field.data), "file": html_params(type="file", **kwargs), "marker": "_%s-delete" % field.name, } ) class BS3ImageUploadFieldWidget(object): empty_template = ( '<div class="input-group">' '<span class="input-group-addon"><span class="glyphicon glyphicon-upload"></span>' "</span>" '<input class="form-control" %(file)s/>' "</div>" ) data_template = ( '<div class="thumbnail">' " <img %(image)s>" ' <input type="checkbox" name="%(marker)s">Delete</input>' "</div>" '<div class="input-group">' '<span class="input-group-addon"><span class="glyphicon glyphicon-upload"></span>' "</span>" '<input class="form-control" %(file)s/>' "</div>" ) def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) kwargs.setdefault("name", field.name) args = { "file": html_params(type="file", **kwargs), "marker": "_%s-delete" % field.name, } if field.data: url = self.get_url(field) args["image"] = html_params(src=url) template = self.data_template else: template = self.empty_template return HTMLString(template % args) def get_url(self, field): im = ImageManager() return im.get_url(field.data) # Fields class FileUploadField(fields.TextField): """ Customizable file-upload field. Saves file to configured path, handles updates and deletions. Inherits from `TextField`, resulting filename will be stored as string. """ widget = BS3FileUploadFieldWidget() def __init__(self, label=None, validators=None, filemanager=None, **kwargs): """ Constructor. :param label: Display label :param validators: Validators """ self.filemanager = filemanager or FileManager() self._should_delete = False super(FileUploadField, self).__init__(label, validators, **kwargs) def process_on_delete(self, obj): """Override this method to make customised updates to the object when the stored file is going to be deleted.""" pass def process_on_store(self, obj, byte_stream): """Override this method to make customised updates to the object when a file is going to be stored. This may be used to parse file content and extract values for additional fields. Note: as populate_obj() on form fields my be called in an arbitrary order, do not assume that other fields in obj have been correctly set. If an extra information (from other fields) is necessary for parsing the supplied file content, a form-field validator may be used to copy it directly from the form to this field. :param obj: model object :param byte_stream: file contents """ pass def pre_validate(self, form): if ( self.data and isinstance(self.data, FileStorage) and not self.filemanager.is_file_allowed(self.data.filename) ): raise ValidationError(gettext("Invalid file extension")) def process(self, formdata, data=unset_value): if formdata: marker = "_%s-delete" % self.name if marker in formdata: self._should_delete = True return super(FileUploadField, self).process(formdata, data) def populate_obj(self, obj, name): field = getattr(obj, name, None) if field: # If field should be deleted, clean it up if self._should_delete: self.process_on_delete(obj) self.filemanager.delete_file(field) setattr(obj, name, None) return if self.data and isinstance(self.data, FileStorage): if field: self.process_on_delete(obj) self.filemanager.delete_file(field) position = self.data.stream.tell() self.process_on_store(obj, self.data.stream) self.data.stream.seek(position) filename = self.filemanager.generate_name(obj, self.data) filename = self.filemanager.save_file(self.data, filename) setattr(obj, name, filename) class ImageUploadField(fields.StringField): """ Image upload field. """ widget = BS3ImageUploadFieldWidget() def __init__(self, label=None, validators=None, imagemanager=None, **kwargs): self.imagemanager = imagemanager or ImageManager() self._should_delete = False super(ImageUploadField, self).__init__(label, validators, **kwargs) def pre_validate(self, form): if ( self.data and isinstance(self.data, FileStorage) and not self.imagemanager.is_file_allowed(self.data.filename) ): raise ValidationError(gettext("Invalid file extension")) def process(self, formdata, data=unset_value): if formdata: marker = "_%s-delete" % self.name if marker in formdata: self._should_delete = True return super(ImageUploadField, self).process(formdata, data) def populate_obj(self, obj, name): field = getattr(obj, name, None) size = obj.__mapper__.columns[name].type.size thumbnail_size = obj.__mapper__.columns[name].type.thumbnail_size if field: # If field should be deleted, clean it up if self._should_delete: self.imagemanager.delete_file(field) setattr(obj, name, None) return if self.data and isinstance(self.data, FileStorage): if field: self.imagemanager.delete_file(field) filename = self.imagemanager.generate_name(obj, self.data) filename = self.imagemanager.save_file( self.data, filename, size, thumbnail_size ) setattr(obj, name, filename)
31.504132
90
0.59575
from flask_babel import gettext from werkzeug.datastructures import FileStorage from wtforms import fields, ValidationError from wtforms.widgets import html_params, HTMLString from .filemanager import FileManager, ImageManager try: from wtforms.fields.core import _unset_value as unset_value except ImportError: from wtforms.utils import unset_value class BS3FileUploadFieldWidget(object): empty_template = ( '<div class="input-group">' '<span class="input-group-addon"><i class="fa fa-upload"></i>' "</span>" '<input class="form-control" %(file)s/>' "</div>" ) data_template = ( "<div>" " <input %(text)s>" ' <input type="checkbox" name="%(marker)s">Delete</input>' "</div>" '<div class="input-group">' '<span class="input-group-addon"><i class="fa fa-upload"></i>' "</span>" '<input class="form-control" %(file)s/>' "</div>" ) def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) kwargs.setdefault("name", field.name) template = self.data_template if field.data else self.empty_template return HTMLString( template % { "text": html_params(type="text", value=field.data), "file": html_params(type="file", **kwargs), "marker": "_%s-delete" % field.name, } ) class BS3ImageUploadFieldWidget(object): empty_template = ( '<div class="input-group">' '<span class="input-group-addon"><span class="glyphicon glyphicon-upload"></span>' "</span>" '<input class="form-control" %(file)s/>' "</div>" ) data_template = ( '<div class="thumbnail">' " <img %(image)s>" ' <input type="checkbox" name="%(marker)s">Delete</input>' "</div>" '<div class="input-group">' '<span class="input-group-addon"><span class="glyphicon glyphicon-upload"></span>' "</span>" '<input class="form-control" %(file)s/>' "</div>" ) def __call__(self, field, **kwargs): kwargs.setdefault("id", field.id) kwargs.setdefault("name", field.name) args = { "file": html_params(type="file", **kwargs), "marker": "_%s-delete" % field.name, } if field.data: url = self.get_url(field) args["image"] = html_params(src=url) template = self.data_template else: template = self.empty_template return HTMLString(template % args) def get_url(self, field): im = ImageManager() return im.get_url(field.data) class FileUploadField(fields.TextField): widget = BS3FileUploadFieldWidget() def __init__(self, label=None, validators=None, filemanager=None, **kwargs): self.filemanager = filemanager or FileManager() self._should_delete = False super(FileUploadField, self).__init__(label, validators, **kwargs) def process_on_delete(self, obj): pass def process_on_store(self, obj, byte_stream): pass def pre_validate(self, form): if ( self.data and isinstance(self.data, FileStorage) and not self.filemanager.is_file_allowed(self.data.filename) ): raise ValidationError(gettext("Invalid file extension")) def process(self, formdata, data=unset_value): if formdata: marker = "_%s-delete" % self.name if marker in formdata: self._should_delete = True return super(FileUploadField, self).process(formdata, data) def populate_obj(self, obj, name): field = getattr(obj, name, None) if field: if self._should_delete: self.process_on_delete(obj) self.filemanager.delete_file(field) setattr(obj, name, None) return if self.data and isinstance(self.data, FileStorage): if field: self.process_on_delete(obj) self.filemanager.delete_file(field) position = self.data.stream.tell() self.process_on_store(obj, self.data.stream) self.data.stream.seek(position) filename = self.filemanager.generate_name(obj, self.data) filename = self.filemanager.save_file(self.data, filename) setattr(obj, name, filename) class ImageUploadField(fields.StringField): widget = BS3ImageUploadFieldWidget() def __init__(self, label=None, validators=None, imagemanager=None, **kwargs): self.imagemanager = imagemanager or ImageManager() self._should_delete = False super(ImageUploadField, self).__init__(label, validators, **kwargs) def pre_validate(self, form): if ( self.data and isinstance(self.data, FileStorage) and not self.imagemanager.is_file_allowed(self.data.filename) ): raise ValidationError(gettext("Invalid file extension")) def process(self, formdata, data=unset_value): if formdata: marker = "_%s-delete" % self.name if marker in formdata: self._should_delete = True return super(ImageUploadField, self).process(formdata, data) def populate_obj(self, obj, name): field = getattr(obj, name, None) size = obj.__mapper__.columns[name].type.size thumbnail_size = obj.__mapper__.columns[name].type.thumbnail_size if field: if self._should_delete: self.imagemanager.delete_file(field) setattr(obj, name, None) return if self.data and isinstance(self.data, FileStorage): if field: self.imagemanager.delete_file(field) filename = self.imagemanager.generate_name(obj, self.data) filename = self.imagemanager.save_file( self.data, filename, size, thumbnail_size ) setattr(obj, name, filename)
true
true
1c372cbb8dc8e60a038c8382ff9a7f1df34661e3
15,918
py
Python
hdmm/hdmm/templates.py
FumiyukiKato/PrivBTS
d2fae18588b24281d0968b8af09dc9295e73cdda
[ "Apache-2.0" ]
null
null
null
hdmm/hdmm/templates.py
FumiyukiKato/PrivBTS
d2fae18588b24281d0968b8af09dc9295e73cdda
[ "Apache-2.0" ]
null
null
null
hdmm/hdmm/templates.py
FumiyukiKato/PrivBTS
d2fae18588b24281d0968b8af09dc9295e73cdda
[ "Apache-2.0" ]
null
null
null
import numpy as np from scipy import sparse, optimize from scipy.sparse.linalg import spsolve_triangular, aslinearoperator from hdmm import workload, approximation, implicit import time from functools import reduce class TemplateStrategy: """ A template strategy is a space of strategies parameterized by some vector of weights. This weight vector can be optimized for a particular workload. """ def __init__(self, theta0=None): self.set_params(theta0) def get_params(self): return self.theta def set_params(self, theta): self.theta = np.maximum(theta, 0) def run_mechanism(self, x, eps): """ Run the matrix mechanism with the current strategy on the given data vector """ A = self.strategy() A1 = self.inverse() delta = self.sensitivity() y = A.dot(x) + np.random.laplace(0, delta/eps, size=A.shape[0]) return A1.dot(y) @property def A(self): return self.strategy(form='matrix') def _AtA1(self): return np.linalg.pinv(self.A.T.dot(self.A)) def sparse_matrix(self): return sparse.csr_matrix(self.A) def strategy(self, form='linop'): """ Return a linear operator for the strategy """ assert form in ['matrix', 'linop'] A = self._strategy() if form == 'matrix': I = np.eye(A.shape[1]) return A.dot(I) return A def _strategy(self): return aslinearoperator(self.A) def inverse(self, form='linop'): """ Return a linear operator for the pseudo inverse of the strategy """ assert form in ['matrix', 'linop'] A1 = self._inverse() if form == 'matrix': I = np.eye(A1.shape[1]) return A1.dot(I) return A1 def _inverse(self): return aslinearoperator(np.linalg.pinv(self.A)) def _loss_and_grad(self): pass def sensitivity(self): return np.abs(self.A).sum(axis=0).max() def set_workload(self, W): self.workload = W def optimize(self, W): """ Optimize strategy for given workload :param W: the workload, may be a n x n numpy array for WtW or a workload object """ t0 = time.time() self.set_workload(W) init = self.get_params() bnds = [(0,None)] * init.size log = [] def obj(theta): self.set_params(theta) ans = self._loss_and_grad() log.append(ans[0]) return ans opts = { 'ftol' : 1e-4 } res = optimize.minimize(obj, init, jac=True, method='L-BFGS-B', bounds=bnds, options=opts) t1 = time.time() params = self.get_params() ans = { 'log' : log, 'time' : t1 - t0, 'loss' : res.fun, 'res' : res, 'params' : params } return ans def restart_optimize(self, W, restarts): best = self.optimize(W) for i in range(restarts-1): ans = self.optimize(W) if ans['loss'] < best['loss']: best = ans self.set_params(best['params']) return best class Default(TemplateStrategy): """ """ def __init__(self, m, n): theta0 = np.random.rand(m*n) self.m = m self.n = n TemplateStrategy.__init__(theta0) def _strategy(self): return self.get_params().reshape(self.m, self.n) def _loss_and_grad(self): WtW = self.workload.WtW A = self.get_params().reshape(self.m, self.n) sums = np.sum(np.abs(A), axis=0) col = np.argmax(sums) F = sums[col]**2 # note: F is not differentiable, but we can take subgradients dF = np.zeros_like(A) dF[:,col] = np.sign(A[:,col])*2*sums[col] AtA = A.T.dot(A) AtA1 = np.linalg.pinv(AtA) M = WtW.dot(AtA1) G = np.trace(M) dX = -AtA1.dot(M) dG = 2*A.dot(dX) dA = dF*G + F*dG return F*G, dA.flatten() class PIdentity(TemplateStrategy): """ A PIdentity strategy is a strategy of the form (I + B) D where D is a diagonal scaling matrix that depends on B and ensures uniform column norm. B is a p x n matrix of free parameters. """ def __init__(self, p, n): """ Initialize a PIdentity strategy :param p: the number of non-identity queries :param n: the domain size """ theta0 = np.random.rand(p*n) self.p = p self.n = n TemplateStrategy.__init__(self, theta0) def sparse_matrix(self): I = sparse.identity(self.n, format='csr') B = self.get_params().reshape(self.p, self.n) D = 1 + B.sum(axis=0) A = sparse.vstack([I,B], format='csr') return A * sparse.diags(1.0 / D) def _strategy(self): I = np.eye(self.n) B = self.get_params().reshape(self.p, self.n) A = np.vstack([I, B]) A = A / A.sum(axis=0) return aslinearoperator(sparse.csr_matrix(A)) def _AtA1(self): B = self.get_params().reshape(self.p, self.n) R = np.linalg.inv(np.eye(self.p) + B.dot(B.T)) D = 1.0 + B.sum(axis=0) return (np.eye(self.n) - B.T.dot(R).dot(B))*D*D[:,None] def _inverse(self): B = self.get_params().reshape(self.p, self.n) return implicit.inverse(B) def _loss_and_grad(self): WtW = self.workload.WtW p, n = self.p, self.n B = np.reshape(self.get_params(), (p,n)) scale = 1.0 + np.sum(B, axis=0) R = np.linalg.inv(np.eye(p) + B.dot(B.T)) # O(k^3) C = WtW * scale * scale[:,None] # O(n^2) M1 = R.dot(B) # O(n k^2) M2 = M1.dot(C) # O(n^2 k) M3 = B.T.dot(M2) # O(n^2 k) M4 = B.T.dot(M2.dot(M1.T)).dot(B) # O(n^2 k) Z = -(C - M3 - M3.T + M4) * scale * scale[:,None] # O(n^2) Y1 = 2*np.diag(Z) / scale # O(n) Y2 = 2*(B/scale).dot(Z) # O(n^2 k) g = Y1 + (B*Y2).sum(axis=0) # O(n k) loss = np.trace(C) - np.trace(M3) grad = (Y2*scale - g) / scale**2 return loss, grad.flatten() class AugmentedIdentity(TemplateStrategy): """ An AugmentedIdentity strategy is like a PIdentity strategy with additional structure imposed. The template is defiend by a p x n matrix of non-negative integers P. Each unique nonzero entry of this matrix P refers to a free parameter that can be optimized. An entry that is 0 in P is a structural zero in the strategy. Example 1: A PIdentity strategy can be represented as an AugmentedIdentity strategy with P = np.arange(1, p*n+1).reshape(p, n) Example 2: A strategy of the form w*T + I can be represented as an AugmentedIdentity strategy with P = np.ones((1, n), dtype=int) """ def __init__(self, imatrix): """ Create an AugmentedIdentity strategy with the given P matrix """ self.imatrix = imatrix p, n = imatrix.shape num = imatrix.max() theta0 = np.random.rand(num) self._pid = PIdentity(p, n) TemplateStrategy.__init__(self, p+n, n, theta0) # should call set_params def _strategy(self): return self._pid._strategy() def _inverse(self): return self._pid.inverse() def set_params(theta): self.theta = theta params = np.append(0, theta) B = params[self.imatrix] self._pid.set_params(B.flatten()) def _AtA1(self): return self._pid._AtA1() def set_workload(self, W): self.workload = W self._pid.set_workload(W) def _loss_and_grad(self): #params = np.append(0, self.get_params()) #B = params[self.imatrix] #self._pid.set_params(B.flatten()) obj, grad = self._pid._loss_and_grad() grad2 = np.bincount(self.imatrix.flatten(), grad)[1:] return obj, grad2 class Static(TemplateStrategy): def __init__(self, strategy): self.A = strategy TemplateStrategy.__init__(self, np.array([])) def optimize(self, W): pass class Kronecker(TemplateStrategy): """ A Kronecker template strategy is of the form A1 x ... x Ad, where each Ai is some 1D template strategy""" def __init__(self, strategies): """ :param strategies: a list of templates for each dimension of template """ self.strategies = strategies def sparse_matrix(self): return reduce(sparse.kron, [A.sparse_matrix() for A in self.strategies]) def set_params(self, params): for strategy, param in zip(self.strategies, params): strategy.set_params(param) def get_params(self): return [strategy.get_params() for strategy in self.strategies] def _strategy(self): return implicit.krons(*[S._strategy() for S in self.strategies]) def _inverse(self): return implicit.krons(*[S._inverse() for S in self.strategies]) def sensitivity(self): return np.prod([S.sensitivity() for S in self.strategies]) def optimize(self, W): self.set_workload(W) t0 = time.time() if isinstance(W, workload.Kron): loss = 0 for subA, subW in zip(self.strategies, W.workloads): ans = subA.optimize(subW) loss += ans['loss'] params = self.get_params() return { 'time' : time.time() - t0, 'loss' : loss, 'params' : params } assert isinstance(W, workload.Concat) and isinstance(W.workloads[0], workload.Kron) workloads = [K.workloads for K in W.workloads] # a k x d table of workloads strategies = self.strategies k = len(workloads) d = len(workloads[0]) log = [] C = np.ones((d, k)) for i in range(d): AtA1 = strategies[i]._AtA1() for j in range(k): C[i,j] = np.sum(workloads[j][i].WtW * AtA1) for r in range(10): err = C.prod(axis=0).sum() for i in range(d): cs = np.sqrt(C.prod(axis=0) / C[i]) What = workload.Concat([c*Ws[i] for c, Ws in zip(cs, workloads)]) res = strategies[i].optimize(What) AtA1 = strategies[i]._AtA1() for j in range(k): C[i,j] = np.sum(workloads[j][i].WtW * AtA1) log.append(err) t1 = time.time() params = self.get_params() ans = { 'log' : log, 'loss' : err, 'time' : t1 - t0, 'params' : params } return ans class Marginals(TemplateStrategy): """ A marginals template is parameterized by 2^d weights where d is the number of dimensions. The strategy is of the form w_1 (T x ... x T) + ... + w_{2^d} (I x ... I) - every marginal with nonzero weight is queried with weight w_i """ def __init__(self, domain): self.domain = domain theta = np.random.rand(2**len(domain)) d = len(domain) mult = np.ones(2**d) for i in range(2**d): for k in range(d): if not (i & (2**k)): mult[i] *= domain[k] self.mult = mult TemplateStrategy.__init__(self, theta) def _strategy(self): return implicit.marginals_linop(self.domain, self.get_params()) def _inverse(self): theta = self.get_params() Y, _ = self._Xmatrix(theta**2) tmp = Y.dot(theta**2) X, _ = self._Xmatrix(tmp) invtheta = spsolve_triangular(X, theta**2, lower=False) return implicit.marginals_inverse(self.domain, theta, invtheta) def sensitivity(self): return np.sum(np.abs(self.get_params())) def _Xmatrix(self,vect): # the matrix X such that M(u) M(v) = M(X(u) v) d = len(self.domain) A = np.arange(2**d) mult = self.mult values = np.zeros(3**d) rows = np.zeros(3**d, dtype=int) cols = np.zeros(3**d, dtype=int) start = 0 for b in range(2**d): #uniq, rev = np.unique(a&B, return_inverse=True) # most of time being spent here mask = np.zeros(2**d, dtype=int) mask[A&b] = 1 uniq = np.nonzero(mask)[0] step = uniq.size mask[uniq] = np.arange(step) rev = mask[A&b] values[start:start+step] = np.bincount(rev, vect*mult[A|b], step) if values[start+step-1] == 0: values[start+step-1] = 1.0 cols[start:start+step] = b rows[start:start+step] = uniq start += step X = sparse.csr_matrix((values, (rows, cols)), (2**d, 2**d)) XT = sparse.csr_matrix((values, (cols, rows)), (2**d, 2**d)) return X, XT def set_workload(self, W): marg = approximation.marginals_approx(W) self.workload = marg d = len(self.domain) A = np.arange(2**d) weights = marg.weight_vector() self.dphi = np.array([np.dot(weights**2, self.mult[A|b]) for b in range(2**d)]) def _loss_and_grad(self): d = len(self.domain) A = np.arange(2**d) mult = self.mult dphi = self.dphi theta = self.get_params() delta = np.sum(theta)**2 ddelta = 2*np.sum(theta) theta2 = theta**2 Y, YT = self._Xmatrix(theta2) params = Y.dot(theta2) X, XT = self._Xmatrix(params) phi = spsolve_triangular(X, theta2, lower=False) # Note: we should be multiplying by domain size here if we want total squared error ans = np.dot(phi, dphi) dXvect = -spsolve_triangular(XT, dphi, lower=True) # dX = outer(dXvect, phi) dparams = np.array([np.dot(dXvect[A&b]*phi, mult[A|b]) for b in range(2**d)]) dtheta2 = YT.dot(dparams) dtheta = 2*theta*dtheta2 return delta*ans, delta*dtheta + ddelta*ans # (df / dtheta_k) = sum_ij (df / d_Aij) (dA_ij / theta_k) def KronPIdentity(ns, ps): """ Builds a template strategy of the form A1 x ... x Ad where each Ai is a PIdentity template :param ns: the domain size of each dimension :param ps: the number of p queries in each dimension """ return Kronecker([PIdentity(p, n) for p,n in zip(ps, ns)]) def RangeTemplate(n, start=32, branch=4, shared=False): """ Builds a template strategy for range queries with queries that have structural zeros everywhere except at indices at [i, i+w) where w is the width of the query and ranges from start to n in powers of branch and i is a multiple of w/2. :param n: the domain size :param start: the width of the smallest query :param branch: the width multiplying factor for larger queries :param shared: flag to determine if parameters should be shared for queries of the same width Example: RangeTemplate(16, start=8, branch=2) builds a strategy template with four augmented queries that have structural zeros everywhere except in the intervals indicated below: 1. [0,8) 2. [4,12) 3. [8,16) 4. [0,16) """ rows = [] width = start idx = 1 while width <= n: for i in range(0, n-width//2, width//2): row = np.zeros(n, dtype=int) row[i:i+width] = np.arange(width) + idx if not shared: idx += width rows.append(row) if shared: idx += width width *= branch return AugmentedIdentity(np.vstack(rows)) def IdTotal(n): """ Build a single-parameter template strategy of the form w*Total + Identity """ P = np.ones((1,n), dtype=int) return AugmentedIdentity(P) def Identity(n): """ Builds a template strategy that is always Identity """ return Static(np.eye(n)) def Total(n): """ Builds a template strategy that is always Total """ return Static(np.ones((1,n)))
33.1625
174
0.572245
import numpy as np from scipy import sparse, optimize from scipy.sparse.linalg import spsolve_triangular, aslinearoperator from hdmm import workload, approximation, implicit import time from functools import reduce class TemplateStrategy: def __init__(self, theta0=None): self.set_params(theta0) def get_params(self): return self.theta def set_params(self, theta): self.theta = np.maximum(theta, 0) def run_mechanism(self, x, eps): A = self.strategy() A1 = self.inverse() delta = self.sensitivity() y = A.dot(x) + np.random.laplace(0, delta/eps, size=A.shape[0]) return A1.dot(y) @property def A(self): return self.strategy(form='matrix') def _AtA1(self): return np.linalg.pinv(self.A.T.dot(self.A)) def sparse_matrix(self): return sparse.csr_matrix(self.A) def strategy(self, form='linop'): assert form in ['matrix', 'linop'] A = self._strategy() if form == 'matrix': I = np.eye(A.shape[1]) return A.dot(I) return A def _strategy(self): return aslinearoperator(self.A) def inverse(self, form='linop'): assert form in ['matrix', 'linop'] A1 = self._inverse() if form == 'matrix': I = np.eye(A1.shape[1]) return A1.dot(I) return A1 def _inverse(self): return aslinearoperator(np.linalg.pinv(self.A)) def _loss_and_grad(self): pass def sensitivity(self): return np.abs(self.A).sum(axis=0).max() def set_workload(self, W): self.workload = W def optimize(self, W): t0 = time.time() self.set_workload(W) init = self.get_params() bnds = [(0,None)] * init.size log = [] def obj(theta): self.set_params(theta) ans = self._loss_and_grad() log.append(ans[0]) return ans opts = { 'ftol' : 1e-4 } res = optimize.minimize(obj, init, jac=True, method='L-BFGS-B', bounds=bnds, options=opts) t1 = time.time() params = self.get_params() ans = { 'log' : log, 'time' : t1 - t0, 'loss' : res.fun, 'res' : res, 'params' : params } return ans def restart_optimize(self, W, restarts): best = self.optimize(W) for i in range(restarts-1): ans = self.optimize(W) if ans['loss'] < best['loss']: best = ans self.set_params(best['params']) return best class Default(TemplateStrategy): def __init__(self, m, n): theta0 = np.random.rand(m*n) self.m = m self.n = n TemplateStrategy.__init__(theta0) def _strategy(self): return self.get_params().reshape(self.m, self.n) def _loss_and_grad(self): WtW = self.workload.WtW A = self.get_params().reshape(self.m, self.n) sums = np.sum(np.abs(A), axis=0) col = np.argmax(sums) F = sums[col]**2 dF = np.zeros_like(A) dF[:,col] = np.sign(A[:,col])*2*sums[col] AtA = A.T.dot(A) AtA1 = np.linalg.pinv(AtA) M = WtW.dot(AtA1) G = np.trace(M) dX = -AtA1.dot(M) dG = 2*A.dot(dX) dA = dF*G + F*dG return F*G, dA.flatten() class PIdentity(TemplateStrategy): def __init__(self, p, n): theta0 = np.random.rand(p*n) self.p = p self.n = n TemplateStrategy.__init__(self, theta0) def sparse_matrix(self): I = sparse.identity(self.n, format='csr') B = self.get_params().reshape(self.p, self.n) D = 1 + B.sum(axis=0) A = sparse.vstack([I,B], format='csr') return A * sparse.diags(1.0 / D) def _strategy(self): I = np.eye(self.n) B = self.get_params().reshape(self.p, self.n) A = np.vstack([I, B]) A = A / A.sum(axis=0) return aslinearoperator(sparse.csr_matrix(A)) def _AtA1(self): B = self.get_params().reshape(self.p, self.n) R = np.linalg.inv(np.eye(self.p) + B.dot(B.T)) D = 1.0 + B.sum(axis=0) return (np.eye(self.n) - B.T.dot(R).dot(B))*D*D[:,None] def _inverse(self): B = self.get_params().reshape(self.p, self.n) return implicit.inverse(B) def _loss_and_grad(self): WtW = self.workload.WtW p, n = self.p, self.n B = np.reshape(self.get_params(), (p,n)) scale = 1.0 + np.sum(B, axis=0) R = np.linalg.inv(np.eye(p) + B.dot(B.T)) C = WtW * scale * scale[:,None] M1 = R.dot(B) M2 = M1.dot(C) M3 = B.T.dot(M2) M4 = B.T.dot(M2.dot(M1.T)).dot(B) Z = -(C - M3 - M3.T + M4) * scale * scale[:,None] Y1 = 2*np.diag(Z) / scale Y2 = 2*(B/scale).dot(Z) g = Y1 + (B*Y2).sum(axis=0) loss = np.trace(C) - np.trace(M3) grad = (Y2*scale - g) / scale**2 return loss, grad.flatten() class AugmentedIdentity(TemplateStrategy): def __init__(self, imatrix): self.imatrix = imatrix p, n = imatrix.shape num = imatrix.max() theta0 = np.random.rand(num) self._pid = PIdentity(p, n) TemplateStrategy.__init__(self, p+n, n, theta0) def _strategy(self): return self._pid._strategy() def _inverse(self): return self._pid.inverse() def set_params(theta): self.theta = theta params = np.append(0, theta) B = params[self.imatrix] self._pid.set_params(B.flatten()) def _AtA1(self): return self._pid._AtA1() def set_workload(self, W): self.workload = W self._pid.set_workload(W) def _loss_and_grad(self): obj, grad = self._pid._loss_and_grad() grad2 = np.bincount(self.imatrix.flatten(), grad)[1:] return obj, grad2 class Static(TemplateStrategy): def __init__(self, strategy): self.A = strategy TemplateStrategy.__init__(self, np.array([])) def optimize(self, W): pass class Kronecker(TemplateStrategy): def __init__(self, strategies): self.strategies = strategies def sparse_matrix(self): return reduce(sparse.kron, [A.sparse_matrix() for A in self.strategies]) def set_params(self, params): for strategy, param in zip(self.strategies, params): strategy.set_params(param) def get_params(self): return [strategy.get_params() for strategy in self.strategies] def _strategy(self): return implicit.krons(*[S._strategy() for S in self.strategies]) def _inverse(self): return implicit.krons(*[S._inverse() for S in self.strategies]) def sensitivity(self): return np.prod([S.sensitivity() for S in self.strategies]) def optimize(self, W): self.set_workload(W) t0 = time.time() if isinstance(W, workload.Kron): loss = 0 for subA, subW in zip(self.strategies, W.workloads): ans = subA.optimize(subW) loss += ans['loss'] params = self.get_params() return { 'time' : time.time() - t0, 'loss' : loss, 'params' : params } assert isinstance(W, workload.Concat) and isinstance(W.workloads[0], workload.Kron) workloads = [K.workloads for K in W.workloads] strategies = self.strategies k = len(workloads) d = len(workloads[0]) log = [] C = np.ones((d, k)) for i in range(d): AtA1 = strategies[i]._AtA1() for j in range(k): C[i,j] = np.sum(workloads[j][i].WtW * AtA1) for r in range(10): err = C.prod(axis=0).sum() for i in range(d): cs = np.sqrt(C.prod(axis=0) / C[i]) What = workload.Concat([c*Ws[i] for c, Ws in zip(cs, workloads)]) res = strategies[i].optimize(What) AtA1 = strategies[i]._AtA1() for j in range(k): C[i,j] = np.sum(workloads[j][i].WtW * AtA1) log.append(err) t1 = time.time() params = self.get_params() ans = { 'log' : log, 'loss' : err, 'time' : t1 - t0, 'params' : params } return ans class Marginals(TemplateStrategy): def __init__(self, domain): self.domain = domain theta = np.random.rand(2**len(domain)) d = len(domain) mult = np.ones(2**d) for i in range(2**d): for k in range(d): if not (i & (2**k)): mult[i] *= domain[k] self.mult = mult TemplateStrategy.__init__(self, theta) def _strategy(self): return implicit.marginals_linop(self.domain, self.get_params()) def _inverse(self): theta = self.get_params() Y, _ = self._Xmatrix(theta**2) tmp = Y.dot(theta**2) X, _ = self._Xmatrix(tmp) invtheta = spsolve_triangular(X, theta**2, lower=False) return implicit.marginals_inverse(self.domain, theta, invtheta) def sensitivity(self): return np.sum(np.abs(self.get_params())) def _Xmatrix(self,vect): d = len(self.domain) A = np.arange(2**d) mult = self.mult values = np.zeros(3**d) rows = np.zeros(3**d, dtype=int) cols = np.zeros(3**d, dtype=int) start = 0 for b in range(2**d): *d, dtype=int) mask[A&b] = 1 uniq = np.nonzero(mask)[0] step = uniq.size mask[uniq] = np.arange(step) rev = mask[A&b] values[start:start+step] = np.bincount(rev, vect*mult[A|b], step) if values[start+step-1] == 0: values[start+step-1] = 1.0 cols[start:start+step] = b rows[start:start+step] = uniq start += step X = sparse.csr_matrix((values, (rows, cols)), (2**d, 2**d)) XT = sparse.csr_matrix((values, (cols, rows)), (2**d, 2**d)) return X, XT def set_workload(self, W): marg = approximation.marginals_approx(W) self.workload = marg d = len(self.domain) A = np.arange(2**d) weights = marg.weight_vector() self.dphi = np.array([np.dot(weights**2, self.mult[A|b]) for b in range(2**d)]) def _loss_and_grad(self): d = len(self.domain) A = np.arange(2**d) mult = self.mult dphi = self.dphi theta = self.get_params() delta = np.sum(theta)**2 ddelta = 2*np.sum(theta) theta2 = theta**2 Y, YT = self._Xmatrix(theta2) params = Y.dot(theta2) X, XT = self._Xmatrix(params) phi = spsolve_triangular(X, theta2, lower=False) ans = np.dot(phi, dphi) dXvect = -spsolve_triangular(XT, dphi, lower=True) dparams = np.array([np.dot(dXvect[A&b]*phi, mult[A|b]) for b in range(2**d)]) dtheta2 = YT.dot(dparams) dtheta = 2*theta*dtheta2 return delta*ans, delta*dtheta + ddelta*ans def KronPIdentity(ns, ps): return Kronecker([PIdentity(p, n) for p,n in zip(ps, ns)]) def RangeTemplate(n, start=32, branch=4, shared=False): rows = [] width = start idx = 1 while width <= n: for i in range(0, n-width//2, width//2): row = np.zeros(n, dtype=int) row[i:i+width] = np.arange(width) + idx if not shared: idx += width rows.append(row) if shared: idx += width width *= branch return AugmentedIdentity(np.vstack(rows)) def IdTotal(n): P = np.ones((1,n), dtype=int) return AugmentedIdentity(P) def Identity(n): return Static(np.eye(n)) def Total(n): return Static(np.ones((1,n)))
true
true
1c372de3506f67236b280e392579b58017caeaa1
2,872
py
Python
cnn.py
arupkpatel/HandGestureDetection
2be7224a53a100c37b71e7a6333ed69f5729032a
[ "Apache-2.0" ]
null
null
null
cnn.py
arupkpatel/HandGestureDetection
2be7224a53a100c37b71e7a6333ed69f5729032a
[ "Apache-2.0" ]
null
null
null
cnn.py
arupkpatel/HandGestureDetection
2be7224a53a100c37b71e7a6333ed69f5729032a
[ "Apache-2.0" ]
null
null
null
import tensorflow as tf from keras.backend.tensorflow_backend import set_session config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.3 set_session(tf.Session(config=config)) from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout classifier = Sequential() classifier.add(Conv2D(32, (3, 3), input_shape=(48, 48, 1), activation='relu')) classifier.add(Conv2D(32, (3, 3), activation='relu')) classifier.add(MaxPooling2D(pool_size=(2, 2))) classifier.add(Dropout(.25)) # classifier.add(MaxPooling2D(pool_size=(2, 2))) # classifier.add(Dropout(.20)) classifier.add(Conv2D(32, (3, 3), activation='relu')) classifier.add(MaxPooling2D(pool_size=(2, 2))) classifier.add(Dropout(.25)) classifier.add(Flatten()) classifier.add(Dense(256, activation='relu')) classifier.add(Dropout(.5)) classifier.add(Dense(1, activation='sigmoid')) classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1. / 255) train_set = train_datagen.flow_from_directory( 'dataset/training', target_size=(48, 48), batch_size=16, color_mode='grayscale', class_mode='binary') test_set = test_datagen.flow_from_directory( 'dataset/testing', target_size=(48, 48), batch_size=16, class_mode='binary', color_mode='grayscale') classifier.fit_generator( train_set, steps_per_epoch=8575, epochs=5, validation_data=test_set, validation_steps=2000) print('done!!') classifier.save('cdi.h5') classifier.save_weights('cdiw.h5') jstring = classifier.to_json() jfile = open('classifier.json','w') jfile.write(jstring) jfile.close() # from keras.models import load_model # classifier = load_model('cdi.h5') # import numpy as np # from keras.preprocessing import image # import cv2 # import os # img = cv2.imread('spred\\9.jpg',0) # img2 =cv2.imread('spred\\8.jpg') # imgbw = cv2.resize(img, (48, 48)) # imgbw = image.img_to_array(imgbw) # imgbw = np.expand_dims(imgbw, axis=0) # result = classifier.predict(imgbw) # # print(result) # if result[0][0] == 0: # print('1') # os.system('notepad') # cv2.putText(img2, 'Gesture Recognised: Notepad', (50, 50), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, # color=(255, 0, 0), # thickness=3) # else: # print('2') # os.system('calc') # cv2.putText(img2, 'Gesture Recognised: Calculator', (50, 50), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, # color=(255, 0, 0), thickness=3) # cv2.imshow('Output',img2) # cv2.waitKey(0) # cv2.destroyAllWindows()
26.841121
115
0.707173
import tensorflow as tf from keras.backend.tensorflow_backend import set_session config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.3 set_session(tf.Session(config=config)) from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout classifier = Sequential() classifier.add(Conv2D(32, (3, 3), input_shape=(48, 48, 1), activation='relu')) classifier.add(Conv2D(32, (3, 3), activation='relu')) classifier.add(MaxPooling2D(pool_size=(2, 2))) classifier.add(Dropout(.25)) classifier.add(Conv2D(32, (3, 3), activation='relu')) classifier.add(MaxPooling2D(pool_size=(2, 2))) classifier.add(Dropout(.25)) classifier.add(Flatten()) classifier.add(Dense(256, activation='relu')) classifier.add(Dropout(.5)) classifier.add(Dense(1, activation='sigmoid')) classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1. / 255) train_set = train_datagen.flow_from_directory( 'dataset/training', target_size=(48, 48), batch_size=16, color_mode='grayscale', class_mode='binary') test_set = test_datagen.flow_from_directory( 'dataset/testing', target_size=(48, 48), batch_size=16, class_mode='binary', color_mode='grayscale') classifier.fit_generator( train_set, steps_per_epoch=8575, epochs=5, validation_data=test_set, validation_steps=2000) print('done!!') classifier.save('cdi.h5') classifier.save_weights('cdiw.h5') jstring = classifier.to_json() jfile = open('classifier.json','w') jfile.write(jstring) jfile.close()
true
true
1c372e7911af2d48425eb1bb3bd4b30efc1e9ce6
536
py
Python
projectmanager/migrations/0043_auto_20201007_1826.py
leonolan2020/phoenix
b5956a7003e548f01255cbd5d0d76cfd0ac77a81
[ "MIT" ]
1
2020-09-19T21:56:40.000Z
2020-09-19T21:56:40.000Z
projectmanager/migrations/0043_auto_20201007_1826.py
leonolan2020/phoenix
b5956a7003e548f01255cbd5d0d76cfd0ac77a81
[ "MIT" ]
null
null
null
projectmanager/migrations/0043_auto_20201007_1826.py
leonolan2020/phoenix
b5956a7003e548f01255cbd5d0d76cfd0ac77a81
[ "MIT" ]
5
2020-09-18T18:53:03.000Z
2020-10-21T14:42:00.000Z
# Generated by Django 3.1 on 2020-10-07 14:56 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0042_auto_20201006_0242'), ] operations = [ migrations.AlterField( model_name='material', name='brand', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='projectmanager.materialbrand', verbose_name='brand'), ), ]
26.8
161
0.664179
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projectmanager', '0042_auto_20201006_0242'), ] operations = [ migrations.AlterField( model_name='material', name='brand', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='projectmanager.materialbrand', verbose_name='brand'), ), ]
true
true
1c37308f55115990d2a038110d5526d8dc981ec4
9,090
py
Python
paper/scripts/emcee-comp/compare.py
dfm/rvhmc
03c9aa6a28722989cf3a6da8963a54d1e1faa0cf
[ "Apache-2.0" ]
1
2018-06-19T03:02:08.000Z
2018-06-19T03:02:08.000Z
paper/scripts/emcee-comp/compare.py
dfm/rvhmc
03c9aa6a28722989cf3a6da8963a54d1e1faa0cf
[ "Apache-2.0" ]
null
null
null
paper/scripts/emcee-comp/compare.py
dfm/rvhmc
03c9aa6a28722989cf3a6da8963a54d1e1faa0cf
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function import os import sys if len(sys.argv) > 1: n_planets = int(sys.argv[1]) else: n_planets = 1 dirname = "{0:02d}".format(n_planets) if len(sys.argv) > 2: version = int(sys.argv[2]) dirname = os.path.join(dirname, "{0:04d}".format(version)) else: version = 0 os.makedirs(dirname, exist_ok=True) os.environ["THEANO_FLAGS"] = \ "compiledir=./{0}/cache".format(dirname) import time import string import emcee import corner import numpy as np import pandas as pd import matplotlib.pyplot as plt import pymc3 as pm import theano import theano.tensor as tt from rvhmc import RVDataset, PolynomialTrend, RVModel, RVPlanet def build_model(peaks, t, y=None, yerr=None, model=None): model = pm.modelcontext(model) n_planets = len(peaks) if yerr is None: yerr = np.random.uniform(0.01, 0.1, len(t)) if y is None: y = yerr*np.random.randn(len(t)) trend = PolynomialTrend("trend", order=3) logs = pm.Normal("logs", mu=-5.0, sd=5.0, testval=-5.0) meanrv = pm.Normal("meanrv", mu=0.0, sd=10.0, testval=0.0) dataset = RVDataset("data", t, y, yerr, logs=logs, trend=trend, meanrv=meanrv) logamps = pm.Uniform("logamps", lower=np.log(min_amp), upper=np.log(max_amp), shape=n_planets, testval=np.log([np.clip(peak["amp"], min_amp+1e-2, max_amp-1e-2) for peak in peaks])) planets = [] for i, (peak, name) in enumerate(zip(peaks, string.ascii_lowercase[1:])): logP = pm.Uniform(name + ":logP", lower=np.log(min_period), upper=np.log(max_period), testval=np.log(peak["period"])) logK = pm.Deterministic(name + ":logK", logamps[i]) eccen = pm.Beta(name + ":eccen", alpha=0.867, beta=3.03, testval=peak["eccen"]) omegabase = pm.Uniform(name + ":omegabase", -2*np.pi, 2*np.pi, testval=peak["omega"]) omegavec = pm.Deterministic(name + ":omegavec", tt.stack([tt.cos(omegabase), tt.sin(omegabase)])) phibase = pm.Uniform(name + ":phibase", -2*np.pi, 2*np.pi, testval=peak["phase"]) phivec = pm.Deterministic(name + ":phivec", tt.stack([tt.cos(phibase), tt.sin(phibase)])) planets.append( RVPlanet(name, logP, logK, phivec=phivec, eccen=eccen, omegavec=omegavec)) rvmodel = RVModel("rv", dataset, planets) pm.Deterministic("logp", model.logpt) return rvmodel # Simulate a random dataset np.random.seed(42 + version) t = np.sort(np.random.uniform(0.0, 4*365.0, 50)) yerr = np.random.uniform(0.01, 0.1, len(t)) y = yerr * np.random.randn(len(t)) min_period = 5 max_period = 100 min_amp = 0.2 max_amp = 0.8 target_n_eff = 500 peaks = [] for i in range(n_planets): peaks.append(dict( period=np.exp(np.random.uniform(np.log(min_period), np.log(max_period))), amp=np.exp(np.random.uniform(np.log(min_amp), np.log(max_amp))), phase=np.random.uniform(0, 2*np.pi), omega=np.random.uniform(0, 2*np.pi), eccen=np.random.uniform(0.01, 0.3), )) peaks = sorted(peaks, key=lambda x: x["amp"]) with pm.Model() as sim_model: sim_rvmodel = build_model(peaks, t, y, yerr) f = theano.function(sim_model.vars, sim_rvmodel.get_rvmodels(t), on_unused_input="ignore") coords = sim_model.test_point y += np.sum(f(*(coords[k.name] for k in sim_model.vars)), axis=1) # Plot the data fig = plt.figure() plt.errorbar(t % peaks[-1]["period"], y, yerr=yerr, fmt=".k") fig.savefig(os.path.join(dirname, "data.png"), bbox_inches="tight") plt.close(fig) # Work out the key variables with pm.Model() as model: rvmodel = build_model(peaks, t, y, yerr) key_vars = [v.name for v in rvmodel.datasets[0].vars] key_vars += [p.name + k for p in rvmodel.planets for k in (":logP", ":logK", ":phi", ":eccen", ":omega")] # Fit using emcee with model: f = theano.function(model.vars, [model.logpt] + model.vars + model.deterministics) def log_prob_func(params): dct = model.bijection.rmap(params) args = (dct[k.name] for k in model.vars) results = f(*args) return tuple(results) # First we work out the shapes of all of the deterministic variables res = model.test_point vec = model.bijection.map(res) initial_blobs = log_prob_func(vec)[1:] dtype = [(var.name, float, np.shape(b)) for var, b in zip(model.vars + model.deterministics, initial_blobs)] # Then sample as usual coords = vec + 1e-5 * np.random.randn(3*len(vec), len(vec)) nwalkers, ndim = coords.shape sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob_func, blobs_dtype=dtype) thin_by = 100 tottime = 0 for i in range(1000): strt = time.time() sampler.run_mcmc(coords, 50, thin_by=thin_by, progress=True) tottime += time.time() - strt samples = sampler.get_blobs() tau = np.array([float(emcee.autocorr.integrated_time(samples[k], tol=0)) for k in key_vars]) print(sampler.iteration * nwalkers / tau) converged = np.all(tau * target_n_eff / thin_by < sampler.iteration * nwalkers) converged &= np.all(sampler.iteration > 50 * tau) if converged: break samples = sampler.get_blobs(discard=int(tau.max())) tau_emcee = np.array([float(emcee.autocorr.integrated_time(samples[k], tol=0)) for k in key_vars]) time_emcee = tottime time_per_emcee = time_emcee / (sampler.iteration * nwalkers) time_ind_emcee = time_per_emcee * tau_emcee # Sample using pymc with model: start = model.test_point ntune = 2000 samples = sampler.get_chain(discard=int(tau_emcee.max()), flat=True) potential = pm.step_methods.hmc.quadpotential.QuadPotentialFull( np.cov(samples, rowvar=0)) step = pm.NUTS(potential=potential) # ntune = 5000 # _, step = pm.init_nuts(init="adapt_diag", target_accept=0.8) print("Running burn-in...") burnin = pm.sample(start=start, tune=ntune, draws=1, step=step, chains=1, compute_convergence_checks=False) trace = None next_start = burnin.point(-1) draws = 2000 chains = 2 ntotal = 0 tottime = 0 for i in range(100): strt = time.time() trace = pm.sample(start=next_start, trace=trace, tune=0, draws=draws, step=step, chains=chains, compute_convergence_checks=False, cores=1) tottime += time.time() - strt ntotal += draws * chains next_start = [trace.point(-1, c) for c in trace.chains] tau = np.array([ float(emcee.autocorr.integrated_time(np.array( trace.get_values(v, combine=False)).T, tol=0)) for v in key_vars]) print(tau) print(ntotal / tau) print(pm.summary(trace, varnames=key_vars).n_eff) if (ntotal / tau).min() > target_n_eff and ntotal > tau.max() * 50: break tau_pymc = np.copy(tau) time_pymc = tottime time_per_pymc = time_pymc / (len(trace) * chains) time_ind_pymc = time_per_pymc * tau_pymc print("time per ind. sample, emcee: {0}".format(time_ind_emcee)) print("time per ind. sample, pymc: {0}".format(time_ind_pymc)) print("time per ind. sample, ratio: {0}" .format(time_ind_emcee / time_ind_pymc)) df = pd.DataFrame(dict(zip(key_vars, zip(time_ind_emcee, time_ind_pymc)))) df["method"] = ["emcee", "pymc"] df.to_csv(os.path.join(dirname, "results.csv"), index=False) tau = tau_emcee.max() samples = sampler.get_blobs(flat=True, discard=int(2*tau), thin=int(tau)) df_emcee = pd.DataFrame.from_records(samples[key_vars]) ranges = [(np.min(df_emcee[k]), np.max(df_emcee[k])) for k in df_emcee.columns] df_pymc = pm.trace_to_dataframe(trace, varnames=key_vars) w_pymc = len(df_emcee) / len(df_pymc) + np.zeros(len(df_pymc)) v = key_vars[:15] fig = corner.corner(df_emcee[v], color="C0", range=ranges[:len(v)]) corner.corner(df_pymc[v], weights=w_pymc, color="C1", fig=fig, range=ranges[:len(v)]) fig.savefig(os.path.join(dirname, "corner.png"), bbox_inches="tight") plt.close(fig)
33.791822
79
0.579538
from __future__ import division, print_function import os import sys if len(sys.argv) > 1: n_planets = int(sys.argv[1]) else: n_planets = 1 dirname = "{0:02d}".format(n_planets) if len(sys.argv) > 2: version = int(sys.argv[2]) dirname = os.path.join(dirname, "{0:04d}".format(version)) else: version = 0 os.makedirs(dirname, exist_ok=True) os.environ["THEANO_FLAGS"] = \ "compiledir=./{0}/cache".format(dirname) import time import string import emcee import corner import numpy as np import pandas as pd import matplotlib.pyplot as plt import pymc3 as pm import theano import theano.tensor as tt from rvhmc import RVDataset, PolynomialTrend, RVModel, RVPlanet def build_model(peaks, t, y=None, yerr=None, model=None): model = pm.modelcontext(model) n_planets = len(peaks) if yerr is None: yerr = np.random.uniform(0.01, 0.1, len(t)) if y is None: y = yerr*np.random.randn(len(t)) trend = PolynomialTrend("trend", order=3) logs = pm.Normal("logs", mu=-5.0, sd=5.0, testval=-5.0) meanrv = pm.Normal("meanrv", mu=0.0, sd=10.0, testval=0.0) dataset = RVDataset("data", t, y, yerr, logs=logs, trend=trend, meanrv=meanrv) logamps = pm.Uniform("logamps", lower=np.log(min_amp), upper=np.log(max_amp), shape=n_planets, testval=np.log([np.clip(peak["amp"], min_amp+1e-2, max_amp-1e-2) for peak in peaks])) planets = [] for i, (peak, name) in enumerate(zip(peaks, string.ascii_lowercase[1:])): logP = pm.Uniform(name + ":logP", lower=np.log(min_period), upper=np.log(max_period), testval=np.log(peak["period"])) logK = pm.Deterministic(name + ":logK", logamps[i]) eccen = pm.Beta(name + ":eccen", alpha=0.867, beta=3.03, testval=peak["eccen"]) omegabase = pm.Uniform(name + ":omegabase", -2*np.pi, 2*np.pi, testval=peak["omega"]) omegavec = pm.Deterministic(name + ":omegavec", tt.stack([tt.cos(omegabase), tt.sin(omegabase)])) phibase = pm.Uniform(name + ":phibase", -2*np.pi, 2*np.pi, testval=peak["phase"]) phivec = pm.Deterministic(name + ":phivec", tt.stack([tt.cos(phibase), tt.sin(phibase)])) planets.append( RVPlanet(name, logP, logK, phivec=phivec, eccen=eccen, omegavec=omegavec)) rvmodel = RVModel("rv", dataset, planets) pm.Deterministic("logp", model.logpt) return rvmodel np.random.seed(42 + version) t = np.sort(np.random.uniform(0.0, 4*365.0, 50)) yerr = np.random.uniform(0.01, 0.1, len(t)) y = yerr * np.random.randn(len(t)) min_period = 5 max_period = 100 min_amp = 0.2 max_amp = 0.8 target_n_eff = 500 peaks = [] for i in range(n_planets): peaks.append(dict( period=np.exp(np.random.uniform(np.log(min_period), np.log(max_period))), amp=np.exp(np.random.uniform(np.log(min_amp), np.log(max_amp))), phase=np.random.uniform(0, 2*np.pi), omega=np.random.uniform(0, 2*np.pi), eccen=np.random.uniform(0.01, 0.3), )) peaks = sorted(peaks, key=lambda x: x["amp"]) with pm.Model() as sim_model: sim_rvmodel = build_model(peaks, t, y, yerr) f = theano.function(sim_model.vars, sim_rvmodel.get_rvmodels(t), on_unused_input="ignore") coords = sim_model.test_point y += np.sum(f(*(coords[k.name] for k in sim_model.vars)), axis=1) fig = plt.figure() plt.errorbar(t % peaks[-1]["period"], y, yerr=yerr, fmt=".k") fig.savefig(os.path.join(dirname, "data.png"), bbox_inches="tight") plt.close(fig) with pm.Model() as model: rvmodel = build_model(peaks, t, y, yerr) key_vars = [v.name for v in rvmodel.datasets[0].vars] key_vars += [p.name + k for p in rvmodel.planets for k in (":logP", ":logK", ":phi", ":eccen", ":omega")] with model: f = theano.function(model.vars, [model.logpt] + model.vars + model.deterministics) def log_prob_func(params): dct = model.bijection.rmap(params) args = (dct[k.name] for k in model.vars) results = f(*args) return tuple(results) res = model.test_point vec = model.bijection.map(res) initial_blobs = log_prob_func(vec)[1:] dtype = [(var.name, float, np.shape(b)) for var, b in zip(model.vars + model.deterministics, initial_blobs)] coords = vec + 1e-5 * np.random.randn(3*len(vec), len(vec)) nwalkers, ndim = coords.shape sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob_func, blobs_dtype=dtype) thin_by = 100 tottime = 0 for i in range(1000): strt = time.time() sampler.run_mcmc(coords, 50, thin_by=thin_by, progress=True) tottime += time.time() - strt samples = sampler.get_blobs() tau = np.array([float(emcee.autocorr.integrated_time(samples[k], tol=0)) for k in key_vars]) print(sampler.iteration * nwalkers / tau) converged = np.all(tau * target_n_eff / thin_by < sampler.iteration * nwalkers) converged &= np.all(sampler.iteration > 50 * tau) if converged: break samples = sampler.get_blobs(discard=int(tau.max())) tau_emcee = np.array([float(emcee.autocorr.integrated_time(samples[k], tol=0)) for k in key_vars]) time_emcee = tottime time_per_emcee = time_emcee / (sampler.iteration * nwalkers) time_ind_emcee = time_per_emcee * tau_emcee with model: start = model.test_point ntune = 2000 samples = sampler.get_chain(discard=int(tau_emcee.max()), flat=True) potential = pm.step_methods.hmc.quadpotential.QuadPotentialFull( np.cov(samples, rowvar=0)) step = pm.NUTS(potential=potential) print("Running burn-in...") burnin = pm.sample(start=start, tune=ntune, draws=1, step=step, chains=1, compute_convergence_checks=False) trace = None next_start = burnin.point(-1) draws = 2000 chains = 2 ntotal = 0 tottime = 0 for i in range(100): strt = time.time() trace = pm.sample(start=next_start, trace=trace, tune=0, draws=draws, step=step, chains=chains, compute_convergence_checks=False, cores=1) tottime += time.time() - strt ntotal += draws * chains next_start = [trace.point(-1, c) for c in trace.chains] tau = np.array([ float(emcee.autocorr.integrated_time(np.array( trace.get_values(v, combine=False)).T, tol=0)) for v in key_vars]) print(tau) print(ntotal / tau) print(pm.summary(trace, varnames=key_vars).n_eff) if (ntotal / tau).min() > target_n_eff and ntotal > tau.max() * 50: break tau_pymc = np.copy(tau) time_pymc = tottime time_per_pymc = time_pymc / (len(trace) * chains) time_ind_pymc = time_per_pymc * tau_pymc print("time per ind. sample, emcee: {0}".format(time_ind_emcee)) print("time per ind. sample, pymc: {0}".format(time_ind_pymc)) print("time per ind. sample, ratio: {0}" .format(time_ind_emcee / time_ind_pymc)) df = pd.DataFrame(dict(zip(key_vars, zip(time_ind_emcee, time_ind_pymc)))) df["method"] = ["emcee", "pymc"] df.to_csv(os.path.join(dirname, "results.csv"), index=False) tau = tau_emcee.max() samples = sampler.get_blobs(flat=True, discard=int(2*tau), thin=int(tau)) df_emcee = pd.DataFrame.from_records(samples[key_vars]) ranges = [(np.min(df_emcee[k]), np.max(df_emcee[k])) for k in df_emcee.columns] df_pymc = pm.trace_to_dataframe(trace, varnames=key_vars) w_pymc = len(df_emcee) / len(df_pymc) + np.zeros(len(df_pymc)) v = key_vars[:15] fig = corner.corner(df_emcee[v], color="C0", range=ranges[:len(v)]) corner.corner(df_pymc[v], weights=w_pymc, color="C1", fig=fig, range=ranges[:len(v)]) fig.savefig(os.path.join(dirname, "corner.png"), bbox_inches="tight") plt.close(fig)
true
true
1c3730954f76b804a76e015b8e69d49472ad3f30
932
py
Python
src/migrations/versions/8f63db3ad7a1_added_project_id_and_nanodegree_id_as_.py
Dev-Nebe/student-hub
fe6718aced065dab4bb8d92372bfe098c1a75137
[ "MIT" ]
3
2020-05-25T19:36:11.000Z
2021-09-15T09:05:57.000Z
src/migrations/versions/8f63db3ad7a1_added_project_id_and_nanodegree_id_as_.py
Dev-Nebe/student-hub
fe6718aced065dab4bb8d92372bfe098c1a75137
[ "MIT" ]
1
2021-04-30T21:11:44.000Z
2021-04-30T21:11:44.000Z
src/migrations/versions/8f63db3ad7a1_added_project_id_and_nanodegree_id_as_.py
Dev-Nebe/student-hub
fe6718aced065dab4bb8d92372bfe098c1a75137
[ "MIT" ]
null
null
null
"""Added project_id and nanodegree_id as indices on the question table Revision ID: 8f63db3ad7a1 Revises: cbcb7906e58d Create Date: 2020-05-21 20:45:11.073358 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8f63db3ad7a1' down_revision = 'cbcb7906e58d' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_index(op.f('ix_question_nanodegree_id'), 'question', ['nanodegree_id'], unique=False) op.create_index(op.f('ix_question_project_id'), 'question', ['project_id'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_question_project_id'), table_name='question') op.drop_index(op.f('ix_question_nanodegree_id'), table_name='question') # ### end Alembic commands ###
30.064516
99
0.722103
from alembic import op import sqlalchemy as sa revision = '8f63db3ad7a1' down_revision = 'cbcb7906e58d' branch_labels = None depends_on = None def upgrade(): unique=False)
true
true
1c373256733877a610ee969ef88496c29dd8a58b
3,865
py
Python
xcube_server/controllers/features.py
bcdev/xcube-server
d6fc4bef26ae1f6929904bad0f920b50ea6974f7
[ "MIT" ]
null
null
null
xcube_server/controllers/features.py
bcdev/xcube-server
d6fc4bef26ae1f6929904bad0f920b50ea6974f7
[ "MIT" ]
null
null
null
xcube_server/controllers/features.py
bcdev/xcube-server
d6fc4bef26ae1f6929904bad0f920b50ea6974f7
[ "MIT" ]
null
null
null
import logging from typing import Any, Dict, List import shapely.geometry import shapely.wkt from shapely.errors import WKTReadingError from ..context import ServiceContext from ..errors import ServiceBadRequestError from ..logtime import log_time from ..utils import get_dataset_geometry, get_box_split_bounds_geometry _LOG = logging.getLogger('xcube') GeoJsonFeatureCollection = Dict GeoJsonFeature = Dict def find_dataset_features(ctx: ServiceContext, collection_name: str, ds_name: str, query_expr: Any = None, comb_op: str = "and") -> GeoJsonFeatureCollection: dataset = ctx.get_dataset(ds_name) query_geometry = get_dataset_geometry(dataset) return _find_features(ctx, collection_name, query_geometry=query_geometry, query_expr=query_expr, comb_op=comb_op) def find_features(ctx: ServiceContext, collection_name: str, box_coords: str = None, geom_wkt: str = None, query_expr: Any = None, geojson_obj: Dict = None, comb_op: str = "and") -> GeoJsonFeatureCollection: query_geometry = None if box_coords: try: query_geometry = get_box_split_bounds_geometry(*[float(s) for s in box_coords.split(",")]) except (TypeError, ValueError) as e: raise ServiceBadRequestError("Received invalid bounding box geometry") from e elif geom_wkt: try: query_geometry = shapely.wkt.loads(geom_wkt) except (TypeError, WKTReadingError) as e: raise ServiceBadRequestError("Received invalid geometry WKT") from e elif geojson_obj: try: if geojson_obj["type"] == "FeatureCollection": query_geometry = shapely.geometry.shape(geojson_obj["features"][0]["geometry"]) elif geojson_obj["type"] == "Feature": query_geometry = shapely.geometry.shape(geojson_obj["geometry"]) else: query_geometry = shapely.geometry.shape(geojson_obj) except (IndexError, ValueError, KeyError) as e: raise ServiceBadRequestError("Received invalid GeoJSON object") from e return _find_features(ctx, collection_name, query_geometry, query_expr, comb_op) def _find_features(ctx: ServiceContext, collection_name: str, query_geometry: shapely.geometry.base.BaseGeometry = None, query_expr: Any = None, comb_op: str = "and") -> GeoJsonFeatureCollection: with log_time() as cm: features = __find_features(ctx, collection_name, query_geometry, query_expr, comb_op) _LOG.info(f"{len(features)} features found within {cm.duration} seconds") return features def __find_features(ctx: ServiceContext, collection_name: str, query_geometry: shapely.geometry.base.BaseGeometry = None, query_expr: Any = None, comb_op: str = "and") -> GeoJsonFeatureCollection: feature_collection = ctx.get_feature_collection(collection_name) if query_geometry is None: if query_expr is None: return feature_collection else: raise NotImplementedError() else: matching_features = [] if query_expr is None: for feature in feature_collection["features"]: geometry = shapely.geometry.shape(feature["geometry"]) if geometry.intersects(query_geometry): matching_features.append(feature) else: raise NotImplementedError() return dict(type="FeatureCollection", features=matching_features)
40.684211
102
0.627943
import logging from typing import Any, Dict, List import shapely.geometry import shapely.wkt from shapely.errors import WKTReadingError from ..context import ServiceContext from ..errors import ServiceBadRequestError from ..logtime import log_time from ..utils import get_dataset_geometry, get_box_split_bounds_geometry _LOG = logging.getLogger('xcube') GeoJsonFeatureCollection = Dict GeoJsonFeature = Dict def find_dataset_features(ctx: ServiceContext, collection_name: str, ds_name: str, query_expr: Any = None, comb_op: str = "and") -> GeoJsonFeatureCollection: dataset = ctx.get_dataset(ds_name) query_geometry = get_dataset_geometry(dataset) return _find_features(ctx, collection_name, query_geometry=query_geometry, query_expr=query_expr, comb_op=comb_op) def find_features(ctx: ServiceContext, collection_name: str, box_coords: str = None, geom_wkt: str = None, query_expr: Any = None, geojson_obj: Dict = None, comb_op: str = "and") -> GeoJsonFeatureCollection: query_geometry = None if box_coords: try: query_geometry = get_box_split_bounds_geometry(*[float(s) for s in box_coords.split(",")]) except (TypeError, ValueError) as e: raise ServiceBadRequestError("Received invalid bounding box geometry") from e elif geom_wkt: try: query_geometry = shapely.wkt.loads(geom_wkt) except (TypeError, WKTReadingError) as e: raise ServiceBadRequestError("Received invalid geometry WKT") from e elif geojson_obj: try: if geojson_obj["type"] == "FeatureCollection": query_geometry = shapely.geometry.shape(geojson_obj["features"][0]["geometry"]) elif geojson_obj["type"] == "Feature": query_geometry = shapely.geometry.shape(geojson_obj["geometry"]) else: query_geometry = shapely.geometry.shape(geojson_obj) except (IndexError, ValueError, KeyError) as e: raise ServiceBadRequestError("Received invalid GeoJSON object") from e return _find_features(ctx, collection_name, query_geometry, query_expr, comb_op) def _find_features(ctx: ServiceContext, collection_name: str, query_geometry: shapely.geometry.base.BaseGeometry = None, query_expr: Any = None, comb_op: str = "and") -> GeoJsonFeatureCollection: with log_time() as cm: features = __find_features(ctx, collection_name, query_geometry, query_expr, comb_op) _LOG.info(f"{len(features)} features found within {cm.duration} seconds") return features def __find_features(ctx: ServiceContext, collection_name: str, query_geometry: shapely.geometry.base.BaseGeometry = None, query_expr: Any = None, comb_op: str = "and") -> GeoJsonFeatureCollection: feature_collection = ctx.get_feature_collection(collection_name) if query_geometry is None: if query_expr is None: return feature_collection else: raise NotImplementedError() else: matching_features = [] if query_expr is None: for feature in feature_collection["features"]: geometry = shapely.geometry.shape(feature["geometry"]) if geometry.intersects(query_geometry): matching_features.append(feature) else: raise NotImplementedError() return dict(type="FeatureCollection", features=matching_features)
true
true
1c3732819a8a0879b9c05357b24f24810fe6f3b3
12,299
py
Python
tests/models/test_model_core.py
mohammadul/tensorlayer
e17e49f03477d524ef688474fe9ddde044ca5cf5
[ "Apache-2.0" ]
null
null
null
tests/models/test_model_core.py
mohammadul/tensorlayer
e17e49f03477d524ef688474fe9ddde044ca5cf5
[ "Apache-2.0" ]
null
null
null
tests/models/test_model_core.py
mohammadul/tensorlayer
e17e49f03477d524ef688474fe9ddde044ca5cf5
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import numpy as np import tensorflow as tf import tensorlayer as tl from tensorlayer.layers import * from tensorlayer.models import * from tests.utils import CustomTestCase def basic_static_model(): ni = Input((None, 24, 24, 3)) nn = Conv2d(16, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, name="conv1")(ni) nn = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool1')(nn) nn = Conv2d(16, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, name="conv2")(nn) nn = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool2')(nn) nn = Flatten(name='flatten')(nn) nn = Dense(100, act=None, name="dense1")(nn) nn = Dense(10, act=None, name="dense2")(nn) M = Model(inputs=ni, outputs=nn) return M class basic_dynamic_model(Model): def __init__(self): super(basic_dynamic_model, self).__init__() self.conv1 = Conv2d(16, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, in_channels=3, name="conv1") self.pool1 = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool1') self.conv2 = Conv2d(16, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, in_channels=16, name="conv2") self.pool2 = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool2') self.flatten = Flatten(name='flatten') self.dense1 = Dense(100, act=None, in_channels=576, name="dense1") self.dense2 = Dense(10, act=None, in_channels=100, name="dense2") def forward(self, x): x = self.conv1(x) x = self.pool1(x) x = self.conv2(x) x = self.pool2(x) x = self.flatten(x) x = self.dense1(x) x = self.dense2(x) return x class Model_Core_Test(CustomTestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_dynamic_basic(self): print('-' * 20, 'test_dynamic_basic', '-' * 20) model_basic = basic_dynamic_model() # test empty model before calling self.assertEqual(model_basic.is_train, None) self.assertEqual(model_basic._weights, None) self.assertEqual(model_basic._inputs, None) self.assertEqual(model_basic._outputs, None) self.assertEqual(model_basic._model_layer, None) self.assertEqual(model_basic._all_layers, None) self.assertEqual(model_basic._nodes_fixed, False) # test layer and weights access all_layers = model_basic.all_layers self.assertEqual(len(model_basic.all_layers), 7) self.assertEqual(model_basic._weights, None) self.assertIsNotNone(model_basic.weights) print([w.name for w in model_basic.weights]) # test model mode model_basic.train() self.assertEqual(model_basic.is_train, True) model_basic.eval() self.assertEqual(model_basic.is_train, False) model_basic.test() self.assertEqual(model_basic.is_train, False) model_basic.infer() self.assertEqual(model_basic.is_train, False) # test as_layer try: model_basic.as_layer() except Exception as e: print(e) self.assertIsNone(model_basic._model_layer) # test print try: print(model_basic) except Exception as e: print(e) # test forwarding inputs = np.random.normal(size=[2, 24, 24, 3]).astype(np.float32) outputs1 = model_basic(inputs) self.assertEqual(model_basic._nodes_fixed, True) self.assertEqual(model_basic.is_train, False) try: outputs2 = model_basic(inputs, is_train=True) except Exception as e: print(e) outputs2 = model_basic(inputs, is_train=False) self.assertEqual(model_basic.is_train, False) self.assertLess(np.max(np.abs(outputs1.numpy() - outputs2.numpy())), 1e-7) # test layer node self.assertEqual(len(model_basic.all_layers[-1]._nodes), 0) self.assertEqual(model_basic.all_layers[-2]._nodes_fixed, True) # test release_memory try: model_basic.release_memory() except Exception as e: print(e) def test_static_basic(self): print('-' * 20, 'test_static_basic', '-' * 20) model_basic = basic_static_model() # test empty model before calling self.assertEqual(model_basic.is_train, None) self.assertEqual(model_basic._weights, None) self.assertIsNotNone(model_basic._inputs) self.assertIsNotNone(model_basic._outputs) self.assertEqual(model_basic._model_layer, None) self.assertIsNotNone(model_basic._all_layers) self.assertIsNotNone(model_basic._nodes_fixed) # test layer and weights access all_layers = model_basic.all_layers self.assertEqual(len(model_basic.all_layers), 8) self.assertEqual(model_basic._weights, None) self.assertIsNotNone(model_basic.weights) print([w.name for w in model_basic.weights]) # test model mode model_basic.train() self.assertEqual(model_basic.is_train, True) model_basic.eval() self.assertEqual(model_basic.is_train, False) model_basic.test() self.assertEqual(model_basic.is_train, False) model_basic.infer() self.assertEqual(model_basic.is_train, False) # test as_layer self.assertIsInstance(model_basic.as_layer(), tl.layers.Layer) self.assertIsNotNone(model_basic._model_layer) # test print try: print(model_basic) except Exception as e: print(e) # test forwarding inputs = np.random.normal(size=[2, 24, 24, 3]).astype(np.float32) outputs1 = model_basic(inputs) self.assertEqual(model_basic._nodes_fixed, True) self.assertEqual(model_basic.is_train, False) try: outputs2 = model_basic(inputs, is_train=True) except Exception as e: print(e) outputs2 = model_basic(inputs, is_train=False) self.assertEqual(model_basic.is_train, False) self.assertLess(np.max(np.abs(outputs1.numpy() - outputs2.numpy())), 1e-7) # test layer node self.assertEqual(len(model_basic.all_layers[-1]._nodes), 1) self.assertEqual(model_basic.all_layers[-2]._nodes_fixed, True) # test release_memory try: model_basic.release_memory() except Exception as e: print(e) def test_deprecated_function(self): print('-' * 20, 'test_deprecated_function', '-' * 20) model = basic_dynamic_model() try: model.print_all_layers() except Exception as e: print(e) try: model.count_params() except Exception as e: print(e) try: model.print_params() except Exception as e: print(e) try: model.all_params() except Exception as e: print(e) try: model.all_drop() except Exception as e: print(e) def test_exceptions(self): print('-' * 20, 'test exceptions', '-' * 20) np_arr = np.random.normal(size=[4, 784]).astype(np.float32) tf_tensor = tf.random.normal(shape=[4, 784]) ni = Input(shape=[4, 784]) try: model = Model(inputs=[], outputs=[]) except Exception as e: self.assertIsInstance(e, ValueError) print(e) try: model = Model(inputs=np_arr, outputs=np_arr + 1) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: model = Model(inputs=[np_arr], outputs=[np_arr + 1]) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: model = Model(inputs=[tf_tensor], outputs=[tf_tensor + 1]) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: model = Model(inputs=tf_tensor, outputs=[tf_tensor + 1]) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: model = Model(inputs=ni, outputs=[tf_tensor + 1]) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: class ill_model(Model): def __init__(self): super(ill_model, self).__init__() self.dense2 = Dense(10, act=None) def forward(self, x): x = self.dense2(x) return x model = ill_model() weights = model.weights except Exception as e: self.assertIsInstance(e, AttributeError) print(e) try: ni = Input([4, 784]) nn = Dense(10)(ni) model = Model(inputs=ni, outputs=nn) outputs = model(np_arr) except Exception as e: self.assertIsInstance(e, ValueError) print(e) try: ni = Input([4, 784]) model = Model(inputs=ni, outputs=ni) model.save_weights('./empty_model.h5') except Exception as e: print(e) try: ni = Input([4, 784]) nn = Dense(10)(ni) model = Model(inputs=ni, outputs=nn) model._outputs = None outputs = model(np_arr, is_train=True) except Exception as e: self.assertIsInstance(e, ValueError) print(e) def test_list_inputs_outputs(self): print('-' * 20, 'test_list_inputs_outputs', '-' * 20) ni_1 = Input(shape=[4, 16]) ni_2 = Input(shape=[4, 32]) a_1 = Dense(80)(ni_1) b_1 = Dense(160)(ni_2) concat = Concat()([a_1, b_1]) a_2 = Dense(10)(concat) b_2 = Dense(20)(concat) model = Model(inputs=[ni_1, ni_2], outputs=[a_2, b_2]) model.train() np_arr1 = np.random.normal(size=[4, 16]).astype(np.float32) np_arr2 = np.random.normal(size=[4, 32]).astype(np.float32) try: outputs = model(np_arr1) except Exception as e: self.assertIsInstance(e, ValueError) print(e) try: outputs = model([np_arr1]) except Exception as e: self.assertIsInstance(e, ValueError) print(e) out_a, out_b = model([np_arr1, np_arr2]) self.assertEqual(out_a.shape, [4, 10]) self.assertEqual(out_b.shape, [4, 20]) def test_special_case(self): print('-' * 20, 'test_special_case', '-' * 20) class my_model(Model): def __init__(self): super(my_model, self).__init__() self.dense = Dense(64, in_channels=3) self.vgg = tl.models.vgg16() def forward(self, x): return x model = my_model() weights = model.weights self.assertGreater(len(weights), 2) print(len(weights)) def test_get_layer(self): print('-' * 20, 'test_get_layer', '-' * 20) model_basic = basic_dynamic_model() self.assertIsInstance(model_basic.get_layer('conv2'), tl.layers.Conv2d) try: model_basic.get_layer('abc') except Exception as e: print(e) try: model_basic.get_layer(index=99) except Exception as e: print(e) model_basic = basic_static_model() self.assertIsInstance(model_basic.get_layer('conv2'), tl.layers.Conv2d) self.assertIsInstance(model_basic.get_layer(index=2), tl.layers.MaxPool2d) print([w.name for w in model_basic.get_layer(index=-1).weights]) try: model_basic.get_layer('abc') except Exception as e: print(e) try: model_basic.get_layer(index=99) except Exception as e: print(e) if __name__ == '__main__': unittest.main()
30.824561
109
0.58086
import os import unittest os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import numpy as np import tensorflow as tf import tensorlayer as tl from tensorlayer.layers import * from tensorlayer.models import * from tests.utils import CustomTestCase def basic_static_model(): ni = Input((None, 24, 24, 3)) nn = Conv2d(16, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, name="conv1")(ni) nn = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool1')(nn) nn = Conv2d(16, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, name="conv2")(nn) nn = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool2')(nn) nn = Flatten(name='flatten')(nn) nn = Dense(100, act=None, name="dense1")(nn) nn = Dense(10, act=None, name="dense2")(nn) M = Model(inputs=ni, outputs=nn) return M class basic_dynamic_model(Model): def __init__(self): super(basic_dynamic_model, self).__init__() self.conv1 = Conv2d(16, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, in_channels=3, name="conv1") self.pool1 = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool1') self.conv2 = Conv2d(16, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, in_channels=16, name="conv2") self.pool2 = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool2') self.flatten = Flatten(name='flatten') self.dense1 = Dense(100, act=None, in_channels=576, name="dense1") self.dense2 = Dense(10, act=None, in_channels=100, name="dense2") def forward(self, x): x = self.conv1(x) x = self.pool1(x) x = self.conv2(x) x = self.pool2(x) x = self.flatten(x) x = self.dense1(x) x = self.dense2(x) return x class Model_Core_Test(CustomTestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def test_dynamic_basic(self): print('-' * 20, 'test_dynamic_basic', '-' * 20) model_basic = basic_dynamic_model() self.assertEqual(model_basic.is_train, None) self.assertEqual(model_basic._weights, None) self.assertEqual(model_basic._inputs, None) self.assertEqual(model_basic._outputs, None) self.assertEqual(model_basic._model_layer, None) self.assertEqual(model_basic._all_layers, None) self.assertEqual(model_basic._nodes_fixed, False) all_layers = model_basic.all_layers self.assertEqual(len(model_basic.all_layers), 7) self.assertEqual(model_basic._weights, None) self.assertIsNotNone(model_basic.weights) print([w.name for w in model_basic.weights]) model_basic.train() self.assertEqual(model_basic.is_train, True) model_basic.eval() self.assertEqual(model_basic.is_train, False) model_basic.test() self.assertEqual(model_basic.is_train, False) model_basic.infer() self.assertEqual(model_basic.is_train, False) try: model_basic.as_layer() except Exception as e: print(e) self.assertIsNone(model_basic._model_layer) try: print(model_basic) except Exception as e: print(e) inputs = np.random.normal(size=[2, 24, 24, 3]).astype(np.float32) outputs1 = model_basic(inputs) self.assertEqual(model_basic._nodes_fixed, True) self.assertEqual(model_basic.is_train, False) try: outputs2 = model_basic(inputs, is_train=True) except Exception as e: print(e) outputs2 = model_basic(inputs, is_train=False) self.assertEqual(model_basic.is_train, False) self.assertLess(np.max(np.abs(outputs1.numpy() - outputs2.numpy())), 1e-7) self.assertEqual(len(model_basic.all_layers[-1]._nodes), 0) self.assertEqual(model_basic.all_layers[-2]._nodes_fixed, True) try: model_basic.release_memory() except Exception as e: print(e) def test_static_basic(self): print('-' * 20, 'test_static_basic', '-' * 20) model_basic = basic_static_model() self.assertEqual(model_basic.is_train, None) self.assertEqual(model_basic._weights, None) self.assertIsNotNone(model_basic._inputs) self.assertIsNotNone(model_basic._outputs) self.assertEqual(model_basic._model_layer, None) self.assertIsNotNone(model_basic._all_layers) self.assertIsNotNone(model_basic._nodes_fixed) all_layers = model_basic.all_layers self.assertEqual(len(model_basic.all_layers), 8) self.assertEqual(model_basic._weights, None) self.assertIsNotNone(model_basic.weights) print([w.name for w in model_basic.weights]) model_basic.train() self.assertEqual(model_basic.is_train, True) model_basic.eval() self.assertEqual(model_basic.is_train, False) model_basic.test() self.assertEqual(model_basic.is_train, False) model_basic.infer() self.assertEqual(model_basic.is_train, False) self.assertIsInstance(model_basic.as_layer(), tl.layers.Layer) self.assertIsNotNone(model_basic._model_layer) try: print(model_basic) except Exception as e: print(e) inputs = np.random.normal(size=[2, 24, 24, 3]).astype(np.float32) outputs1 = model_basic(inputs) self.assertEqual(model_basic._nodes_fixed, True) self.assertEqual(model_basic.is_train, False) try: outputs2 = model_basic(inputs, is_train=True) except Exception as e: print(e) outputs2 = model_basic(inputs, is_train=False) self.assertEqual(model_basic.is_train, False) self.assertLess(np.max(np.abs(outputs1.numpy() - outputs2.numpy())), 1e-7) self.assertEqual(len(model_basic.all_layers[-1]._nodes), 1) self.assertEqual(model_basic.all_layers[-2]._nodes_fixed, True) try: model_basic.release_memory() except Exception as e: print(e) def test_deprecated_function(self): print('-' * 20, 'test_deprecated_function', '-' * 20) model = basic_dynamic_model() try: model.print_all_layers() except Exception as e: print(e) try: model.count_params() except Exception as e: print(e) try: model.print_params() except Exception as e: print(e) try: model.all_params() except Exception as e: print(e) try: model.all_drop() except Exception as e: print(e) def test_exceptions(self): print('-' * 20, 'test exceptions', '-' * 20) np_arr = np.random.normal(size=[4, 784]).astype(np.float32) tf_tensor = tf.random.normal(shape=[4, 784]) ni = Input(shape=[4, 784]) try: model = Model(inputs=[], outputs=[]) except Exception as e: self.assertIsInstance(e, ValueError) print(e) try: model = Model(inputs=np_arr, outputs=np_arr + 1) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: model = Model(inputs=[np_arr], outputs=[np_arr + 1]) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: model = Model(inputs=[tf_tensor], outputs=[tf_tensor + 1]) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: model = Model(inputs=tf_tensor, outputs=[tf_tensor + 1]) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: model = Model(inputs=ni, outputs=[tf_tensor + 1]) except Exception as e: self.assertIsInstance(e, TypeError) print(e) try: class ill_model(Model): def __init__(self): super(ill_model, self).__init__() self.dense2 = Dense(10, act=None) def forward(self, x): x = self.dense2(x) return x model = ill_model() weights = model.weights except Exception as e: self.assertIsInstance(e, AttributeError) print(e) try: ni = Input([4, 784]) nn = Dense(10)(ni) model = Model(inputs=ni, outputs=nn) outputs = model(np_arr) except Exception as e: self.assertIsInstance(e, ValueError) print(e) try: ni = Input([4, 784]) model = Model(inputs=ni, outputs=ni) model.save_weights('./empty_model.h5') except Exception as e: print(e) try: ni = Input([4, 784]) nn = Dense(10)(ni) model = Model(inputs=ni, outputs=nn) model._outputs = None outputs = model(np_arr, is_train=True) except Exception as e: self.assertIsInstance(e, ValueError) print(e) def test_list_inputs_outputs(self): print('-' * 20, 'test_list_inputs_outputs', '-' * 20) ni_1 = Input(shape=[4, 16]) ni_2 = Input(shape=[4, 32]) a_1 = Dense(80)(ni_1) b_1 = Dense(160)(ni_2) concat = Concat()([a_1, b_1]) a_2 = Dense(10)(concat) b_2 = Dense(20)(concat) model = Model(inputs=[ni_1, ni_2], outputs=[a_2, b_2]) model.train() np_arr1 = np.random.normal(size=[4, 16]).astype(np.float32) np_arr2 = np.random.normal(size=[4, 32]).astype(np.float32) try: outputs = model(np_arr1) except Exception as e: self.assertIsInstance(e, ValueError) print(e) try: outputs = model([np_arr1]) except Exception as e: self.assertIsInstance(e, ValueError) print(e) out_a, out_b = model([np_arr1, np_arr2]) self.assertEqual(out_a.shape, [4, 10]) self.assertEqual(out_b.shape, [4, 20]) def test_special_case(self): print('-' * 20, 'test_special_case', '-' * 20) class my_model(Model): def __init__(self): super(my_model, self).__init__() self.dense = Dense(64, in_channels=3) self.vgg = tl.models.vgg16() def forward(self, x): return x model = my_model() weights = model.weights self.assertGreater(len(weights), 2) print(len(weights)) def test_get_layer(self): print('-' * 20, 'test_get_layer', '-' * 20) model_basic = basic_dynamic_model() self.assertIsInstance(model_basic.get_layer('conv2'), tl.layers.Conv2d) try: model_basic.get_layer('abc') except Exception as e: print(e) try: model_basic.get_layer(index=99) except Exception as e: print(e) model_basic = basic_static_model() self.assertIsInstance(model_basic.get_layer('conv2'), tl.layers.Conv2d) self.assertIsInstance(model_basic.get_layer(index=2), tl.layers.MaxPool2d) print([w.name for w in model_basic.get_layer(index=-1).weights]) try: model_basic.get_layer('abc') except Exception as e: print(e) try: model_basic.get_layer(index=99) except Exception as e: print(e) if __name__ == '__main__': unittest.main()
true
true
1c3733713646a167c06cd428aed5d8d22838b7c9
15,437
py
Python
experiment_variable_number_of_objects/theoritical_model_bag_of_words.py
gaetanmargueritte/ccg2esn
3745ef23eb409837d20261045fad808af5ab82a8
[ "CC0-1.0" ]
3
2020-11-24T09:53:26.000Z
2021-03-24T16:43:28.000Z
experiment_variable_number_of_objects/theoritical_model_bag_of_words.py
gaetanmargueritte/ccg2esn
3745ef23eb409837d20261045fad808af5ab82a8
[ "CC0-1.0" ]
null
null
null
experiment_variable_number_of_objects/theoritical_model_bag_of_words.py
gaetanmargueritte/ccg2esn
3745ef23eb409837d20261045fad808af5ab82a8
[ "CC0-1.0" ]
1
2020-09-04T14:38:31.000Z
2020-09-04T14:38:31.000Z
import os import sys sys.path.append(r'..') from sentence_to_predicate import WordPredicate import json import sentence_grounding_test_parameters as param import numpy as np from recognized_object import RecognizedObject from plots import * import time import matplotlib.pyplot as plt import math def caracteristics_to_output_teacher(object_lists, concept_to_output_id_dict, output_size, nb_concepts): """ Transforms a list of caracteristics into a teacher numpy vector """ targeted_output = np.zeros(output_size) for i, obj in enumerate(object_lists): offset = i * nb_concepts for j, concept in enumerate(obj): if concept is None: continue concept_id = offset + concept_to_output_id_dict[concept] targeted_output[concept_id] = 1. return targeted_output def random_sentence_and_predicates(): """ Returns a ranodm sentence and predicates it contains. 50% of the sentences concern one object only, 50% two. """ nb_sentences = len(param.SENTENCE_TO_PREDICATE.items()) rand_sentence_id_1 = np.random.choice(nb_sentences) sentence_1, predicate_1 = param.SENTENCE_TO_PREDICATE.items()[rand_sentence_id_1] if np.random.rand() < 0.5: rand_sentence_id_2 = np.random.choice(nb_sentences) sentence_2, predicate_2 = param.SENTENCE_TO_PREDICATE.items()[rand_sentence_id_2] sentence = sentence_1 + ' and ' + sentence_2 else: sentence = sentence_1 predicate_2 = None predicates = [predicate_1, predicate_2] return sentence, predicates def random_recognized_object(category_choices = param.CATEGORIES, position_choices = param.POSITIONS, color_choices = param.COLORS): """ Returns a random object. One half of the time, an empty object is returned. """ if np.random.rand() < 0.5: random_category = np.random.choice(category_choices) random_position = np.random.choice(position_choices) random_color = np.random.choice(color_choices) return RecognizedObject(random_category, random_position, random_color) return RecognizedObject(None, None, None) def random_object(category_choices = None, position_choices = None, color_choices = None): if category_choices is None: category_choices = param.CATEGORIES position_choices = param.POSITIONS color_choices = param.COLORS if np.random.rand() < 0.5: return [np.random.choice(category_choices), np.random.choice(position_choices), np.random.choice(color_choices)] else: return [None, None, None] def possible_recognized_object_for_predicate(predicate, fill_unkown_fields = True): """ From a predicate using words from sentence, returns an object from vision module corresponding to the situation described by the predicate (in french), using grounded concept (in english) """ if predicate is None: if fill_unkown_fields: return random_recognized_object() return RecognizedObject(None, None, None) if fill_unkown_fields: default_category = np.random.choice(param.CATEGORIES) default_position = np.random.choice(param.POSITIONS) default_color = np.random.choice(param.COLORS) else: default_category = None default_position = None default_color = None seen_category = default_category seen_position = default_position seen_color = default_color seen_category = param.OBJ_NAME_TO_CONCEPT.get(predicate.object, default_category) seen_position = param.POSITION_NAME_TO_CONCEPT.get(predicate.action, default_position) seen_color = param.COLOR_NAME_TO_CONCEPT.get(predicate.color, default_color) return RecognizedObject(seen_category, seen_position, seen_color) def possible_categories_for_predicate(predicate, fill_unkown_fields = True): """ From a predicate using words from sentence, returns an object from vision module corresponding to the situation described by the predicate (in french), using grounded concept (in english) """ if predicate is None: if fill_unkown_fields: return random_object() return [None, None, None] if fill_unkown_fields: default_category = np.random.choice(param.CATEGORIES) default_position = np.random.choice(param.POSITIONS) default_color = np.random.choice(param.COLORS) else: default_category = None default_position = None default_color = None seen_category = param.OBJ_NAME_TO_CONCEPT.get(predicate.object, default_category) seen_position = param.POSITION_NAME_TO_CONCEPT.get(predicate.action, default_position) seen_color = param.COLOR_NAME_TO_CONCEPT.get(predicate.color, default_color) return [seen_category, seen_position, seen_color] def sentence_to_pred(sentence, sent_to_role): clauses = sentence.split(" and ") predicates = [] if len(clauses) == 1: predicates.append(WordPredicate(clauses[0], sent_to_role[clauses[0]])) predicates.append(WordPredicate(None, None)) else: for i in range(len(clauses)): predicates.append(WordPredicate(clauses[i], sent_to_role[clauses[i]])) return predicates def softmax(x, beta = 1.): y = np.exp(beta * (x - np.max(x))) return y / np.sum(y) def is_a_valid_imagined_object(predicate, imagined_object): """ Returns whether the predicate description could apply to the imagine_object. Inputs: predicate: WordPredicate instance imagined_object: RecognizedObject instance """ target = possible_recognized_object_for_predicate(predicate, fill_unkown_fields = False) for field in ['category', 'position', 'color']: wanted_field = getattr(target, field) if wanted_field is not None and getattr(imagined_object, field) != wanted_field: return False return True def is_a_valid_representation(predicates, imagined_objects): """ Returns whether each predicate description could apply to its corresponding imagined_object. Inputs: predicates: a list of WordPredicate instances imagined_objects: a list of RecognizedObject instance """ return all(map(is_a_valid_imagined_object, predicates, imagined_objects)) def is_an_exact_imagined_object(predicate, imagined_object): """ Returns whether the imagined object matches exactly what the predicate describes. Inputs: predicate: WordPredicate instance imagined_object: RecognizedObject instance """ target = possible_recognized_object_for_predicate(predicate, fill_unkown_fields = False) for field in ['category', 'position', 'color']: if getattr(imagined_object, field) != getattr(target, field): return False return True def is_an_exact_representation(predicates, imagined_objects): """ Returns whether the imagined object matches exactly what the predicate describes. Inputs: predicates: a list of WordPredicate instances imagined_objects: a list of RecognizedObject instance """ return all(map(is_an_exact_imagined_object, predicates, imagined_objects)) def sentence_to_output_teacher_vector(sentence, sent_to_role, concept_to_output_id_dict, nb_concepts): ## sentences (str) -> list of predicate (WordPredicate) -> list of RecognizedObject -> list of categrories list -> input vector clauses = sentence.split(" and ") predicates = [] if len(clauses) == 1: predicates.append(WordPredicate(clauses[0], sent_to_role[clauses[0]])) predicates.append(None) else: for i in range(len(clauses)): predicates.append(WordPredicate(clauses[i], sent_to_role[clauses[i]])) obj_list = list(map(possible_categories_for_predicate, predicates)) #print("sentence : ", sentence, "obj list: ",obj_list) #the output size is 2*nb_cocpets because it can only be up to 2 objects per clause return caracteristics_to_output_teacher(obj_list, concept_to_output_id_dict, 2*nb_concepts, nb_concepts) def output_to_vision(output, nb_concepts, factor): global concepts_delimitations global output_id_to_concept_dict objs = [] nb_objects = 2 for j in range(nb_objects): cat = [None] * 3 offset = j*nb_concepts for i in range(len(concepts_delimitations)): cat_activations = output[offset+concepts_delimitations[i][0]:offset+concepts_delimitations[i][1]] #print(output_id_to_concept_dict[i], cat_activations, output, concepts_delimitations) proba = softmax(cat_activations) #print(proba) concept = np.argmax(proba) #the threshold to be accepted depend on the number of concept to choose from : must be a factor higher than the uniform proba threshold = factor / (concepts_delimitations[i][1] - concepts_delimitations[i][0]) if proba[concept] < threshold: cat[i] = None else: cat[i] = output_id_to_concept_dict[concepts_delimitations[i][0] + concept] objs.append(RecognizedObject(cat[0], cat[1], cat[2])) #object, position, color return objs ## Bag of word model def test_th_model_on_test_set(test_sentences, verbose): global nb_concepts, sent_to_role, concepts_delimitations, output_id_to_concept_dict test_outputs = [] exact = 0 valid = 0 for i in range(len(test_sentences)): v = output_to_vision(bag_of_word_test(test_sentences[i]),nb_concepts, 1.3) pred = sentence_to_pred(test_sentences[i], sent_to_role) if is_an_exact_representation(pred, v): exact +=1 if is_a_valid_representation(pred, v): valid +=1 nb_sample = len(test_sentences) if verbose: print("Valid representations : ", valid,"/", nb_sample) print("Exact representations : ", exact,"/", nb_sample) return 1-valid/nb_sample, 1-exact/nb_sample memory = {} def filter_sentence(s): """Split s in two clauses and keep only key words""" sem_words = list(set(param.COLOR_NAMES + param.POSITION_NAMES + param.OBJECT_NAMES)) clauses = s.split(" and ") clauses = [c.split(" ") for c in clauses] filtered_clauses = [] for c in clauses: filt_clause = [] for w in c: if w in sem_words: filt_clause.append(w) filt_clause.sort() filtered_clauses.append(str(filt_clause)) return filtered_clauses def bag_of_word_model_train(s, teacher_vect): """Keep the association bewteen the key words in s and the output in memory.""" global memory, nb_concepts clauses = filter_sentence(s) for i in range(len(clauses)): memory[clauses[i]] = teacher_vect[i*nb_concepts: i*nb_concepts+nb_concepts] def bag_of_word_test(s): """Return the output kept in memory if key words in s has been seen else a null vector""" global memory, nb_concepts f = filter_sentence(s) output = [] for i in range(2): if i >= len(f): output.append(np.zeros(nb_concepts)) else: c = f[i] if c in memory: output.append(memory[c]) else: output.append(np.zeros(nb_concepts)) return np.concatenate(output) def train_and_test_bag_of_word(nb_object): global nb_concepts, sent_to_role, concepts_delimitations, output_id_to_concept_dict, memory, output_size #Prepropreccingand data generation param.create_dataset(nb_objects = nb_object) sent_to_role = param.SENTENCE_TO_ROLES sentences_one_object = list(sent_to_role.keys()) sentences_two_objects = [] concepts = param.CATEGORIES + param.POSITIONS + param.COLORS concepts_delimitations = [(0,len(param.CATEGORIES)), (len(param.CATEGORIES), len(param.CATEGORIES) + len(param.POSITIONS)), (len(param.CATEGORIES) + len(param.POSITIONS), len(param.CATEGORIES) + len(param.POSITIONS)+ len(param.COLORS))] nb_concepts = len(concepts) output_size = 2*nb_concepts concept_to_output_id_dict = {} output_id_to_concept_dict = {} for i,c in enumerate(concepts): concept_to_output_id_dict[c] = i output_id_to_concept_dict[i] = c np.random.shuffle(sentences_one_object) train_one_obj = 300 train_two_objs = 700 test_one_obj = 300 test_two_objs = 700 valid_ers = [] exact_ers = [] for j in range(10): memory = {} train_sentences = set(sentences_one_object[:train_one_obj]) for i in range(train_two_objs): s1 = np.random.choice(sentences_one_object) s2 = np.random.choice(sentences_one_object) train_sentences.add( s1 + " and "+ s2 ) test_sentences = set(sentences_one_object[-test_one_obj:]) for i in range(test_two_objs): s1 = np.random.choice(sentences_one_object) s2 = np.random.choice(sentences_one_object) s = s1 + " and "+ s2 if not(s in train_sentences): test_sentences.add(s) test_sentences = list(test_sentences) train_sentences = list(train_sentences) if j ==5: print("Number of possible sentences:", len(sentences_one_object)**2 + len(sentences_one_object)) trainY = np.array([sentence_to_output_teacher_vector(s, sent_to_role, concept_to_output_id_dict, nb_concepts) for s in train_sentences]) testY = np.array([sentence_to_output_teacher_vector(s, sent_to_role, concept_to_output_id_dict, nb_concepts) for s in test_sentences]) ##th model training for i in range(len(train_sentences)): bag_of_word_model_train(train_sentences[i], trainY[i]) ##th model testing valid_er, exact_er = test_th_model_on_test_set(test_sentences, False) exact_ers.append(exact_er) valid_ers.append(valid_er) return np.mean(valid_ers), np.mean(exact_ers) with open("mean_perf_bag_of_words.txt", "a") as f: f.write("Nb of objects, Valid error, Exact error\n") #test the bag of word model for several number of objects for nb in range(3,51): print(nb, "objects:") v, e = train_and_test_bag_of_word(nb) print("Valid error:", np.round(v,4)) print("Exact error:", np.round(e,4)) with open("mean_perf_bag_of_words.txt", "a") as f: f.write(str(nb) + ","+str(v) + "," + str(e) + "\n") print("-----------------------------------")
31.312373
145
0.65194
import os import sys sys.path.append(r'..') from sentence_to_predicate import WordPredicate import json import sentence_grounding_test_parameters as param import numpy as np from recognized_object import RecognizedObject from plots import * import time import matplotlib.pyplot as plt import math def caracteristics_to_output_teacher(object_lists, concept_to_output_id_dict, output_size, nb_concepts): targeted_output = np.zeros(output_size) for i, obj in enumerate(object_lists): offset = i * nb_concepts for j, concept in enumerate(obj): if concept is None: continue concept_id = offset + concept_to_output_id_dict[concept] targeted_output[concept_id] = 1. return targeted_output def random_sentence_and_predicates(): nb_sentences = len(param.SENTENCE_TO_PREDICATE.items()) rand_sentence_id_1 = np.random.choice(nb_sentences) sentence_1, predicate_1 = param.SENTENCE_TO_PREDICATE.items()[rand_sentence_id_1] if np.random.rand() < 0.5: rand_sentence_id_2 = np.random.choice(nb_sentences) sentence_2, predicate_2 = param.SENTENCE_TO_PREDICATE.items()[rand_sentence_id_2] sentence = sentence_1 + ' and ' + sentence_2 else: sentence = sentence_1 predicate_2 = None predicates = [predicate_1, predicate_2] return sentence, predicates def random_recognized_object(category_choices = param.CATEGORIES, position_choices = param.POSITIONS, color_choices = param.COLORS): if np.random.rand() < 0.5: random_category = np.random.choice(category_choices) random_position = np.random.choice(position_choices) random_color = np.random.choice(color_choices) return RecognizedObject(random_category, random_position, random_color) return RecognizedObject(None, None, None) def random_object(category_choices = None, position_choices = None, color_choices = None): if category_choices is None: category_choices = param.CATEGORIES position_choices = param.POSITIONS color_choices = param.COLORS if np.random.rand() < 0.5: return [np.random.choice(category_choices), np.random.choice(position_choices), np.random.choice(color_choices)] else: return [None, None, None] def possible_recognized_object_for_predicate(predicate, fill_unkown_fields = True): if predicate is None: if fill_unkown_fields: return random_recognized_object() return RecognizedObject(None, None, None) if fill_unkown_fields: default_category = np.random.choice(param.CATEGORIES) default_position = np.random.choice(param.POSITIONS) default_color = np.random.choice(param.COLORS) else: default_category = None default_position = None default_color = None seen_category = default_category seen_position = default_position seen_color = default_color seen_category = param.OBJ_NAME_TO_CONCEPT.get(predicate.object, default_category) seen_position = param.POSITION_NAME_TO_CONCEPT.get(predicate.action, default_position) seen_color = param.COLOR_NAME_TO_CONCEPT.get(predicate.color, default_color) return RecognizedObject(seen_category, seen_position, seen_color) def possible_categories_for_predicate(predicate, fill_unkown_fields = True): if predicate is None: if fill_unkown_fields: return random_object() return [None, None, None] if fill_unkown_fields: default_category = np.random.choice(param.CATEGORIES) default_position = np.random.choice(param.POSITIONS) default_color = np.random.choice(param.COLORS) else: default_category = None default_position = None default_color = None seen_category = param.OBJ_NAME_TO_CONCEPT.get(predicate.object, default_category) seen_position = param.POSITION_NAME_TO_CONCEPT.get(predicate.action, default_position) seen_color = param.COLOR_NAME_TO_CONCEPT.get(predicate.color, default_color) return [seen_category, seen_position, seen_color] def sentence_to_pred(sentence, sent_to_role): clauses = sentence.split(" and ") predicates = [] if len(clauses) == 1: predicates.append(WordPredicate(clauses[0], sent_to_role[clauses[0]])) predicates.append(WordPredicate(None, None)) else: for i in range(len(clauses)): predicates.append(WordPredicate(clauses[i], sent_to_role[clauses[i]])) return predicates def softmax(x, beta = 1.): y = np.exp(beta * (x - np.max(x))) return y / np.sum(y) def is_a_valid_imagined_object(predicate, imagined_object): target = possible_recognized_object_for_predicate(predicate, fill_unkown_fields = False) for field in ['category', 'position', 'color']: wanted_field = getattr(target, field) if wanted_field is not None and getattr(imagined_object, field) != wanted_field: return False return True def is_a_valid_representation(predicates, imagined_objects): return all(map(is_a_valid_imagined_object, predicates, imagined_objects)) def is_an_exact_imagined_object(predicate, imagined_object): target = possible_recognized_object_for_predicate(predicate, fill_unkown_fields = False) for field in ['category', 'position', 'color']: if getattr(imagined_object, field) != getattr(target, field): return False return True def is_an_exact_representation(predicates, imagined_objects): return all(map(is_an_exact_imagined_object, predicates, imagined_objects)) def sentence_to_output_teacher_vector(sentence, sent_to_role, concept_to_output_id_dict, nb_concepts): te(clauses[0], sent_to_role[clauses[0]])) predicates.append(None) else: for i in range(len(clauses)): predicates.append(WordPredicate(clauses[i], sent_to_role[clauses[i]])) obj_list = list(map(possible_categories_for_predicate, predicates)) return caracteristics_to_output_teacher(obj_list, concept_to_output_id_dict, 2*nb_concepts, nb_concepts) def output_to_vision(output, nb_concepts, factor): global concepts_delimitations global output_id_to_concept_dict objs = [] nb_objects = 2 for j in range(nb_objects): cat = [None] * 3 offset = j*nb_concepts for i in range(len(concepts_delimitations)): cat_activations = output[offset+concepts_delimitations[i][0]:offset+concepts_delimitations[i][1]] proba = softmax(cat_activations) concept = np.argmax(proba) threshold = factor / (concepts_delimitations[i][1] - concepts_delimitations[i][0]) if proba[concept] < threshold: cat[i] = None else: cat[i] = output_id_to_concept_dict[concepts_delimitations[i][0] + concept] objs.append(RecognizedObject(cat[0], cat[1], cat[2])) return objs odel_on_test_set(test_sentences, verbose): global nb_concepts, sent_to_role, concepts_delimitations, output_id_to_concept_dict test_outputs = [] exact = 0 valid = 0 for i in range(len(test_sentences)): v = output_to_vision(bag_of_word_test(test_sentences[i]),nb_concepts, 1.3) pred = sentence_to_pred(test_sentences[i], sent_to_role) if is_an_exact_representation(pred, v): exact +=1 if is_a_valid_representation(pred, v): valid +=1 nb_sample = len(test_sentences) if verbose: print("Valid representations : ", valid,"/", nb_sample) print("Exact representations : ", exact,"/", nb_sample) return 1-valid/nb_sample, 1-exact/nb_sample memory = {} def filter_sentence(s): sem_words = list(set(param.COLOR_NAMES + param.POSITION_NAMES + param.OBJECT_NAMES)) clauses = s.split(" and ") clauses = [c.split(" ") for c in clauses] filtered_clauses = [] for c in clauses: filt_clause = [] for w in c: if w in sem_words: filt_clause.append(w) filt_clause.sort() filtered_clauses.append(str(filt_clause)) return filtered_clauses def bag_of_word_model_train(s, teacher_vect): global memory, nb_concepts clauses = filter_sentence(s) for i in range(len(clauses)): memory[clauses[i]] = teacher_vect[i*nb_concepts: i*nb_concepts+nb_concepts] def bag_of_word_test(s): global memory, nb_concepts f = filter_sentence(s) output = [] for i in range(2): if i >= len(f): output.append(np.zeros(nb_concepts)) else: c = f[i] if c in memory: output.append(memory[c]) else: output.append(np.zeros(nb_concepts)) return np.concatenate(output) def train_and_test_bag_of_word(nb_object): global nb_concepts, sent_to_role, concepts_delimitations, output_id_to_concept_dict, memory, output_size param.create_dataset(nb_objects = nb_object) sent_to_role = param.SENTENCE_TO_ROLES sentences_one_object = list(sent_to_role.keys()) sentences_two_objects = [] concepts = param.CATEGORIES + param.POSITIONS + param.COLORS concepts_delimitations = [(0,len(param.CATEGORIES)), (len(param.CATEGORIES), len(param.CATEGORIES) + len(param.POSITIONS)), (len(param.CATEGORIES) + len(param.POSITIONS), len(param.CATEGORIES) + len(param.POSITIONS)+ len(param.COLORS))] nb_concepts = len(concepts) output_size = 2*nb_concepts concept_to_output_id_dict = {} output_id_to_concept_dict = {} for i,c in enumerate(concepts): concept_to_output_id_dict[c] = i output_id_to_concept_dict[i] = c np.random.shuffle(sentences_one_object) train_one_obj = 300 train_two_objs = 700 test_one_obj = 300 test_two_objs = 700 valid_ers = [] exact_ers = [] for j in range(10): memory = {} train_sentences = set(sentences_one_object[:train_one_obj]) for i in range(train_two_objs): s1 = np.random.choice(sentences_one_object) s2 = np.random.choice(sentences_one_object) train_sentences.add( s1 + " and "+ s2 ) test_sentences = set(sentences_one_object[-test_one_obj:]) for i in range(test_two_objs): s1 = np.random.choice(sentences_one_object) s2 = np.random.choice(sentences_one_object) s = s1 + " and "+ s2 if not(s in train_sentences): test_sentences.add(s) test_sentences = list(test_sentences) train_sentences = list(train_sentences) if j ==5: print("Number of possible sentences:", len(sentences_one_object)**2 + len(sentences_one_object)) trainY = np.array([sentence_to_output_teacher_vector(s, sent_to_role, concept_to_output_id_dict, nb_concepts) for s in train_sentences]) testY = np.array([sentence_to_output_teacher_vector(s, sent_to_role, concept_to_output_id_dict, nb_concepts) for s in test_sentences]) range(len(train_sentences)): bag_of_word_model_train(train_sentences[i], trainY[i]) r, exact_er = test_th_model_on_test_set(test_sentences, False) exact_ers.append(exact_er) valid_ers.append(valid_er) return np.mean(valid_ers), np.mean(exact_ers) with open("mean_perf_bag_of_words.txt", "a") as f: f.write("Nb of objects, Valid error, Exact error\n") for nb in range(3,51): print(nb, "objects:") v, e = train_and_test_bag_of_word(nb) print("Valid error:", np.round(v,4)) print("Exact error:", np.round(e,4)) with open("mean_perf_bag_of_words.txt", "a") as f: f.write(str(nb) + ","+str(v) + "," + str(e) + "\n") print("-----------------------------------")
true
true
1c3735ee86de43d9e7b5d9048eaa51889f53405d
1,074
py
Python
examples/vl6180x_simpletest.py
caternuson/Adafruit_CircuitPython_VL6180X
74a7a7feccb6219e0e74dc31679242035743dda1
[ "MIT" ]
null
null
null
examples/vl6180x_simpletest.py
caternuson/Adafruit_CircuitPython_VL6180X
74a7a7feccb6219e0e74dc31679242035743dda1
[ "MIT" ]
null
null
null
examples/vl6180x_simpletest.py
caternuson/Adafruit_CircuitPython_VL6180X
74a7a7feccb6219e0e74dc31679242035743dda1
[ "MIT" ]
null
null
null
# Demo of reading the range and lux from the VL6180x distance sensor and # printing it every second. # Author: Tony DiCola import time import board import busio import adafruit_vl6180x # Create I2C bus. i2c = busio.I2C(board.SCL, board.SDA) # Create sensor instance. sensor = adafruit_vl6180x.VL6180X(i2c) # Main loop prints the range and lux every second: while True: # Read the range in millimeters and print it. range_mm = sensor.range print('Range: {0}mm'.format(range_mm)) # Read the light, note this requires specifying a gain value: # - adafruit_vl6180x.ALS_GAIN_1 = 1x # - adafruit_vl6180x.ALS_GAIN_1_25 = 1.25x # - adafruit_vl6180x.ALS_GAIN_1_67 = 1.67x # - adafruit_vl6180x.ALS_GAIN_2_5 = 2.5x # - adafruit_vl6180x.ALS_GAIN_5 = 5x # - adafruit_vl6180x.ALS_GAIN_10 = 10x # - adafruit_vl6180x.ALS_GAIN_20 = 20x # - adafruit_vl6180x.ALS_GAIN_40 = 40x light_lux = sensor.read_lux(adafruit_vl6180x.ALS_GAIN_1) print('Light (1x gain): {0}lux'.format(light_lux)) # Delay for a second. time.sleep(1.0)
29.833333
72
0.716946
import time import board import busio import adafruit_vl6180x i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_vl6180x.VL6180X(i2c) while True: range_mm = sensor.range print('Range: {0}mm'.format(range_mm)) light_lux = sensor.read_lux(adafruit_vl6180x.ALS_GAIN_1) print('Light (1x gain): {0}lux'.format(light_lux)) time.sleep(1.0)
true
true
1c3736d3994d409ca62d707988d89ce6ffada63b
5,915
py
Python
snnpytorch/test/test_spike_raster.py
BorthakurAyon/snnpytorch
212eea2d7cd80d9ebc709cc334ca28d165fc2861
[ "MIT" ]
null
null
null
snnpytorch/test/test_spike_raster.py
BorthakurAyon/snnpytorch
212eea2d7cd80d9ebc709cc334ca28d165fc2861
[ "MIT" ]
null
null
null
snnpytorch/test/test_spike_raster.py
BorthakurAyon/snnpytorch
212eea2d7cd80d9ebc709cc334ca28d165fc2861
[ "MIT" ]
1
2021-07-15T14:51:58.000Z
2021-07-15T14:51:58.000Z
""" Test and Plot Spike Raster =========================== """ from snnpytorch.network.spiking_neural_network import SNN from snnpytorch.dataset.spike_raster import SpikeRaster from time import time as t from torch.utils import data from tqdm import tqdm from pathlib import Path import matplotlib.pyplot as plt import numpy as np import argparse import torch import os class Pipeline(object): """ Class for testing the network and plotting spike raster """ def __init__(self): self.num_steps = None self.num_input_neurons = None self.num_output_neurons = None self.conn_prob = None self.device = None def parse_cmd(self) -> None: """ Parse command line inputs and update the model """ parser = argparse.ArgumentParser() parser.add_argument("--num_steps", type=int, default=200) parser.add_argument("--num_input_neurons", type=int, default=10) parser.add_argument("--num_output_neurons", type=int, default=100) parser.add_argument("--conn_prob", type=float, default=0.5) args = parser.parse_args() self.num_steps = args.num_steps self.num_input_neurons = args.num_input_neurons self.num_output_neurons = args.num_output_neurons self.conn_prob = args.conn_prob use_cuda = torch.cuda.is_available() self.device = torch.device("cuda:0" if use_cuda else "cpu") def gen_input_spike_raster(self) -> None: """ Generate and save input spike raster. """ input_data = np.zeros((self.num_steps, self.num_input_neurons)) expectation = 5 num_spikes_per_neuron = int(self.num_steps / expectation) # Make the spike data for input_neuron in range(self.num_input_neurons): isi = np.random.poisson(expectation, num_spikes_per_neuron) spike_times = np.cumsum(isi) input_data[ spike_times[spike_times < self.num_steps], input_neuron] = 1 # Save the data for later use by dataloader file_name = Path.cwd() / 'snnpytorch' / 'data' / 'input_data.pt' torch.save(input_data, file_name) def load_dataset(self) -> torch.Tensor: """ Load spike data for time points using torch dataloader\n :return: Input spike data for a single time point """ # Parameters params = {'shuffle': False, 'batch_size': 1 } file_name = Path.cwd() / 'snnpytorch' / 'data' / 'input_data.pt' # Generators input_data = SpikeRaster(fname=file_name) input_data_generator = data.DataLoader(input_data, **params) return input_data_generator def run(self) -> (torch.Tensor, torch.Tensor): """ Run the simulation for the defined number of steps.\n :return: input spike raster, output spike raster """ output_spikes = [] input_spikes = [] # Update parameters as specified from command line self.parse_cmd() # Generate input spike raster ( self.num_steps, self.num_input_neurons ) self.gen_input_spike_raster() # Load dataset input_data_generator = self.load_dataset() # Create spiking neuron model model = SNN(num_input_neurons=self.num_input_neurons, num_output_neurons=self.num_output_neurons, conn_prob=self.conn_prob) model.to(self.device) start = t() print("\nProgress: ""(%.4f seconds)" % (t() - start)) progress = tqdm(total=len(input_data_generator)) for local_data in input_data_generator: # Transfer data to GPU / CPU local_data = local_data.to(self.device).float() with torch.no_grad(): # No learning in the model input_spikes.append(local_data.tolist()[0]) # batch size=1 # Update model with the data and store the spike outputs output_spikes.append(model.forward(local_data).tolist()[0]) progress.update(1) progress.close() return torch.tensor(input_spikes), torch.tensor(output_spikes) def plot_simulation_results(self, input_spike_data: torch.Tensor, output_spike_data: torch.Tensor) -> None: """ Plot input and output spike raster.\n :param input_spike_data: Input spike raster :param output_spike_data: Output spike raster """ fig, ax = plt.subplots(1, 2) # Input spike raster plot ax[0].scatter(*torch.where(input_spike_data), color='k') ax[0].set_xlim([0, self.num_steps]) ax[0].set_ylabel(" Number of input channels (M) ") ax[0].set_xlabel(" Number of time points (T) ") ax[0].set_title(" Spike raster plot ") # Output spike raster plot ax[1].scatter(*torch.where(output_spike_data), color='r') ax[1].set_xlim([0, self.num_steps]) ax[1].set_xlabel(" Number of time points (T) ") ax[1].set_ylabel(" Number of output neurons (N) ") ax[1].set_title(" Spike raster plot ") # plot if display is available have_display = bool(os.environ.get('DISPLAY', None)) if have_display: plt.show() filename = Path.cwd() / 'snnpytorch' / 'data' / \ 'input_output_spike_raster.png' plt.savefig(filename) else: filename = Path.cwd() / 'snnpytorch' / 'data' / \ 'input_output_spike_raster.png' plt.savefig(filename) if __name__ == "__main__": pipeline = Pipeline() input_spikes, output_spikes = pipeline.run() # Plot raster if device display is available pipeline.plot_simulation_results(input_spikes, output_spikes) print("End of simulation")
32.5
80
0.617413
from snnpytorch.network.spiking_neural_network import SNN from snnpytorch.dataset.spike_raster import SpikeRaster from time import time as t from torch.utils import data from tqdm import tqdm from pathlib import Path import matplotlib.pyplot as plt import numpy as np import argparse import torch import os class Pipeline(object): def __init__(self): self.num_steps = None self.num_input_neurons = None self.num_output_neurons = None self.conn_prob = None self.device = None def parse_cmd(self) -> None: parser = argparse.ArgumentParser() parser.add_argument("--num_steps", type=int, default=200) parser.add_argument("--num_input_neurons", type=int, default=10) parser.add_argument("--num_output_neurons", type=int, default=100) parser.add_argument("--conn_prob", type=float, default=0.5) args = parser.parse_args() self.num_steps = args.num_steps self.num_input_neurons = args.num_input_neurons self.num_output_neurons = args.num_output_neurons self.conn_prob = args.conn_prob use_cuda = torch.cuda.is_available() self.device = torch.device("cuda:0" if use_cuda else "cpu") def gen_input_spike_raster(self) -> None: input_data = np.zeros((self.num_steps, self.num_input_neurons)) expectation = 5 num_spikes_per_neuron = int(self.num_steps / expectation) for input_neuron in range(self.num_input_neurons): isi = np.random.poisson(expectation, num_spikes_per_neuron) spike_times = np.cumsum(isi) input_data[ spike_times[spike_times < self.num_steps], input_neuron] = 1 file_name = Path.cwd() / 'snnpytorch' / 'data' / 'input_data.pt' torch.save(input_data, file_name) def load_dataset(self) -> torch.Tensor: params = {'shuffle': False, 'batch_size': 1 } file_name = Path.cwd() / 'snnpytorch' / 'data' / 'input_data.pt' input_data = SpikeRaster(fname=file_name) input_data_generator = data.DataLoader(input_data, **params) return input_data_generator def run(self) -> (torch.Tensor, torch.Tensor): output_spikes = [] input_spikes = [] self.parse_cmd() self.gen_input_spike_raster() input_data_generator = self.load_dataset() model = SNN(num_input_neurons=self.num_input_neurons, num_output_neurons=self.num_output_neurons, conn_prob=self.conn_prob) model.to(self.device) start = t() print("\nProgress: ""(%.4f seconds)" % (t() - start)) progress = tqdm(total=len(input_data_generator)) for local_data in input_data_generator: local_data = local_data.to(self.device).float() with torch.no_grad(): input_spikes.append(local_data.tolist()[0]) output_spikes.append(model.forward(local_data).tolist()[0]) progress.update(1) progress.close() return torch.tensor(input_spikes), torch.tensor(output_spikes) def plot_simulation_results(self, input_spike_data: torch.Tensor, output_spike_data: torch.Tensor) -> None: fig, ax = plt.subplots(1, 2) ax[0].scatter(*torch.where(input_spike_data), color='k') ax[0].set_xlim([0, self.num_steps]) ax[0].set_ylabel(" Number of input channels (M) ") ax[0].set_xlabel(" Number of time points (T) ") ax[0].set_title(" Spike raster plot ") ax[1].scatter(*torch.where(output_spike_data), color='r') ax[1].set_xlim([0, self.num_steps]) ax[1].set_xlabel(" Number of time points (T) ") ax[1].set_ylabel(" Number of output neurons (N) ") ax[1].set_title(" Spike raster plot ") have_display = bool(os.environ.get('DISPLAY', None)) if have_display: plt.show() filename = Path.cwd() / 'snnpytorch' / 'data' / \ 'input_output_spike_raster.png' plt.savefig(filename) else: filename = Path.cwd() / 'snnpytorch' / 'data' / \ 'input_output_spike_raster.png' plt.savefig(filename) if __name__ == "__main__": pipeline = Pipeline() input_spikes, output_spikes = pipeline.run() pipeline.plot_simulation_results(input_spikes, output_spikes) print("End of simulation")
true
true
1c373713fc3a5944f43acb2535da70dd94dc5803
3,213
py
Python
pulsar/apps/data/redis/lock.py
goodboy/pulsar
e4b42d94b7e262a165782747d65f8b39fb8d3ba9
[ "BSD-3-Clause" ]
1
2020-11-30T07:36:57.000Z
2020-11-30T07:36:57.000Z
pulsar/apps/data/redis/lock.py
goodboy/pulsar
e4b42d94b7e262a165782747d65f8b39fb8d3ba9
[ "BSD-3-Clause" ]
null
null
null
pulsar/apps/data/redis/lock.py
goodboy/pulsar
e4b42d94b7e262a165782747d65f8b39fb8d3ba9
[ "BSD-3-Clause" ]
null
null
null
import uuid from asyncio import sleep from pulsar import isawaitable, LockError, LockBase class RedisScript: '''An executable Lua script object ''' def __init__(self, script): self.script = script self.sha = None async def __call__(self, client, keys=None, args=None): '''Execute the script, passing any required ``args`` ''' if self.sha not in client.store.loaded_scripts: sha = await client.immediate_execute('SCRIPT', 'LOAD', self.script) self.sha = sha.decode('utf-8') client.store.loaded_scripts.add(self.sha) result = client.evalsha(self.sha, keys, args) if isawaitable(result): result = await result return result class Lock(LockBase): """Asynchronous locking primitive for distributing computing """ def __init__(self, client, name, timeout=None, blocking=True, sleep=0.2): super().__init__(name, loop=client._loop, timeout=timeout, blocking=blocking) self._token = None self.client = client self.sleep = sleep if self.blocking: self.sleep = min(self.sleep, self.blocking) def locked(self): ''''Return the token that acquire the lock or None. ''' return bool(self._token) async def _acquire(self): token = uuid.uuid1().hex.encode('utf-8') timeout = self.timeout and int(self.timeout * 1000) or '' acquired = await self.lua_acquire(self.client, keys=[self.name], args=[token, timeout]) if acquired: self._token = token return acquired async def acquire(self): loop = self._loop start = loop.time() acquired = await self._acquire() if self.blocking is False: return acquired timeout = self.blocking if timeout is True: timeout = 0 while not acquired: if timeout and loop.time() - start >= timeout: break await sleep(self.sleep) acquired = await self._acquire() return acquired async def release(self): expected_token = self._token if not expected_token: raise LockError("Cannot release an unlocked lock") released = await self.lua_release(self.client, keys=[self.name], args=[expected_token]) self._token = None if not released: raise LockError("Cannot release a lock that's no longer owned") return True lua_acquire = RedisScript(""" if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then if ARGV[2] ~= '' then redis.call('pexpire', KEYS[1], ARGV[2]) end return 1 end return 0 """) # KEYS[1] - lock name # ARGS[1] - token # return 1 if the lock was released, otherwise 0 lua_release = RedisScript(""" local token = redis.call('get', KEYS[1]) if not token or token ~= ARGV[1] then return 0 end redis.call('del', KEYS[1]) return 1 """)
30.894231
79
0.563336
import uuid from asyncio import sleep from pulsar import isawaitable, LockError, LockBase class RedisScript: def __init__(self, script): self.script = script self.sha = None async def __call__(self, client, keys=None, args=None): if self.sha not in client.store.loaded_scripts: sha = await client.immediate_execute('SCRIPT', 'LOAD', self.script) self.sha = sha.decode('utf-8') client.store.loaded_scripts.add(self.sha) result = client.evalsha(self.sha, keys, args) if isawaitable(result): result = await result return result class Lock(LockBase): def __init__(self, client, name, timeout=None, blocking=True, sleep=0.2): super().__init__(name, loop=client._loop, timeout=timeout, blocking=blocking) self._token = None self.client = client self.sleep = sleep if self.blocking: self.sleep = min(self.sleep, self.blocking) def locked(self): return bool(self._token) async def _acquire(self): token = uuid.uuid1().hex.encode('utf-8') timeout = self.timeout and int(self.timeout * 1000) or '' acquired = await self.lua_acquire(self.client, keys=[self.name], args=[token, timeout]) if acquired: self._token = token return acquired async def acquire(self): loop = self._loop start = loop.time() acquired = await self._acquire() if self.blocking is False: return acquired timeout = self.blocking if timeout is True: timeout = 0 while not acquired: if timeout and loop.time() - start >= timeout: break await sleep(self.sleep) acquired = await self._acquire() return acquired async def release(self): expected_token = self._token if not expected_token: raise LockError("Cannot release an unlocked lock") released = await self.lua_release(self.client, keys=[self.name], args=[expected_token]) self._token = None if not released: raise LockError("Cannot release a lock that's no longer owned") return True lua_acquire = RedisScript(""" if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then if ARGV[2] ~= '' then redis.call('pexpire', KEYS[1], ARGV[2]) end return 1 end return 0 """) # KEYS[1] - lock name # ARGS[1] - token # return 1 if the lock was released, otherwise 0 lua_release = RedisScript(""" local token = redis.call('get', KEYS[1]) if not token or token ~= ARGV[1] then return 0 end redis.call('del', KEYS[1]) return 1 """)
true
true
1c3737435236ccf4b4d3a8e05f591029381480cc
2,534
py
Python
__init__.py
Andndre/calcul
3a7d51c0b793169e5efcd397768247d84d2c3c68
[ "MIT" ]
1
2022-01-03T02:27:58.000Z
2022-01-03T02:27:58.000Z
__init__.py
Andndre/calcul
3a7d51c0b793169e5efcd397768247d84d2c3c68
[ "MIT" ]
null
null
null
__init__.py
Andndre/calcul
3a7d51c0b793169e5efcd397768247d84d2c3c68
[ "MIT" ]
null
null
null
import re def calculate(input : str): """ Accepted operators and symbols: `^` or `**`: power `)` and `(`: brackets for computation ordering `+`: add `-`: subtract `x` or `*`: multiply `:` or `/`: divide `,` or `.`: decimal Args: input (str): input Raises: SyntaxError: When user inputs wrong syntax, i.e. Invalid brackets, Unsupported character, and Invalid operator Returns: number: result Examples: 1+1*0 3((5/(5/25))^(56/4))(5+6-(1+2+3+4)) 5(2)(4 --> Too many opening brackets 5^^4 --> Operator error 4/0 --> can't divide by zero! """ if re.search(r'[^0-9+\-*/:()Xx^.,\s]', input): raise SyntaxError('Accepts only numbers and symbols + - * x : / ) ( ^ . ,') input = ( input .replace('++', '+') .replace('-+', '-') .replace('+-', '-') .replace('--', '+') .replace('^', '**') .replace('x', '*') .replace('X', '*') .replace(':', '/') .replace(',', '.') .replace(' ', '') ) op = input.count('(') cl = input.count(')') if op != cl: opcl = "opening" if op > cl else "closing" raise SyntaxError(f'There are too many {opcl} brackets somewhere') step1 = __validate__(input) # print('step 1:',step1) step2 = __calc__(step1.replace(' ', '')) # print('step 2:',step2) return step2 def __validate__(mth : str) -> str: # add missing * before ( or after ) j = 1 operators = ['+','-','*','/', '^'] if len(mth.strip()) == 1: return mth while(True): if j == len(mth)-1: break if mth[j] == '(': if mth[j-1] not in operators and mth[j-1] != '(': # insert '*' at i mth = mth[:j] + '*' + mth[j:] elif mth[j] == ')': if mth[j+1] not in operators and mth[j+1] != ')': # insert '*' at i+1 mth = mth[:j+1] + '*' + mth[j+1:] j+=1 return mth def __calc__(mth : str): tmp = '' final = '' unclosed = 0 got_brace = False for n in mth: if n == '(': if got_brace: tmp += '(' got_brace = True unclosed += 1 continue if n == ')': unclosed -= 1 if got_brace: if unclosed == 0: expanded = __calc__(tmp) final += expanded got_brace = False tmp = '' else: tmp += ')' continue if got_brace: tmp += n else: final += n result = str(eval(final)) return result
21.474576
114
0.46764
import re def calculate(input : str): if re.search(r'[^0-9+\-*/:()Xx^.,\s]', input): raise SyntaxError('Accepts only numbers and symbols + - * x : / ) ( ^ . ,') input = ( input .replace('++', '+') .replace('-+', '-') .replace('+-', '-') .replace('--', '+') .replace('^', '**') .replace('x', '*') .replace('X', '*') .replace(':', '/') .replace(',', '.') .replace(' ', '') ) op = input.count('(') cl = input.count(')') if op != cl: opcl = "opening" if op > cl else "closing" raise SyntaxError(f'There are too many {opcl} brackets somewhere') step1 = __validate__(input) step2 = __calc__(step1.replace(' ', '')) return step2 def __validate__(mth : str) -> str: j = 1 operators = ['+','-','*','/', '^'] if len(mth.strip()) == 1: return mth while(True): if j == len(mth)-1: break if mth[j] == '(': if mth[j-1] not in operators and mth[j-1] != '(': mth = mth[:j] + '*' + mth[j:] elif mth[j] == ')': if mth[j+1] not in operators and mth[j+1] != ')': mth = mth[:j+1] + '*' + mth[j+1:] j+=1 return mth def __calc__(mth : str): tmp = '' final = '' unclosed = 0 got_brace = False for n in mth: if n == '(': if got_brace: tmp += '(' got_brace = True unclosed += 1 continue if n == ')': unclosed -= 1 if got_brace: if unclosed == 0: expanded = __calc__(tmp) final += expanded got_brace = False tmp = '' else: tmp += ')' continue if got_brace: tmp += n else: final += n result = str(eval(final)) return result
true
true
1c3737f6d24a87545027d263c01427ba4c66fea5
6,266
py
Python
troposphere/blueprints/security-groups-opc.py
pataraco/hart_challenge
47872a17b5ade54620df92a27d0ece2a8dfa6f07
[ "MIT" ]
null
null
null
troposphere/blueprints/security-groups-opc.py
pataraco/hart_challenge
47872a17b5ade54620df92a27d0ece2a8dfa6f07
[ "MIT" ]
1
2021-05-10T21:34:20.000Z
2021-05-10T21:34:20.000Z
troposphere/blueprints/security-groups-opc.py
pataraco/iac
47872a17b5ade54620df92a27d0ece2a8dfa6f07
[ "MIT" ]
1
2017-05-28T10:45:14.000Z
2017-05-28T10:45:14.000Z
#!/usr/bin/env python """Module with VPC security groups.""" from stacker.blueprints.base import Blueprint from stacker.blueprints.variables.types import CFNString, EC2VPCId from troposphere import ec2, Export, Join, Output, Ref, Sub, Tags from utils import standalone_output, version # pylint: disable=relative-import class SecurityGroups(Blueprint): """Stacker blueprint for core AWS environment security groups.""" VARIABLES = { 'CustomerName': {'type': CFNString, 'description': 'The nickname for the new customer. ' 'Must be all lowercase letters, ' 'should not contain spaces or special ' 'characters, nor should it include ' 'any part of EnvironmentName.', 'allowed_pattern': '[-_ a-z]*', 'default': ''}, 'EnvironmentName': {'type': CFNString, 'description': 'Name of Environment', 'default': 'common'}, 'VpcId': {'type': EC2VPCId, 'description': 'VPC id.'} } def add_resources(self): """Add resources to template.""" template = self.template variables = self.get_variables() vpnsecuritygroup = template.add_resource( ec2.SecurityGroup( 'VPNSecurityGroup', GroupDescription=Join('-', [variables['CustomerName'].ref, 'vpn-servers']), SecurityGroupIngress=[ ec2.SecurityGroupRule( IpProtocol='udp', FromPort='1194', # OpenVPN server ToPort='1194', CidrIp='0.0.0.0/0') ], SecurityGroupEgress=[ ec2.SecurityGroupRule( IpProtocol='-1', FromPort='0', ToPort='65535', CidrIp='0.0.0.0/0') ], Tags=Tags( Name=Join( '-', [variables['CustomerName'].ref, 'vpn-servers', variables['EnvironmentName'].ref] ) ), VpcId=Ref('VpcId') ) ) template.add_output( Output( vpnsecuritygroup.title, Description='Security group for VPN servers', Export=Export( Sub('${AWS::StackName}-%s' % vpnsecuritygroup.title) ), Value=Ref(vpnsecuritygroup) ) ) allsecuritygroup = template.add_resource( ec2.SecurityGroup( 'AllSecurityGroup', GroupDescription=Join('-', [variables['CustomerName'].ref, 'all-servers']), SecurityGroupIngress=[ ec2.SecurityGroupRule( IpProtocol='-1', FromPort='0', ToPort='65535', SourceSecurityGroupId=Ref(vpnsecuritygroup)) ], SecurityGroupEgress=[ ec2.SecurityGroupRule( IpProtocol='-1', FromPort='0', ToPort='65535', CidrIp='0.0.0.0/0') ], Tags=Tags( Name=Join( '-', [variables['CustomerName'].ref, 'all-servers', variables['EnvironmentName'].ref] ) ), VpcId=Ref('VpcId') ) ) template.add_output( Output( allsecuritygroup.title, Description='Security group for all servers', Export=Export( Sub('${AWS::StackName}-%s' % allsecuritygroup.title) ), Value=Ref(allsecuritygroup) ) ) internalsecuritygroup = template.add_resource( ec2.SecurityGroup( 'InternalSecurityGroup', GroupDescription=Join('-', [variables['CustomerName'].ref, 'internal-servers']), SecurityGroupIngress=[], SecurityGroupEgress=[ ec2.SecurityGroupRule( IpProtocol='-1', FromPort='0', ToPort='65535', CidrIp='0.0.0.0/0') ], Tags=Tags( Name=Join( '-', [variables['CustomerName'].ref, 'internal-servers', variables['EnvironmentName'].ref] ) ), VpcId=Ref('VpcId') ) ) template.add_output( Output( internalsecuritygroup.title, Description='Security group for internal servers', Export=Export( Sub('${AWS::StackName}-%s' % internalsecuritygroup.title) ), Value=Ref(internalsecuritygroup) ) ) def create_template(self): """Create template (main function called by Stacker).""" self.template.add_version('2010-09-09') self.template.add_description( 'Onica Platform - Core' ' - Security Groups - {}'.format(version.version()) ) self.add_resources() # Helper section to enable easy blueprint -> template generation # (just run `python <thisfile>` to output the json) if __name__ == "__main__": from stacker.context import Context standalone_output.json( blueprint=SecurityGroups( 'test', Context({"namespace": "test"}), None ) )
36.430233
79
0.437759
from stacker.blueprints.base import Blueprint from stacker.blueprints.variables.types import CFNString, EC2VPCId from troposphere import ec2, Export, Join, Output, Ref, Sub, Tags from utils import standalone_output, version class SecurityGroups(Blueprint): VARIABLES = { 'CustomerName': {'type': CFNString, 'description': 'The nickname for the new customer. ' 'Must be all lowercase letters, ' 'should not contain spaces or special ' 'characters, nor should it include ' 'any part of EnvironmentName.', 'allowed_pattern': '[-_ a-z]*', 'default': ''}, 'EnvironmentName': {'type': CFNString, 'description': 'Name of Environment', 'default': 'common'}, 'VpcId': {'type': EC2VPCId, 'description': 'VPC id.'} } def add_resources(self): template = self.template variables = self.get_variables() vpnsecuritygroup = template.add_resource( ec2.SecurityGroup( 'VPNSecurityGroup', GroupDescription=Join('-', [variables['CustomerName'].ref, 'vpn-servers']), SecurityGroupIngress=[ ec2.SecurityGroupRule( IpProtocol='udp', FromPort='1194', ToPort='1194', CidrIp='0.0.0.0/0') ], SecurityGroupEgress=[ ec2.SecurityGroupRule( IpProtocol='-1', FromPort='0', ToPort='65535', CidrIp='0.0.0.0/0') ], Tags=Tags( Name=Join( '-', [variables['CustomerName'].ref, 'vpn-servers', variables['EnvironmentName'].ref] ) ), VpcId=Ref('VpcId') ) ) template.add_output( Output( vpnsecuritygroup.title, Description='Security group for VPN servers', Export=Export( Sub('${AWS::StackName}-%s' % vpnsecuritygroup.title) ), Value=Ref(vpnsecuritygroup) ) ) allsecuritygroup = template.add_resource( ec2.SecurityGroup( 'AllSecurityGroup', GroupDescription=Join('-', [variables['CustomerName'].ref, 'all-servers']), SecurityGroupIngress=[ ec2.SecurityGroupRule( IpProtocol='-1', FromPort='0', ToPort='65535', SourceSecurityGroupId=Ref(vpnsecuritygroup)) ], SecurityGroupEgress=[ ec2.SecurityGroupRule( IpProtocol='-1', FromPort='0', ToPort='65535', CidrIp='0.0.0.0/0') ], Tags=Tags( Name=Join( '-', [variables['CustomerName'].ref, 'all-servers', variables['EnvironmentName'].ref] ) ), VpcId=Ref('VpcId') ) ) template.add_output( Output( allsecuritygroup.title, Description='Security group for all servers', Export=Export( Sub('${AWS::StackName}-%s' % allsecuritygroup.title) ), Value=Ref(allsecuritygroup) ) ) internalsecuritygroup = template.add_resource( ec2.SecurityGroup( 'InternalSecurityGroup', GroupDescription=Join('-', [variables['CustomerName'].ref, 'internal-servers']), SecurityGroupIngress=[], SecurityGroupEgress=[ ec2.SecurityGroupRule( IpProtocol='-1', FromPort='0', ToPort='65535', CidrIp='0.0.0.0/0') ], Tags=Tags( Name=Join( '-', [variables['CustomerName'].ref, 'internal-servers', variables['EnvironmentName'].ref] ) ), VpcId=Ref('VpcId') ) ) template.add_output( Output( internalsecuritygroup.title, Description='Security group for internal servers', Export=Export( Sub('${AWS::StackName}-%s' % internalsecuritygroup.title) ), Value=Ref(internalsecuritygroup) ) ) def create_template(self): self.template.add_version('2010-09-09') self.template.add_description( 'Onica Platform - Core' ' - Security Groups - {}'.format(version.version()) ) self.add_resources() if __name__ == "__main__": from stacker.context import Context standalone_output.json( blueprint=SecurityGroups( 'test', Context({"namespace": "test"}), None ) )
true
true
1c3739bd387a9511930bdc26079a66d2550ad7c1
5,529
py
Python
new_package/seed/generate_asdf_normal.py
ziyixi/SeisScripts
a484bc1747eae52b2441f0bfd47ac7e093150f1d
[ "MIT" ]
null
null
null
new_package/seed/generate_asdf_normal.py
ziyixi/SeisScripts
a484bc1747eae52b2441f0bfd47ac7e093150f1d
[ "MIT" ]
null
null
null
new_package/seed/generate_asdf_normal.py
ziyixi/SeisScripts
a484bc1747eae52b2441f0bfd47ac7e093150f1d
[ "MIT" ]
null
null
null
""" since always obspy may have problem in reading seed files, it's better to use rdseed to generate sac files and resp files. """ import pyasdf from glob import glob import obspy import tempfile from os.path import join import subprocess from loguru import logger from obspy.io.xseed import Parser def generate_asdf_for_single_event(seed_directory, cmt_path, output_path, with_mpi, logfile): logger.add(logfile, format="{time} {level} {message}", level="INFO") # generate asdf file if(not with_mpi): ds = pyasdf.ASDFDataSet(output_path, compression="gzip-3") logger.info("not with mpi, use gzip-3") else: ds = pyasdf.ASDFDataSet(output_path, compression=None) logger.info("will use mpi, no compression") # readin eventxml event_xml = obspy.read_events(cmt_path) # add event xml to ds logger.info(f"adding event_xml {cmt_path}") ds.add_quakeml(event_xml) event = ds.events[0] # readin waves files = glob(join(seed_directory, "*")) station_xml = obspy.core.inventory.inventory.Inventory() waveform_read_status = None for i, filename in enumerate(files): logger.info(f"adding waves #{i} {filename}") # try to use obspy try: waveform_stream = obspy.read(filename) logger.info(f"{filename} is able to use obspy to read waveforms") waveform_read_status = 1 except: dirpath = tempfile.mkdtemp() command = f"rdseed -d -f {filename} -q {dirpath}" subprocess.call(command, shell=True) waveform_stream = obspy.read(join(dirpath, "*SAC")) logger.info(f"{filename} could only use rdseed to read waveforms") waveform_read_status = 2 ds.add_waveforms(waveform_stream, tag="raw", event_id=event) # add stationxml (since statinxml may be different for different events, it's better # to store only one event in ds) logger.info(f"adding stationxml #{i} {filename}") try: station_xml_file_obj = tempfile.NamedTemporaryFile(delete=False) station_xml_file_obj.close() station_xml_file_path = station_xml_file_obj.name sp = Parser(filename) sp.write_xseed(station_xml_file_path) station_xml_this_seed = obspy.read_inventory(station_xml_file_path) logger.info(f"{filename} could use obspy to read stationxml") except: # since such an error occurs, we might have to use the except part to read the waveform to get the sac head if(waveform_read_status == 1): # re readin waveform_stream dirpath = tempfile.mkdtemp() command = f"rdseed -d -f {filename} -q {dirpath}" subprocess.call(command, shell=True) waveform_stream = obspy.read(join(dirpath, "*SAC")) logger.info( f"{filename} uses rdseed to read in head information") else: pass # should already have the head information dirpath = tempfile.mkdtemp() command = f"rdseed -R -f {filename} -q {dirpath}" subprocess.call(command, shell=True) station_xml_this_seed = obspy.core.inventory.inventory.Inventory() allfiles = glob(join(dirpath, "*")) for fname in allfiles: inv_temp = obspy.read_inventory(fname) # update essencial location information inv_temp = update_info(inv_temp, waveform_stream) if(inv_temp == None): continue station_xml_this_seed += inv_temp logger.info(f"{filename} could only use rdseed to read stationxml") station_xml += station_xml_this_seed ds.add_stationxml(station_xml) del ds logger.success(f"success in creating {output_path}") def update_info(inv, waveform_stream): usable_channels = inv.get_contents()["channels"] # loop all channels, search info status = False for channel in usable_channels: # channel, like BO.NKG..BHE if(status == False): for thewave in waveform_stream: waveid = thewave.id if(waveid == channel): status = True inv[0][0].latitude = thewave.stats.sac.stla inv[0][0].longitude = thewave.stats.sac.stlo inv[0][0].elevation = thewave.stats.sac.stel break if(not status): logger.error( f"problem in updating head info for {inv.get_contents()['stations'][0]}") return None else: return inv if __name__ == "__main__": import click @click.command() @click.option('--seed_directory', required=True, type=str, help="the directory containing all the seed files for this event") @click.option('--cmt_path', required=True, type=str, help="the CMTSOLUTION file for this event") @click.option('--output_path', required=True, type=str, help="the output path for hdf5 file") @click.option('--with_mpi/--no-with_mpi', default=False, help="if this file will be used with mpi (compression or not)") @click.option('--logfile', required=True, type=str, help="the log file path") def main(seed_directory, cmt_path, output_path, with_mpi, logfile): generate_asdf_for_single_event( seed_directory, cmt_path, output_path, with_mpi, logfile) main()
39.776978
129
0.629589
import pyasdf from glob import glob import obspy import tempfile from os.path import join import subprocess from loguru import logger from obspy.io.xseed import Parser def generate_asdf_for_single_event(seed_directory, cmt_path, output_path, with_mpi, logfile): logger.add(logfile, format="{time} {level} {message}", level="INFO") if(not with_mpi): ds = pyasdf.ASDFDataSet(output_path, compression="gzip-3") logger.info("not with mpi, use gzip-3") else: ds = pyasdf.ASDFDataSet(output_path, compression=None) logger.info("will use mpi, no compression") event_xml = obspy.read_events(cmt_path) logger.info(f"adding event_xml {cmt_path}") ds.add_quakeml(event_xml) event = ds.events[0] files = glob(join(seed_directory, "*")) station_xml = obspy.core.inventory.inventory.Inventory() waveform_read_status = None for i, filename in enumerate(files): logger.info(f"adding waves #{i} {filename}") try: waveform_stream = obspy.read(filename) logger.info(f"{filename} is able to use obspy to read waveforms") waveform_read_status = 1 except: dirpath = tempfile.mkdtemp() command = f"rdseed -d -f {filename} -q {dirpath}" subprocess.call(command, shell=True) waveform_stream = obspy.read(join(dirpath, "*SAC")) logger.info(f"{filename} could only use rdseed to read waveforms") waveform_read_status = 2 ds.add_waveforms(waveform_stream, tag="raw", event_id=event) # to store only one event in ds) logger.info(f"adding stationxml #{i} {filename}") try: station_xml_file_obj = tempfile.NamedTemporaryFile(delete=False) station_xml_file_obj.close() station_xml_file_path = station_xml_file_obj.name sp = Parser(filename) sp.write_xseed(station_xml_file_path) station_xml_this_seed = obspy.read_inventory(station_xml_file_path) logger.info(f"{filename} could use obspy to read stationxml") except: # since such an error occurs, we might have to use the except part to read the waveform to get the sac head if(waveform_read_status == 1): # re readin waveform_stream dirpath = tempfile.mkdtemp() command = f"rdseed -d -f {filename} -q {dirpath}" subprocess.call(command, shell=True) waveform_stream = obspy.read(join(dirpath, "*SAC")) logger.info( f"{filename} uses rdseed to read in head information") else: pass # should already have the head information dirpath = tempfile.mkdtemp() command = f"rdseed -R -f {filename} -q {dirpath}" subprocess.call(command, shell=True) station_xml_this_seed = obspy.core.inventory.inventory.Inventory() allfiles = glob(join(dirpath, "*")) for fname in allfiles: inv_temp = obspy.read_inventory(fname) # update essencial location information inv_temp = update_info(inv_temp, waveform_stream) if(inv_temp == None): continue station_xml_this_seed += inv_temp logger.info(f"{filename} could only use rdseed to read stationxml") station_xml += station_xml_this_seed ds.add_stationxml(station_xml) del ds logger.success(f"success in creating {output_path}") def update_info(inv, waveform_stream): usable_channels = inv.get_contents()["channels"] # loop all channels, search info status = False for channel in usable_channels: # channel, like BO.NKG..BHE if(status == False): for thewave in waveform_stream: waveid = thewave.id if(waveid == channel): status = True inv[0][0].latitude = thewave.stats.sac.stla inv[0][0].longitude = thewave.stats.sac.stlo inv[0][0].elevation = thewave.stats.sac.stel break if(not status): logger.error( f"problem in updating head info for {inv.get_contents()['stations'][0]}") return None else: return inv if __name__ == "__main__": import click @click.command() @click.option('--seed_directory', required=True, type=str, help="the directory containing all the seed files for this event") @click.option('--cmt_path', required=True, type=str, help="the CMTSOLUTION file for this event") @click.option('--output_path', required=True, type=str, help="the output path for hdf5 file") @click.option('--with_mpi/--no-with_mpi', default=False, help="if this file will be used with mpi (compression or not)") @click.option('--logfile', required=True, type=str, help="the log file path") def main(seed_directory, cmt_path, output_path, with_mpi, logfile): generate_asdf_for_single_event( seed_directory, cmt_path, output_path, with_mpi, logfile) main()
true
true
1c3739d9aebb85cd18276e43617d0ccfffa6040b
30,411
py
Python
pandas/tests/indexes/common.py
tyvich/pandas
22de58e63f9271d4ddb2bf49d008c5a9550c5cc4
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause" ]
null
null
null
pandas/tests/indexes/common.py
tyvich/pandas
22de58e63f9271d4ddb2bf49d008c5a9550c5cc4
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause" ]
null
null
null
pandas/tests/indexes/common.py
tyvich/pandas
22de58e63f9271d4ddb2bf49d008c5a9550c5cc4
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause" ]
null
null
null
from __future__ import annotations from datetime import datetime import gc import numpy as np import pytest from pandas._libs import iNaT from pandas._libs.tslibs import Timestamp from pandas.core.dtypes.common import ( is_datetime64tz_dtype, is_float_dtype, is_integer_dtype, is_unsigned_integer_dtype, ) from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd from pandas import ( CategoricalIndex, DatetimeIndex, Index, IntervalIndex, MultiIndex, NumericIndex, PeriodIndex, RangeIndex, Series, TimedeltaIndex, isna, ) import pandas._testing as tm from pandas.core.api import ( # noqa:F401 Float64Index, Int64Index, UInt64Index, ) from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin class Base: """ Base class for index sub-class tests. """ _index_cls: type[Index] @pytest.fixture def simple_index(self): raise NotImplementedError("Method not implemented") def create_index(self) -> Index: raise NotImplementedError("Method not implemented") def test_pickle_compat_construction(self): # need an object to create with msg = "|".join( [ r"Index\(\.\.\.\) must be called with a collection of some " r"kind, None was passed", r"DatetimeIndex\(\) must be called with a collection of some " r"kind, None was passed", r"TimedeltaIndex\(\) must be called with a collection of some " r"kind, None was passed", r"__new__\(\) missing 1 required positional argument: 'data'", r"__new__\(\) takes at least 2 arguments \(1 given\)", ] ) with pytest.raises(TypeError, match=msg): self._index_cls() @pytest.mark.parametrize("name", [None, "new_name"]) def test_to_frame(self, name, simple_index): # see GH-15230, GH-22580 idx = simple_index if name: idx_name = name else: idx_name = idx.name or 0 df = idx.to_frame(name=idx_name) assert df.index is idx assert len(df.columns) == 1 assert df.columns[0] == idx_name assert df[idx_name].values is not idx.values df = idx.to_frame(index=False, name=idx_name) assert df.index is not idx def test_shift(self, simple_index): # GH8083 test the base class for shift idx = simple_index msg = ( f"This method is only implemented for DatetimeIndex, PeriodIndex and " f"TimedeltaIndex; Got type {type(idx).__name__}" ) with pytest.raises(NotImplementedError, match=msg): idx.shift(1) with pytest.raises(NotImplementedError, match=msg): idx.shift(1, 2) def test_constructor_name_unhashable(self, simple_index): # GH#29069 check that name is hashable # See also same-named test in tests.series.test_constructors idx = simple_index with pytest.raises(TypeError, match="Index.name must be a hashable type"): type(idx)(idx, name=[]) def test_create_index_existing_name(self, simple_index): # GH11193, when an existing index is passed, and a new name is not # specified, the new index should inherit the previous object name expected = simple_index if not isinstance(expected, MultiIndex): expected.name = "foo" result = Index(expected) tm.assert_index_equal(result, expected) result = Index(expected, name="bar") expected.name = "bar" tm.assert_index_equal(result, expected) else: expected.names = ["foo", "bar"] result = Index(expected) tm.assert_index_equal( result, Index( Index( [ ("foo", "one"), ("foo", "two"), ("bar", "one"), ("baz", "two"), ("qux", "one"), ("qux", "two"), ], dtype="object", ), names=["foo", "bar"], ), ) result = Index(expected, names=["A", "B"]) tm.assert_index_equal( result, Index( Index( [ ("foo", "one"), ("foo", "two"), ("bar", "one"), ("baz", "two"), ("qux", "one"), ("qux", "two"), ], dtype="object", ), names=["A", "B"], ), ) def test_numeric_compat(self, simple_index): idx = simple_index # Check that this doesn't cover MultiIndex case, if/when it does, # we can remove multi.test_compat.test_numeric_compat assert not isinstance(idx, MultiIndex) if type(idx) is Index: return typ = type(idx._data).__name__ cls = type(idx).__name__ lmsg = "|".join( [ rf"unsupported operand type\(s\) for \*: '{typ}' and 'int'", "cannot perform (__mul__|__truediv__|__floordiv__) with " f"this index type: ({cls}|{typ})", ] ) with pytest.raises(TypeError, match=lmsg): idx * 1 rmsg = "|".join( [ rf"unsupported operand type\(s\) for \*: 'int' and '{typ}'", "cannot perform (__rmul__|__rtruediv__|__rfloordiv__) with " f"this index type: ({cls}|{typ})", ] ) with pytest.raises(TypeError, match=rmsg): 1 * idx div_err = lmsg.replace("*", "/") with pytest.raises(TypeError, match=div_err): idx / 1 div_err = rmsg.replace("*", "/") with pytest.raises(TypeError, match=div_err): 1 / idx floordiv_err = lmsg.replace("*", "//") with pytest.raises(TypeError, match=floordiv_err): idx // 1 floordiv_err = rmsg.replace("*", "//") with pytest.raises(TypeError, match=floordiv_err): 1 // idx def test_logical_compat(self, simple_index): idx = simple_index with pytest.raises(TypeError, match="cannot perform all"): idx.all() with pytest.raises(TypeError, match="cannot perform any"): idx.any() def test_repr_roundtrip(self, simple_index): idx = simple_index tm.assert_index_equal(eval(repr(idx)), idx) def test_repr_max_seq_item_setting(self, simple_index): # GH10182 idx = simple_index idx = idx.repeat(50) with pd.option_context("display.max_seq_items", None): repr(idx) assert "..." not in str(idx) def test_copy_name(self, index): # gh-12309: Check that the "name" argument # passed at initialization is honored. if isinstance(index, MultiIndex): return first = type(index)(index, copy=True, name="mario") second = type(first)(first, copy=False) # Even though "copy=False", we want a new object. assert first is not second # Not using tm.assert_index_equal() since names differ. assert index.equals(first) assert first.name == "mario" assert second.name == "mario" s1 = Series(2, index=first) s2 = Series(3, index=second[:-1]) if not isinstance(index, CategoricalIndex): # See gh-13365 s3 = s1 * s2 assert s3.index.name == "mario" def test_copy_name2(self, index): # gh-35592 if isinstance(index, MultiIndex): return assert index.copy(name="mario").name == "mario" with pytest.raises(ValueError, match="Length of new names must be 1, got 2"): index.copy(name=["mario", "luigi"]) msg = f"{type(index).__name__}.name must be a hashable type" with pytest.raises(TypeError, match=msg): index.copy(name=[["mario"]]) def test_ensure_copied_data(self, index): # Check the "copy" argument of each Index.__new__ is honoured # GH12309 init_kwargs = {} if isinstance(index, PeriodIndex): # Needs "freq" specification: init_kwargs["freq"] = index.freq elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)): # RangeIndex cannot be initialized from data # MultiIndex and CategoricalIndex are tested separately return index_type = type(index) result = index_type(index.values, copy=True, **init_kwargs) if is_datetime64tz_dtype(index.dtype): result = result.tz_localize("UTC").tz_convert(index.tz) if isinstance(index, (DatetimeIndex, TimedeltaIndex)): index = index._with_freq(None) tm.assert_index_equal(index, result) if isinstance(index, PeriodIndex): # .values an object array of Period, thus copied result = index_type(ordinal=index.asi8, copy=False, **init_kwargs) tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same") elif isinstance(index, IntervalIndex): # checked in test_interval.py pass else: result = index_type(index.values, copy=False, **init_kwargs) tm.assert_numpy_array_equal(index.values, result.values, check_same="same") def test_memory_usage(self, index): index._engine.clear_mapping() result = index.memory_usage() if index.empty: # we report 0 for no-length assert result == 0 return # non-zero length index.get_loc(index[0]) result2 = index.memory_usage() result3 = index.memory_usage(deep=True) # RangeIndex, IntervalIndex # don't have engines if not isinstance(index, (RangeIndex, IntervalIndex)): assert result2 > result if index.inferred_type == "object": assert result3 > result2 def test_argsort(self, request, index): # separately tested if isinstance(index, CategoricalIndex): return result = index.argsort() expected = np.array(index).argsort() tm.assert_numpy_array_equal(result, expected, check_dtype=False) def test_numpy_argsort(self, index): result = np.argsort(index) expected = index.argsort() tm.assert_numpy_array_equal(result, expected) # these are the only two types that perform # pandas compatibility input validation - the # rest already perform separate (or no) such # validation via their 'values' attribute as # defined in pandas.core.indexes/base.py - they # cannot be changed at the moment due to # backwards compatibility concerns if isinstance(type(index), (CategoricalIndex, RangeIndex)): # TODO: why type(index)? msg = "the 'axis' parameter is not supported" with pytest.raises(ValueError, match=msg): np.argsort(index, axis=1) msg = "the 'kind' parameter is not supported" with pytest.raises(ValueError, match=msg): np.argsort(index, kind="mergesort") msg = "the 'order' parameter is not supported" with pytest.raises(ValueError, match=msg): np.argsort(index, order=("a", "b")) def test_repeat(self, simple_index): rep = 2 idx = simple_index.copy() new_index_cls = Int64Index if isinstance(idx, RangeIndex) else idx._constructor expected = new_index_cls(idx.values.repeat(rep), name=idx.name) tm.assert_index_equal(idx.repeat(rep), expected) idx = simple_index rep = np.arange(len(idx)) expected = new_index_cls(idx.values.repeat(rep), name=idx.name) tm.assert_index_equal(idx.repeat(rep), expected) def test_numpy_repeat(self, simple_index): rep = 2 idx = simple_index expected = idx.repeat(rep) tm.assert_index_equal(np.repeat(idx, rep), expected) msg = "the 'axis' parameter is not supported" with pytest.raises(ValueError, match=msg): np.repeat(idx, rep, axis=0) def test_where(self, listlike_box_with_tuple, simple_index): klass = listlike_box_with_tuple idx = simple_index if isinstance(idx, (DatetimeIndex, TimedeltaIndex)): # where does not preserve freq idx = idx._with_freq(None) cond = [True] * len(idx) result = idx.where(klass(cond)) expected = idx tm.assert_index_equal(result, expected) cond = [False] + [True] * len(idx[1:]) expected = Index([idx._na_value] + idx[1:].tolist(), dtype=idx.dtype) result = idx.where(klass(cond)) tm.assert_index_equal(result, expected) def test_insert_base(self, index): result = index[1:4] if not len(index): return # test 0th element assert index[0:4].equals(result.insert(0, index[0])) def test_delete_base(self, index): if not len(index): return if isinstance(index, RangeIndex): # tested in class return expected = index[1:] result = index.delete(0) assert result.equals(expected) assert result.name == expected.name expected = index[:-1] result = index.delete(-1) assert result.equals(expected) assert result.name == expected.name length = len(index) msg = f"index {length} is out of bounds for axis 0 with size {length}" with pytest.raises(IndexError, match=msg): index.delete(length) def test_equals(self, index): if isinstance(index, IntervalIndex): # IntervalIndex tested separately, the index.equals(index.astype(object)) # fails for IntervalIndex return assert index.equals(index) assert index.equals(index.copy()) assert index.equals(index.astype(object)) assert not index.equals(list(index)) assert not index.equals(np.array(index)) # Cannot pass in non-int64 dtype to RangeIndex if not isinstance(index, RangeIndex): same_values = Index(index, dtype=object) assert index.equals(same_values) assert same_values.equals(index) if index.nlevels == 1: # do not test MultiIndex assert not index.equals(Series(index)) def test_equals_op(self, simple_index): # GH9947, GH10637 index_a = simple_index n = len(index_a) index_b = index_a[0:-1] index_c = index_a[0:-1].append(index_a[-2:-1]) index_d = index_a[0:1] msg = "Lengths must match|could not be broadcast" with pytest.raises(ValueError, match=msg): index_a == index_b expected1 = np.array([True] * n) expected2 = np.array([True] * (n - 1) + [False]) tm.assert_numpy_array_equal(index_a == index_a, expected1) tm.assert_numpy_array_equal(index_a == index_c, expected2) # test comparisons with numpy arrays array_a = np.array(index_a) array_b = np.array(index_a[0:-1]) array_c = np.array(index_a[0:-1].append(index_a[-2:-1])) array_d = np.array(index_a[0:1]) with pytest.raises(ValueError, match=msg): index_a == array_b tm.assert_numpy_array_equal(index_a == array_a, expected1) tm.assert_numpy_array_equal(index_a == array_c, expected2) # test comparisons with Series series_a = Series(array_a) series_b = Series(array_b) series_c = Series(array_c) series_d = Series(array_d) with pytest.raises(ValueError, match=msg): index_a == series_b tm.assert_numpy_array_equal(index_a == series_a, expected1) tm.assert_numpy_array_equal(index_a == series_c, expected2) # cases where length is 1 for one of them with pytest.raises(ValueError, match="Lengths must match"): index_a == index_d with pytest.raises(ValueError, match="Lengths must match"): index_a == series_d with pytest.raises(ValueError, match="Lengths must match"): index_a == array_d msg = "Can only compare identically-labeled Series objects" with pytest.raises(ValueError, match=msg): series_a == series_d with pytest.raises(ValueError, match="Lengths must match"): series_a == array_d # comparing with a scalar should broadcast; note that we are excluding # MultiIndex because in this case each item in the index is a tuple of # length 2, and therefore is considered an array of length 2 in the # comparison instead of a scalar if not isinstance(index_a, MultiIndex): expected3 = np.array([False] * (len(index_a) - 2) + [True, False]) # assuming the 2nd to last item is unique in the data item = index_a[-2] tm.assert_numpy_array_equal(index_a == item, expected3) # For RangeIndex we can convert to Int64Index tm.assert_series_equal(series_a == item, Series(expected3)) def test_format(self, simple_index): # GH35439 idx = simple_index expected = [str(x) for x in idx] assert idx.format() == expected def test_format_empty(self): # GH35712 empty_idx = self._index_cls([]) assert empty_idx.format() == [] assert empty_idx.format(name=True) == [""] def test_fillna(self, index): # GH 11343 if len(index) == 0: return elif isinstance(index, NumericIndex) and is_integer_dtype(index.dtype): return elif isinstance(index, MultiIndex): idx = index.copy(deep=True) msg = "isna is not defined for MultiIndex" with pytest.raises(NotImplementedError, match=msg): idx.fillna(idx[0]) else: idx = index.copy(deep=True) result = idx.fillna(idx[0]) tm.assert_index_equal(result, idx) assert result is not idx msg = "'value' must be a scalar, passed: " with pytest.raises(TypeError, match=msg): idx.fillna([idx[0]]) idx = index.copy(deep=True) values = np.asarray(idx.values) if isinstance(index, DatetimeIndexOpsMixin): values[1] = iNaT else: values[1] = np.nan if isinstance(index, PeriodIndex): idx = type(index)(values, freq=index.freq) else: idx = type(index)(values) expected = np.array([False] * len(idx), dtype=bool) expected[1] = True tm.assert_numpy_array_equal(idx._isnan, expected) assert idx.hasnans is True def test_nulls(self, index): # this is really a smoke test for the methods # as these are adequately tested for function elsewhere if len(index) == 0: tm.assert_numpy_array_equal(index.isna(), np.array([], dtype=bool)) elif isinstance(index, MultiIndex): idx = index.copy() msg = "isna is not defined for MultiIndex" with pytest.raises(NotImplementedError, match=msg): idx.isna() elif not index.hasnans: tm.assert_numpy_array_equal(index.isna(), np.zeros(len(index), dtype=bool)) tm.assert_numpy_array_equal(index.notna(), np.ones(len(index), dtype=bool)) else: result = isna(index) tm.assert_numpy_array_equal(index.isna(), result) tm.assert_numpy_array_equal(index.notna(), ~result) def test_empty(self, simple_index): # GH 15270 idx = simple_index assert not idx.empty assert idx[:0].empty def test_join_self_unique(self, join_type, simple_index): idx = simple_index if idx.is_unique: joined = idx.join(idx, how=join_type) assert (idx == joined).all() def test_map(self, simple_index): # callable idx = simple_index # we don't infer UInt64 if is_integer_dtype(idx.dtype): expected = idx.astype("int64") elif is_float_dtype(idx.dtype): expected = idx.astype("float64") if idx._is_backward_compat_public_numeric_index: # We get a NumericIndex back, not Float64Index expected = type(idx)(expected) else: expected = idx result = idx.map(lambda x: x) # For RangeIndex we convert to Int64Index tm.assert_index_equal(result, expected, exact="equiv") @pytest.mark.parametrize( "mapper", [ lambda values, index: {i: e for e, i in zip(values, index)}, lambda values, index: Series(values, index), ], ) def test_map_dictlike(self, mapper, simple_index): idx = simple_index if isinstance(idx, CategoricalIndex): pytest.skip(f"skipping tests for {type(idx)}") identity = mapper(idx.values, idx) # we don't infer to UInt64 for a dict if is_unsigned_integer_dtype(idx.dtype) and isinstance(identity, dict): expected = idx.astype("int64") else: expected = idx result = idx.map(identity) # For RangeIndex we convert to Int64Index tm.assert_index_equal(result, expected, exact="equiv") # empty mappable if idx._is_backward_compat_public_numeric_index: new_index_cls = NumericIndex else: new_index_cls = Float64Index expected = new_index_cls([np.nan] * len(idx)) result = idx.map(mapper(expected, idx)) tm.assert_index_equal(result, expected) def test_map_str(self, simple_index): # GH 31202 idx = simple_index result = idx.map(str) expected = Index([str(x) for x in idx], dtype=object) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("copy", [True, False]) @pytest.mark.parametrize("name", [None, "foo"]) @pytest.mark.parametrize("ordered", [True, False]) def test_astype_category(self, copy, name, ordered, simple_index): # GH 18630 idx = simple_index if name: idx = idx.rename(name) # standard categories dtype = CategoricalDtype(ordered=ordered) result = idx.astype(dtype, copy=copy) expected = CategoricalIndex(idx, name=name, ordered=ordered) tm.assert_index_equal(result, expected, exact=True) # non-standard categories dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered) result = idx.astype(dtype, copy=copy) expected = CategoricalIndex(idx, name=name, dtype=dtype) tm.assert_index_equal(result, expected, exact=True) if ordered is False: # dtype='category' defaults to ordered=False, so only test once result = idx.astype("category", copy=copy) expected = CategoricalIndex(idx, name=name) tm.assert_index_equal(result, expected, exact=True) def test_is_unique(self, simple_index): # initialize a unique index index = simple_index.drop_duplicates() assert index.is_unique is True # empty index should be unique index_empty = index[:0] assert index_empty.is_unique is True # test basic dupes index_dup = index.insert(0, index[0]) assert index_dup.is_unique is False # single NA should be unique index_na = index.insert(0, np.nan) assert index_na.is_unique is True # multiple NA should not be unique index_na_dup = index_na.insert(0, np.nan) assert index_na_dup.is_unique is False @pytest.mark.arm_slow def test_engine_reference_cycle(self, simple_index): # GH27585 index = simple_index nrefs_pre = len(gc.get_referrers(index)) index._engine assert len(gc.get_referrers(index)) == nrefs_pre def test_getitem_2d_deprecated(self, simple_index): # GH#30588, GH#31479 idx = simple_index msg = "Support for multi-dimensional indexing" with tm.assert_produces_warning(FutureWarning, match=msg): res = idx[:, None] assert isinstance(res, np.ndarray), type(res) def test_copy_shares_cache(self, simple_index): # GH32898, GH36840 idx = simple_index idx.get_loc(idx[0]) # populates the _cache. copy = idx.copy() assert copy._cache is idx._cache def test_shallow_copy_shares_cache(self, simple_index): # GH32669, GH36840 idx = simple_index idx.get_loc(idx[0]) # populates the _cache. shallow_copy = idx._view() assert shallow_copy._cache is idx._cache shallow_copy = idx._shallow_copy(idx._data) assert shallow_copy._cache is not idx._cache assert shallow_copy._cache == {} def test_index_groupby(self, simple_index): idx = simple_index[:5] to_groupby = np.array([1, 2, np.nan, 2, 1]) tm.assert_dict_equal( idx.groupby(to_groupby), {1.0: idx[[0, 4]], 2.0: idx[[1, 3]]} ) to_groupby = DatetimeIndex( [ datetime(2011, 11, 1), datetime(2011, 12, 1), pd.NaT, datetime(2011, 12, 1), datetime(2011, 11, 1), ], tz="UTC", ).values ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")] expected = {ex_keys[0]: idx[[0, 4]], ex_keys[1]: idx[[1, 3]]} tm.assert_dict_equal(idx.groupby(to_groupby), expected) def test_append_preserves_dtype(self, simple_index): # In particular NumericIndex with dtype float32 index = simple_index N = len(index) result = index.append(index) assert result.dtype == index.dtype tm.assert_index_equal(result[:N], index, check_exact=True) tm.assert_index_equal(result[N:], index, check_exact=True) alt = index.take(list(range(N)) * 2) tm.assert_index_equal(result, alt, check_exact=True) class NumericBase(Base): """ Base class for numeric index (incl. RangeIndex) sub-class tests. """ def test_constructor_unwraps_index(self, dtype): index_cls = self._index_cls idx = Index([1, 2], dtype=dtype) result = index_cls(idx) expected = np.array([1, 2], dtype=idx.dtype) tm.assert_numpy_array_equal(result._data, expected) def test_where(self): # Tested in numeric.test_indexing pass def test_can_hold_identifiers(self, simple_index): idx = simple_index key = idx[0] assert idx._can_hold_identifiers_and_holds_name(key) is False def test_format(self, simple_index): # GH35439 idx = simple_index max_width = max(len(str(x)) for x in idx) expected = [str(x).ljust(max_width) for x in idx] assert idx.format() == expected def test_numeric_compat(self): pass # override Base method def test_insert_non_na(self, simple_index): # GH#43921 inserting an element that we know we can hold should # not change dtype or type (except for RangeIndex) index = simple_index result = index.insert(0, index[0]) cls = type(index) if cls is RangeIndex: cls = Int64Index expected = cls([index[0]] + list(index), dtype=index.dtype) tm.assert_index_equal(result, expected, exact=True) def test_insert_na(self, nulls_fixture, simple_index): # GH 18295 (test missing) index = simple_index na_val = nulls_fixture if na_val is pd.NaT: expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object) else: expected = Float64Index([index[0], np.nan] + list(index[1:])) if index._is_backward_compat_public_numeric_index: # GH#43921 we preserve NumericIndex if index.dtype.kind == "f": expected = NumericIndex(expected, dtype=index.dtype) else: expected = NumericIndex(expected) result = index.insert(1, na_val) tm.assert_index_equal(result, expected, exact=True) def test_arithmetic_explicit_conversions(self): # GH 8608 # add/sub are overridden explicitly for Float/Int Index index_cls = self._index_cls if index_cls is RangeIndex: idx = RangeIndex(5) else: idx = index_cls(np.arange(5, dtype="int64")) # float conversions arr = np.arange(5, dtype="int64") * 3.2 expected = Float64Index(arr) fidx = idx * 3.2 tm.assert_index_equal(fidx, expected) fidx = 3.2 * idx tm.assert_index_equal(fidx, expected) # interops with numpy arrays expected = Float64Index(arr) a = np.zeros(5, dtype="float64") result = fidx - a tm.assert_index_equal(result, expected) expected = Float64Index(-arr) a = np.zeros(5, dtype="float64") result = a - fidx tm.assert_index_equal(result, expected) def test_invalid_dtype(self, invalid_dtype): # GH 29539 dtype = invalid_dtype msg = fr"Incorrect `dtype` passed: expected \w+(?: \w+)?, received {dtype}" with pytest.raises(ValueError, match=msg): self._index_cls([1, 2, 3], dtype=dtype)
34.557955
87
0.586827
from __future__ import annotations from datetime import datetime import gc import numpy as np import pytest from pandas._libs import iNaT from pandas._libs.tslibs import Timestamp from pandas.core.dtypes.common import ( is_datetime64tz_dtype, is_float_dtype, is_integer_dtype, is_unsigned_integer_dtype, ) from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd from pandas import ( CategoricalIndex, DatetimeIndex, Index, IntervalIndex, MultiIndex, NumericIndex, PeriodIndex, RangeIndex, Series, TimedeltaIndex, isna, ) import pandas._testing as tm from pandas.core.api import ( Float64Index, Int64Index, UInt64Index, ) from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin class Base: _index_cls: type[Index] @pytest.fixture def simple_index(self): raise NotImplementedError("Method not implemented") def create_index(self) -> Index: raise NotImplementedError("Method not implemented") def test_pickle_compat_construction(self): msg = "|".join( [ r"Index\(\.\.\.\) must be called with a collection of some " r"kind, None was passed", r"DatetimeIndex\(\) must be called with a collection of some " r"kind, None was passed", r"TimedeltaIndex\(\) must be called with a collection of some " r"kind, None was passed", r"__new__\(\) missing 1 required positional argument: 'data'", r"__new__\(\) takes at least 2 arguments \(1 given\)", ] ) with pytest.raises(TypeError, match=msg): self._index_cls() @pytest.mark.parametrize("name", [None, "new_name"]) def test_to_frame(self, name, simple_index): idx = simple_index if name: idx_name = name else: idx_name = idx.name or 0 df = idx.to_frame(name=idx_name) assert df.index is idx assert len(df.columns) == 1 assert df.columns[0] == idx_name assert df[idx_name].values is not idx.values df = idx.to_frame(index=False, name=idx_name) assert df.index is not idx def test_shift(self, simple_index): idx = simple_index msg = ( f"This method is only implemented for DatetimeIndex, PeriodIndex and " f"TimedeltaIndex; Got type {type(idx).__name__}" ) with pytest.raises(NotImplementedError, match=msg): idx.shift(1) with pytest.raises(NotImplementedError, match=msg): idx.shift(1, 2) def test_constructor_name_unhashable(self, simple_index): ex with pytest.raises(TypeError, match="Index.name must be a hashable type"): type(idx)(idx, name=[]) def test_create_index_existing_name(self, simple_index): expected = simple_index if not isinstance(expected, MultiIndex): expected.name = "foo" result = Index(expected) tm.assert_index_equal(result, expected) result = Index(expected, name="bar") expected.name = "bar" tm.assert_index_equal(result, expected) else: expected.names = ["foo", "bar"] result = Index(expected) tm.assert_index_equal( result, Index( Index( [ ("foo", "one"), ("foo", "two"), ("bar", "one"), ("baz", "two"), ("qux", "one"), ("qux", "two"), ], dtype="object", ), names=["foo", "bar"], ), ) result = Index(expected, names=["A", "B"]) tm.assert_index_equal( result, Index( Index( [ ("foo", "one"), ("foo", "two"), ("bar", "one"), ("baz", "two"), ("qux", "one"), ("qux", "two"), ], dtype="object", ), names=["A", "B"], ), ) def test_numeric_compat(self, simple_index): idx = simple_index # we can remove multi.test_compat.test_numeric_compat assert not isinstance(idx, MultiIndex) if type(idx) is Index: return typ = type(idx._data).__name__ cls = type(idx).__name__ lmsg = "|".join( [ rf"unsupported operand type\(s\) for \*: '{typ}' and 'int'", "cannot perform (__mul__|__truediv__|__floordiv__) with " f"this index type: ({cls}|{typ})", ] ) with pytest.raises(TypeError, match=lmsg): idx * 1 rmsg = "|".join( [ rf"unsupported operand type\(s\) for \*: 'int' and '{typ}'", "cannot perform (__rmul__|__rtruediv__|__rfloordiv__) with " f"this index type: ({cls}|{typ})", ] ) with pytest.raises(TypeError, match=rmsg): 1 * idx div_err = lmsg.replace("*", "/") with pytest.raises(TypeError, match=div_err): idx / 1 div_err = rmsg.replace("*", "/") with pytest.raises(TypeError, match=div_err): 1 / idx floordiv_err = lmsg.replace("*", "//") with pytest.raises(TypeError, match=floordiv_err): idx // 1 floordiv_err = rmsg.replace("*", "//") with pytest.raises(TypeError, match=floordiv_err): 1 // idx def test_logical_compat(self, simple_index): idx = simple_index with pytest.raises(TypeError, match="cannot perform all"): idx.all() with pytest.raises(TypeError, match="cannot perform any"): idx.any() def test_repr_roundtrip(self, simple_index): idx = simple_index tm.assert_index_equal(eval(repr(idx)), idx) def test_repr_max_seq_item_setting(self, simple_index): # GH10182 idx = simple_index idx = idx.repeat(50) with pd.option_context("display.max_seq_items", None): repr(idx) assert "..." not in str(idx) def test_copy_name(self, index): # gh-12309: Check that the "name" argument # passed at initialization is honored. if isinstance(index, MultiIndex): return first = type(index)(index, copy=True, name="mario") second = type(first)(first, copy=False) # Even though "copy=False", we want a new object. assert first is not second # Not using tm.assert_index_equal() since names differ. assert index.equals(first) assert first.name == "mario" assert second.name == "mario" s1 = Series(2, index=first) s2 = Series(3, index=second[:-1]) if not isinstance(index, CategoricalIndex): # See gh-13365 s3 = s1 * s2 assert s3.index.name == "mario" def test_copy_name2(self, index): # gh-35592 if isinstance(index, MultiIndex): return assert index.copy(name="mario").name == "mario" with pytest.raises(ValueError, match="Length of new names must be 1, got 2"): index.copy(name=["mario", "luigi"]) msg = f"{type(index).__name__}.name must be a hashable type" with pytest.raises(TypeError, match=msg): index.copy(name=[["mario"]]) def test_ensure_copied_data(self, index): # Check the "copy" argument of each Index.__new__ is honoured # GH12309 init_kwargs = {} if isinstance(index, PeriodIndex): # Needs "freq" specification: init_kwargs["freq"] = index.freq elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)): # RangeIndex cannot be initialized from data # MultiIndex and CategoricalIndex are tested separately return index_type = type(index) result = index_type(index.values, copy=True, **init_kwargs) if is_datetime64tz_dtype(index.dtype): result = result.tz_localize("UTC").tz_convert(index.tz) if isinstance(index, (DatetimeIndex, TimedeltaIndex)): index = index._with_freq(None) tm.assert_index_equal(index, result) if isinstance(index, PeriodIndex): # .values an object array of Period, thus copied result = index_type(ordinal=index.asi8, copy=False, **init_kwargs) tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same") elif isinstance(index, IntervalIndex): # checked in test_interval.py pass else: result = index_type(index.values, copy=False, **init_kwargs) tm.assert_numpy_array_equal(index.values, result.values, check_same="same") def test_memory_usage(self, index): index._engine.clear_mapping() result = index.memory_usage() if index.empty: # we report 0 for no-length assert result == 0 return # non-zero length index.get_loc(index[0]) result2 = index.memory_usage() result3 = index.memory_usage(deep=True) # RangeIndex, IntervalIndex # don't have engines if not isinstance(index, (RangeIndex, IntervalIndex)): assert result2 > result if index.inferred_type == "object": assert result3 > result2 def test_argsort(self, request, index): if isinstance(index, CategoricalIndex): return result = index.argsort() expected = np.array(index).argsort() tm.assert_numpy_array_equal(result, expected, check_dtype=False) def test_numpy_argsort(self, index): result = np.argsort(index) expected = index.argsort() tm.assert_numpy_array_equal(result, expected) if isinstance(type(index), (CategoricalIndex, RangeIndex)): msg = "the 'axis' parameter is not supported" with pytest.raises(ValueError, match=msg): np.argsort(index, axis=1) msg = "the 'kind' parameter is not supported" with pytest.raises(ValueError, match=msg): np.argsort(index, kind="mergesort") msg = "the 'order' parameter is not supported" with pytest.raises(ValueError, match=msg): np.argsort(index, order=("a", "b")) def test_repeat(self, simple_index): rep = 2 idx = simple_index.copy() new_index_cls = Int64Index if isinstance(idx, RangeIndex) else idx._constructor expected = new_index_cls(idx.values.repeat(rep), name=idx.name) tm.assert_index_equal(idx.repeat(rep), expected) idx = simple_index rep = np.arange(len(idx)) expected = new_index_cls(idx.values.repeat(rep), name=idx.name) tm.assert_index_equal(idx.repeat(rep), expected) def test_numpy_repeat(self, simple_index): rep = 2 idx = simple_index expected = idx.repeat(rep) tm.assert_index_equal(np.repeat(idx, rep), expected) msg = "the 'axis' parameter is not supported" with pytest.raises(ValueError, match=msg): np.repeat(idx, rep, axis=0) def test_where(self, listlike_box_with_tuple, simple_index): klass = listlike_box_with_tuple idx = simple_index if isinstance(idx, (DatetimeIndex, TimedeltaIndex)): idx = idx._with_freq(None) cond = [True] * len(idx) result = idx.where(klass(cond)) expected = idx tm.assert_index_equal(result, expected) cond = [False] + [True] * len(idx[1:]) expected = Index([idx._na_value] + idx[1:].tolist(), dtype=idx.dtype) result = idx.where(klass(cond)) tm.assert_index_equal(result, expected) def test_insert_base(self, index): result = index[1:4] if not len(index): return assert index[0:4].equals(result.insert(0, index[0])) def test_delete_base(self, index): if not len(index): return if isinstance(index, RangeIndex): return expected = index[1:] result = index.delete(0) assert result.equals(expected) assert result.name == expected.name expected = index[:-1] result = index.delete(-1) assert result.equals(expected) assert result.name == expected.name length = len(index) msg = f"index {length} is out of bounds for axis 0 with size {length}" with pytest.raises(IndexError, match=msg): index.delete(length) def test_equals(self, index): if isinstance(index, IntervalIndex): return assert index.equals(index) assert index.equals(index.copy()) assert index.equals(index.astype(object)) assert not index.equals(list(index)) assert not index.equals(np.array(index)) if not isinstance(index, RangeIndex): same_values = Index(index, dtype=object) assert index.equals(same_values) assert same_values.equals(index) if index.nlevels == 1: assert not index.equals(Series(index)) def test_equals_op(self, simple_index): index_a = simple_index n = len(index_a) index_b = index_a[0:-1] index_c = index_a[0:-1].append(index_a[-2:-1]) index_d = index_a[0:1] msg = "Lengths must match|could not be broadcast" with pytest.raises(ValueError, match=msg): index_a == index_b expected1 = np.array([True] * n) expected2 = np.array([True] * (n - 1) + [False]) tm.assert_numpy_array_equal(index_a == index_a, expected1) tm.assert_numpy_array_equal(index_a == index_c, expected2) array_a = np.array(index_a) array_b = np.array(index_a[0:-1]) array_c = np.array(index_a[0:-1].append(index_a[-2:-1])) array_d = np.array(index_a[0:1]) with pytest.raises(ValueError, match=msg): index_a == array_b tm.assert_numpy_array_equal(index_a == array_a, expected1) tm.assert_numpy_array_equal(index_a == array_c, expected2) series_a = Series(array_a) series_b = Series(array_b) series_c = Series(array_c) series_d = Series(array_d) with pytest.raises(ValueError, match=msg): index_a == series_b tm.assert_numpy_array_equal(index_a == series_a, expected1) tm.assert_numpy_array_equal(index_a == series_c, expected2) with pytest.raises(ValueError, match="Lengths must match"): index_a == index_d with pytest.raises(ValueError, match="Lengths must match"): index_a == series_d with pytest.raises(ValueError, match="Lengths must match"): index_a == array_d msg = "Can only compare identically-labeled Series objects" with pytest.raises(ValueError, match=msg): series_a == series_d with pytest.raises(ValueError, match="Lengths must match"): series_a == array_d if not isinstance(index_a, MultiIndex): expected3 = np.array([False] * (len(index_a) - 2) + [True, False]) item = index_a[-2] tm.assert_numpy_array_equal(index_a == item, expected3) tm.assert_series_equal(series_a == item, Series(expected3)) def test_format(self, simple_index): idx = simple_index expected = [str(x) for x in idx] assert idx.format() == expected def test_format_empty(self): empty_idx = self._index_cls([]) assert empty_idx.format() == [] assert empty_idx.format(name=True) == [""] def test_fillna(self, index): if len(index) == 0: return elif isinstance(index, NumericIndex) and is_integer_dtype(index.dtype): return elif isinstance(index, MultiIndex): idx = index.copy(deep=True) msg = "isna is not defined for MultiIndex" with pytest.raises(NotImplementedError, match=msg): idx.fillna(idx[0]) else: idx = index.copy(deep=True) result = idx.fillna(idx[0]) tm.assert_index_equal(result, idx) assert result is not idx msg = "'value' must be a scalar, passed: " with pytest.raises(TypeError, match=msg): idx.fillna([idx[0]]) idx = index.copy(deep=True) values = np.asarray(idx.values) if isinstance(index, DatetimeIndexOpsMixin): values[1] = iNaT else: values[1] = np.nan if isinstance(index, PeriodIndex): idx = type(index)(values, freq=index.freq) else: idx = type(index)(values) expected = np.array([False] * len(idx), dtype=bool) expected[1] = True tm.assert_numpy_array_equal(idx._isnan, expected) assert idx.hasnans is True def test_nulls(self, index): if len(index) == 0: tm.assert_numpy_array_equal(index.isna(), np.array([], dtype=bool)) elif isinstance(index, MultiIndex): idx = index.copy() msg = "isna is not defined for MultiIndex" with pytest.raises(NotImplementedError, match=msg): idx.isna() elif not index.hasnans: tm.assert_numpy_array_equal(index.isna(), np.zeros(len(index), dtype=bool)) tm.assert_numpy_array_equal(index.notna(), np.ones(len(index), dtype=bool)) else: result = isna(index) tm.assert_numpy_array_equal(index.isna(), result) tm.assert_numpy_array_equal(index.notna(), ~result) def test_empty(self, simple_index): idx = simple_index assert not idx.empty assert idx[:0].empty def test_join_self_unique(self, join_type, simple_index): idx = simple_index if idx.is_unique: joined = idx.join(idx, how=join_type) assert (idx == joined).all() def test_map(self, simple_index): idx = simple_index if is_integer_dtype(idx.dtype): expected = idx.astype("int64") elif is_float_dtype(idx.dtype): expected = idx.astype("float64") if idx._is_backward_compat_public_numeric_index: # We get a NumericIndex back, not Float64Index expected = type(idx)(expected) else: expected = idx result = idx.map(lambda x: x) # For RangeIndex we convert to Int64Index tm.assert_index_equal(result, expected, exact="equiv") @pytest.mark.parametrize( "mapper", [ lambda values, index: {i: e for e, i in zip(values, index)}, lambda values, index: Series(values, index), ], ) def test_map_dictlike(self, mapper, simple_index): idx = simple_index if isinstance(idx, CategoricalIndex): pytest.skip(f"skipping tests for {type(idx)}") identity = mapper(idx.values, idx) # we don't infer to UInt64 for a dict if is_unsigned_integer_dtype(idx.dtype) and isinstance(identity, dict): expected = idx.astype("int64") else: expected = idx result = idx.map(identity) tm.assert_index_equal(result, expected, exact="equiv") if idx._is_backward_compat_public_numeric_index: new_index_cls = NumericIndex else: new_index_cls = Float64Index expected = new_index_cls([np.nan] * len(idx)) result = idx.map(mapper(expected, idx)) tm.assert_index_equal(result, expected) def test_map_str(self, simple_index): idx = simple_index result = idx.map(str) expected = Index([str(x) for x in idx], dtype=object) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("copy", [True, False]) @pytest.mark.parametrize("name", [None, "foo"]) @pytest.mark.parametrize("ordered", [True, False]) def test_astype_category(self, copy, name, ordered, simple_index): idx = simple_index if name: idx = idx.rename(name) dtype = CategoricalDtype(ordered=ordered) result = idx.astype(dtype, copy=copy) expected = CategoricalIndex(idx, name=name, ordered=ordered) tm.assert_index_equal(result, expected, exact=True) dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered) result = idx.astype(dtype, copy=copy) expected = CategoricalIndex(idx, name=name, dtype=dtype) tm.assert_index_equal(result, expected, exact=True) if ordered is False: result = idx.astype("category", copy=copy) expected = CategoricalIndex(idx, name=name) tm.assert_index_equal(result, expected, exact=True) def test_is_unique(self, simple_index): index = simple_index.drop_duplicates() assert index.is_unique is True index_empty = index[:0] assert index_empty.is_unique is True index_dup = index.insert(0, index[0]) assert index_dup.is_unique is False index_na = index.insert(0, np.nan) assert index_na.is_unique is True index_na_dup = index_na.insert(0, np.nan) assert index_na_dup.is_unique is False @pytest.mark.arm_slow def test_engine_reference_cycle(self, simple_index): index = simple_index nrefs_pre = len(gc.get_referrers(index)) index._engine assert len(gc.get_referrers(index)) == nrefs_pre def test_getitem_2d_deprecated(self, simple_index): index msg = "Support for multi-dimensional indexing" with tm.assert_produces_warning(FutureWarning, match=msg): res = idx[:, None] assert isinstance(res, np.ndarray), type(res) def test_copy_shares_cache(self, simple_index): idx = simple_index idx.get_loc(idx[0]) copy = idx.copy() assert copy._cache is idx._cache def test_shallow_copy_shares_cache(self, simple_index): idx = simple_index idx.get_loc(idx[0]) shallow_copy = idx._view() assert shallow_copy._cache is idx._cache shallow_copy = idx._shallow_copy(idx._data) assert shallow_copy._cache is not idx._cache assert shallow_copy._cache == {} def test_index_groupby(self, simple_index): idx = simple_index[:5] to_groupby = np.array([1, 2, np.nan, 2, 1]) tm.assert_dict_equal( idx.groupby(to_groupby), {1.0: idx[[0, 4]], 2.0: idx[[1, 3]]} ) to_groupby = DatetimeIndex( [ datetime(2011, 11, 1), datetime(2011, 12, 1), pd.NaT, datetime(2011, 12, 1), datetime(2011, 11, 1), ], tz="UTC", ).values ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")] expected = {ex_keys[0]: idx[[0, 4]], ex_keys[1]: idx[[1, 3]]} tm.assert_dict_equal(idx.groupby(to_groupby), expected) def test_append_preserves_dtype(self, simple_index): index = simple_index N = len(index) result = index.append(index) assert result.dtype == index.dtype tm.assert_index_equal(result[:N], index, check_exact=True) tm.assert_index_equal(result[N:], index, check_exact=True) alt = index.take(list(range(N)) * 2) tm.assert_index_equal(result, alt, check_exact=True) class NumericBase(Base): def test_constructor_unwraps_index(self, dtype): index_cls = self._index_cls idx = Index([1, 2], dtype=dtype) result = index_cls(idx) expected = np.array([1, 2], dtype=idx.dtype) tm.assert_numpy_array_equal(result._data, expected) def test_where(self): pass def test_can_hold_identifiers(self, simple_index): idx = simple_index key = idx[0] assert idx._can_hold_identifiers_and_holds_name(key) is False def test_format(self, simple_index): idx = simple_index max_width = max(len(str(x)) for x in idx) expected = [str(x).ljust(max_width) for x in idx] assert idx.format() == expected def test_numeric_compat(self): pass def test_insert_non_na(self, simple_index): dex.insert(0, index[0]) cls = type(index) if cls is RangeIndex: cls = Int64Index expected = cls([index[0]] + list(index), dtype=index.dtype) tm.assert_index_equal(result, expected, exact=True) def test_insert_na(self, nulls_fixture, simple_index): index = simple_index na_val = nulls_fixture if na_val is pd.NaT: expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object) else: expected = Float64Index([index[0], np.nan] + list(index[1:])) if index._is_backward_compat_public_numeric_index: .kind == "f": expected = NumericIndex(expected, dtype=index.dtype) else: expected = NumericIndex(expected) result = index.insert(1, na_val) tm.assert_index_equal(result, expected, exact=True) def test_arithmetic_explicit_conversions(self): index_cls = self._index_cls if index_cls is RangeIndex: idx = RangeIndex(5) else: idx = index_cls(np.arange(5, dtype="int64")) arr = np.arange(5, dtype="int64") * 3.2 expected = Float64Index(arr) fidx = idx * 3.2 tm.assert_index_equal(fidx, expected) fidx = 3.2 * idx tm.assert_index_equal(fidx, expected) expected = Float64Index(arr) a = np.zeros(5, dtype="float64") result = fidx - a tm.assert_index_equal(result, expected) expected = Float64Index(-arr) a = np.zeros(5, dtype="float64") result = a - fidx tm.assert_index_equal(result, expected) def test_invalid_dtype(self, invalid_dtype): dtype = invalid_dtype msg = fr"Incorrect `dtype` passed: expected \w+(?: \w+)?, received {dtype}" with pytest.raises(ValueError, match=msg): self._index_cls([1, 2, 3], dtype=dtype)
true
true
1c3739e1c8ab202fd3a8ed769921786390cfedfc
1,735
py
Python
ingenico/direct/sdk/domain/payment_product130_specific_input.py
Ingenico/direct-sdk-python3
d2b30b8e8afb307153a1f19ac4c054d5344449ce
[ "Apache-2.0" ]
null
null
null
ingenico/direct/sdk/domain/payment_product130_specific_input.py
Ingenico/direct-sdk-python3
d2b30b8e8afb307153a1f19ac4c054d5344449ce
[ "Apache-2.0" ]
1
2021-03-30T12:55:39.000Z
2021-04-08T08:23:27.000Z
ingenico/direct/sdk/domain/payment_product130_specific_input.py
Ingenico/direct-sdk-python3
d2b30b8e8afb307153a1f19ac4c054d5344449ce
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # This class was auto-generated from the API references found at # https://support.direct.ingenico.com/documentation/api/reference/ # from ingenico.direct.sdk.data_object import DataObject from ingenico.direct.sdk.domain.payment_product130_specific_three_d_secure import PaymentProduct130SpecificThreeDSecure class PaymentProduct130SpecificInput(DataObject): """ | Object containing specific input required for CB payments """ __three_d_secure = None @property def three_d_secure(self) -> PaymentProduct130SpecificThreeDSecure: """ | Object containing specific data regarding 3-D Secure Type: :class:`ingenico.direct.sdk.domain.payment_product130_specific_three_d_secure.PaymentProduct130SpecificThreeDSecure` """ return self.__three_d_secure @three_d_secure.setter def three_d_secure(self, value: PaymentProduct130SpecificThreeDSecure): self.__three_d_secure = value def to_dictionary(self): dictionary = super(PaymentProduct130SpecificInput, self).to_dictionary() if self.three_d_secure is not None: dictionary['threeDSecure'] = self.three_d_secure.to_dictionary() return dictionary def from_dictionary(self, dictionary): super(PaymentProduct130SpecificInput, self).from_dictionary(dictionary) if 'threeDSecure' in dictionary: if not isinstance(dictionary['threeDSecure'], dict): raise TypeError('value \'{}\' is not a dictionary'.format(dictionary['threeDSecure'])) value = PaymentProduct130SpecificThreeDSecure() self.three_d_secure = value.from_dictionary(dictionary['threeDSecure']) return self
39.431818
130
0.729107
from ingenico.direct.sdk.data_object import DataObject from ingenico.direct.sdk.domain.payment_product130_specific_three_d_secure import PaymentProduct130SpecificThreeDSecure class PaymentProduct130SpecificInput(DataObject): __three_d_secure = None @property def three_d_secure(self) -> PaymentProduct130SpecificThreeDSecure: return self.__three_d_secure @three_d_secure.setter def three_d_secure(self, value: PaymentProduct130SpecificThreeDSecure): self.__three_d_secure = value def to_dictionary(self): dictionary = super(PaymentProduct130SpecificInput, self).to_dictionary() if self.three_d_secure is not None: dictionary['threeDSecure'] = self.three_d_secure.to_dictionary() return dictionary def from_dictionary(self, dictionary): super(PaymentProduct130SpecificInput, self).from_dictionary(dictionary) if 'threeDSecure' in dictionary: if not isinstance(dictionary['threeDSecure'], dict): raise TypeError('value \'{}\' is not a dictionary'.format(dictionary['threeDSecure'])) value = PaymentProduct130SpecificThreeDSecure() self.three_d_secure = value.from_dictionary(dictionary['threeDSecure']) return self
true
true
1c373a77661fe261e373800cefead053054ae721
1,067
py
Python
src/peopleapp/admin.py
robertsmoto/sodavault
200e843be7abe6cc447647bba55c7c1309092e5e
[ "BSD-3-Clause" ]
null
null
null
src/peopleapp/admin.py
robertsmoto/sodavault
200e843be7abe6cc447647bba55c7c1309092e5e
[ "BSD-3-Clause" ]
null
null
null
src/peopleapp/admin.py
robertsmoto/sodavault
200e843be7abe6cc447647bba55c7c1309092e5e
[ "BSD-3-Clause" ]
null
null
null
from django.contrib import admin # from .models import Company, Person # class PersonInline(admin.StackedInline): # model = Person # # fields = [ # # ('gtin', 'isbn'), # # ('pid_i', 'pid_c') # # ] # extra = 0 # verbose_name = "people" # @admin.register(Person) # class PersonAdmin(admin.ModelAdmin): # verbose_name = "people" # @admin.register(Company) # class CategoryAdmin(admin.ModelAdmin): # # list_display = [ # # 'name', # # 'parent', # # 'slug', # # ] # # ordering = [ # # '-slug', # # 'name' # # ] # # list_display_links = [ # # 'name', # # ] # # list_filter = [ # # 'parent', # # ] # search_fields = ['name'] # # fields = [ # # 'parent', # # 'name', # # 'slug' # # ] # # prepopulated_fields = {'slug': ('name',)} # # autocomplete_fields = ['parent'] # inlines = [PersonInline,] # verbose_name = "companies"
21.34
81
0.451734
from django.contrib import admin
true
true
1c373a83cf29a9784f9977e93c516c30db74deb6
4,674
py
Python
src/linakdeskapp/gui/mpl/position_chart.py
nilp0inter/LinakDeskApp
0cf287ee96002f5c270c087ba73b72c548baa8c5
[ "MIT" ]
121
2018-09-19T20:10:21.000Z
2022-03-31T08:07:33.000Z
src/linakdeskapp/gui/mpl/position_chart.py
nilp0inter/LinakDeskApp
0cf287ee96002f5c270c087ba73b72c548baa8c5
[ "MIT" ]
13
2020-02-19T15:58:37.000Z
2022-03-05T03:20:42.000Z
src/linakdeskapp/gui/mpl/position_chart.py
nilp0inter/LinakDeskApp
0cf287ee96002f5c270c087ba73b72c548baa8c5
[ "MIT" ]
12
2020-02-13T23:55:30.000Z
2022-01-30T15:11:31.000Z
# MIT License # # Copyright (c) 2017 Arkadiusz Netczuk <dev.arnet@gmail.com> # # 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 logging try: import pandas except ImportError: ### No module named <name> logging.exception("Exception while importing") exit(1) from .mpl_canvas import matplotlib, DynamicMplCanvas _LOGGER = logging.getLogger(__name__) class PositionChart(DynamicMplCanvas): def __init__(self, parentWidget=None): super().__init__(parentWidget, 10, 10, 80) self.xdata = list() self.ydata = list() linesList = self.plot.plot_date( self.xdata, self.ydata, 'r', linewidth=3, antialiased=True) self.line = linesList[0] # self.fig.suptitle('Desk position', y=0.95, fontsize=18) self.plot.set_xlabel('Time', fontsize=14) self.plot.set_ylabel('Height', fontsize=14) formatter = matplotlib.dates.DateFormatter('%H:%M:%S') self.plot.xaxis.set_major_formatter( formatter ) self.plot.margins( y=0.2 ) self.plot.set_xmargin(0.0) ## prevents empty space between first tick and y axis # rotates and right aligns the x labels, and moves the bottom of the # axes up to make room for them self.fig.autofmt_xdate() self._set_plot_data() def addData(self, deskHeight): currTime = self.getCurrTime() self.xdata.append(currTime) self.ydata.append(deskHeight) self._set_plot_data() def clearData(self): self.xdata.clear() self.ydata.clear() self._set_plot_data() def updateData(self): yLen = len(self.ydata) if yLen < 1: ## no data - nothing to do return False last = self.ydata[-1] if yLen < 2: ## only one value self.addData( last ) return True ## two or more values last2 = self.ydata[-2] if last != last2: self.addData( last ) return True self.xdata[-1] = self.getCurrTime() self._set_plot_data() return True def getCurrTime(self): currTime = pandas.Timestamp.now() return currTime def _set_plot_data(self): if len(self.xdata) < 2: return self.line.set_xdata( self.xdata ) self.line.set_ydata( self.ydata ) ticks = self._generate_ticks(12) self.plot.set_xticks( ticks ) ### hide first and last major tick (next to plot edges) xticks = self.plot.xaxis.get_major_ticks() xticks[0].label1.set_visible(False) ##xticks[-1].label1.set_visible(False) self.plot.relim(True) self.plot.autoscale_view() self.fig.tight_layout() ## make space for labels of axis # self.fig.subplots_adjust(top=0.82) ## make space for suptitle def _generate_ticks(self, number): if number < 1: return list() start = self.xdata[0].timestamp() tzoffset = start - pandas.Timestamp( start, unit="s" ).timestamp() if number < 2: middle = (start + self.xdata[-1].timestamp()) / 2 + tzoffset ts = pandas.Timestamp( middle, unit="s" ) ticks = [ts] return ticks delta = (self.xdata[-1].timestamp() - start) / (number - 1) ticks = list() ticks.append( self.xdata[0] ) currTs = start + tzoffset for _ in range(1, number): currTs += delta ts = pandas.Timestamp( currTs, unit="s" ) ticks.append( ts ) return ticks
32.915493
93
0.624519
import logging try: import pandas except ImportError: ") exit(1) from .mpl_canvas import matplotlib, DynamicMplCanvas _LOGGER = logging.getLogger(__name__) class PositionChart(DynamicMplCanvas): def __init__(self, parentWidget=None): super().__init__(parentWidget, 10, 10, 80) self.xdata = list() self.ydata = list() linesList = self.plot.plot_date( self.xdata, self.ydata, 'r', linewidth=3, antialiased=True) self.line = linesList[0] self.plot.set_xlabel('Time', fontsize=14) self.plot.set_ylabel('Height', fontsize=14) formatter = matplotlib.dates.DateFormatter('%H:%M:%S') self.plot.xaxis.set_major_formatter( formatter ) self.plot.margins( y=0.2 ) self.plot.set_xmargin(0.0) self._set_plot_data() def addData(self, deskHeight): currTime = self.getCurrTime() self.xdata.append(currTime) self.ydata.append(deskHeight) self._set_plot_data() def clearData(self): self.xdata.clear() self.ydata.clear() self._set_plot_data() def updateData(self): yLen = len(self.ydata) if yLen < 1: last = self.ydata[-1] if yLen < 2: f.addData( last ) return True f.ydata[-2] if last != last2: self.addData( last ) return True self.xdata[-1] = self.getCurrTime() self._set_plot_data() return True def getCurrTime(self): currTime = pandas.Timestamp.now() return currTime def _set_plot_data(self): if len(self.xdata) < 2: return self.line.set_xdata( self.xdata ) self.line.set_ydata( self.ydata ) ticks = self._generate_ticks(12) self.plot.set_xticks( ticks ) self.plot.autoscale_view() self.fig.tight_layout() n list() start = self.xdata[0].timestamp() tzoffset = start - pandas.Timestamp( start, unit="s" ).timestamp() if number < 2: middle = (start + self.xdata[-1].timestamp()) / 2 + tzoffset ts = pandas.Timestamp( middle, unit="s" ) ticks = [ts] return ticks delta = (self.xdata[-1].timestamp() - start) / (number - 1) ticks = list() ticks.append( self.xdata[0] ) currTs = start + tzoffset for _ in range(1, number): currTs += delta ts = pandas.Timestamp( currTs, unit="s" ) ticks.append( ts ) return ticks
true
true
1c373b8d3ccf35c4f9a5a0b930c514b21d09ee44
7,468
py
Python
tf_impl/train_SANNE.py
daiquocnguyen/Walk-Transformer
dc234811dc61bb4d1df7e2d0960be776e2a2b2ac
[ "Apache-2.0" ]
22
2020-06-08T16:23:00.000Z
2021-11-10T11:13:18.000Z
tf_impl/train_SANNE.py
daiquocnguyen/Node-Transformer
dc234811dc61bb4d1df7e2d0960be776e2a2b2ac
[ "Apache-2.0" ]
1
2021-01-24T15:11:23.000Z
2021-01-24T15:11:23.000Z
tf_impl/train_SANNE.py
daiquocnguyen/Node-Transformer
dc234811dc61bb4d1df7e2d0960be776e2a2b2ac
[ "Apache-2.0" ]
5
2020-06-09T08:03:35.000Z
2021-09-28T11:14:06.000Z
#! /usr/bin/env python import tensorflow as tf import numpy as np import os import time import datetime from model_SANNE_squash import SANNE import pickle as cPickle from utils import * from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter np.random.seed(123456789) tf.set_random_seed(123456789) # Parameters # ================================================== parser = ArgumentParser("SANNE", formatter_class=ArgumentDefaultsHelpFormatter, conflict_handler='resolve') parser.add_argument("--data", default="../graph/", help="Data sources.") parser.add_argument("--run_folder", default="../", help="") parser.add_argument("--name", default="cora.128.8.trans.pickle", help="Name of the dataset.") parser.add_argument("--embedding_dim", default=4, type=int, help="Dimensionality of character embedding") parser.add_argument("--learning_rate", default=0.0001, type=float, help="Learning rate") parser.add_argument("--batch_size", default=8, type=int, help="Batch Size") parser.add_argument("--idx_time", default=1, type=int, help="") parser.add_argument("--num_epochs", default=50, type=int, help="Number of training epochs") parser.add_argument("--saveStep", default=1, type=int, help="") parser.add_argument("--allow_soft_placement", default=True, type=bool, help="Allow device soft device placement") parser.add_argument("--log_device_placement", default=False, type=bool, help="Log placement of ops on devices") parser.add_argument("--model_name", default='cora_trans', help="") parser.add_argument("--useInductive", action='store_true') parser.add_argument('--num_sampled', default=32, type=int, help='') parser.add_argument("--is_trainable", default=False, type=bool, help="") parser.add_argument("--write_file", default='cora', help="") parser.add_argument("--dropout_keep_prob", default=1.0, type=float, help="Dropout keep probability") parser.add_argument("--num_hidden_layers", default=4, type=int, help="Number of attention layers") parser.add_argument("--num_heads", default=4, type=int, help="Number of attention heads within each attention layer") parser.add_argument("--ff_hidden_size", default=1024, type=int, help="The hidden size for the feedforward layer") parser.add_argument("--num_neighbors", default=4, type=int, help="") parser.add_argument("--use_pos", default=1, type=int, help="0 when not using positional embeddings. Otherwise.") args = parser.parse_args() print(args) class Batch_Loader_RW(object): def __init__(self, walks): self.walks = walks self.data_size = len(self.walks) self.sequence_length = np.shape(self.walks)[1] self.check() self.getNeighbors() def __call__(self): idxs = np.random.randint(0, self.data_size, args.batch_size) arrY = [] for walk in self.walks[idxs]: for tmpNode in walk: arrY.append(np.random.choice(self.fullGraph[tmpNode], args.num_neighbors, replace=True)) return self.walks[idxs], np.reshape(np.array(arrY), (args.num_neighbors*self.sequence_length*args.batch_size, -1)) def check(self): _dict = set() for walk in self.walks: for tmp in walk: if tmp not in _dict: _dict.add(int(tmp)) self._dict = _dict def getNeighbors(self): self.fullGraph = {} with open('../data/' + str(args.name).split('.')[0] + '.Full.edgelist', 'r') as f: for line in f: tmpNodes = line.strip().split() if len(tmpNodes) == 2: if int(tmpNodes[0]) not in self.fullGraph: self.fullGraph[int(tmpNodes[0])] = [] self.fullGraph[int(tmpNodes[0])].append(int(tmpNodes[1])) # Load data print("Loading data...") with open(args.data + args.name, 'rb') as f: walks = cPickle.load(f) batch_rw = Batch_Loader_RW(walks) #cora,citeseer,pubmed with open('../data/' + str(args.name).split('.')[0] + '.128d.feature.pickle', 'rb') as f: features_matrix = cPickle.load(f) feature_dim_size = features_matrix.shape[1] vocab_size = features_matrix.shape[0] print("Loading data... finished!") # Training # ================================================== with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=args.allow_soft_placement, log_device_placement=args.log_device_placement) session_conf.gpu_options.allow_growth = True sess = tf.Session(config=session_conf) with sess.as_default(): global_step = tf.Variable(0, name="global_step", trainable=False) selfG = SANNE(sequence_length=batch_rw.sequence_length, num_hidden_layers=args.num_hidden_layers, vocab_size=vocab_size, batch_size=args.batch_size, num_sampled=args.num_sampled, initialization=features_matrix, feature_dim_size=feature_dim_size, num_heads=args.num_heads, ff_hidden_size=args.ff_hidden_size, num_neighbors=args.num_neighbors, use_pos=args.use_pos ) # Define Training procedure optimizer = tf.train.AdamOptimizer(learning_rate=args.learning_rate) grads_and_vars = optimizer.compute_gradients(selfG.total_loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) out_dir = os.path.abspath(os.path.join(args.run_folder, "runs_SANNE_trans", args.model_name)) print("Writing to {}\n".format(out_dir)) # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) # Initialize all variables sess.run(tf.global_variables_initializer()) graph = tf.get_default_graph() def train_step(x_batch, y_batch): """ A single training step """ feed_dict = { selfG.input_x: x_batch, selfG.input_y: y_batch, selfG.dropout_keep_prob: args.dropout_keep_prob } _, step, loss = sess.run([train_op, global_step, selfG.total_loss], feed_dict) return loss num_batches_per_epoch = int((batch_rw.data_size - 1) / args.batch_size) + 1 for epoch in range(1, args.num_epochs+1): loss = 0 for batch_num in range(num_batches_per_epoch): x_batch, y_batch = batch_rw() loss += train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) #print(loss) if epoch % args.saveStep == 0: # It will give tensor object embeddingW = graph.get_tensor_by_name('W:0') # To get the value (numpy array) embeddingW_value = sess.run(embeddingW) with open(checkpoint_prefix + '-' + str(epoch), 'wb') as f: cPickle.dump(embeddingW_value, f) # cPickle.dump(embeddings_rw, f) print("Save embeddings to {}\n".format(checkpoint_prefix + '-' + str(epoch)))
44.718563
129
0.63819
import tensorflow as tf import numpy as np import os import time import datetime from model_SANNE_squash import SANNE import pickle as cPickle from utils import * from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter np.random.seed(123456789) tf.set_random_seed(123456789) parser = ArgumentParser("SANNE", formatter_class=ArgumentDefaultsHelpFormatter, conflict_handler='resolve') parser.add_argument("--data", default="../graph/", help="Data sources.") parser.add_argument("--run_folder", default="../", help="") parser.add_argument("--name", default="cora.128.8.trans.pickle", help="Name of the dataset.") parser.add_argument("--embedding_dim", default=4, type=int, help="Dimensionality of character embedding") parser.add_argument("--learning_rate", default=0.0001, type=float, help="Learning rate") parser.add_argument("--batch_size", default=8, type=int, help="Batch Size") parser.add_argument("--idx_time", default=1, type=int, help="") parser.add_argument("--num_epochs", default=50, type=int, help="Number of training epochs") parser.add_argument("--saveStep", default=1, type=int, help="") parser.add_argument("--allow_soft_placement", default=True, type=bool, help="Allow device soft device placement") parser.add_argument("--log_device_placement", default=False, type=bool, help="Log placement of ops on devices") parser.add_argument("--model_name", default='cora_trans', help="") parser.add_argument("--useInductive", action='store_true') parser.add_argument('--num_sampled', default=32, type=int, help='') parser.add_argument("--is_trainable", default=False, type=bool, help="") parser.add_argument("--write_file", default='cora', help="") parser.add_argument("--dropout_keep_prob", default=1.0, type=float, help="Dropout keep probability") parser.add_argument("--num_hidden_layers", default=4, type=int, help="Number of attention layers") parser.add_argument("--num_heads", default=4, type=int, help="Number of attention heads within each attention layer") parser.add_argument("--ff_hidden_size", default=1024, type=int, help="The hidden size for the feedforward layer") parser.add_argument("--num_neighbors", default=4, type=int, help="") parser.add_argument("--use_pos", default=1, type=int, help="0 when not using positional embeddings. Otherwise.") args = parser.parse_args() print(args) class Batch_Loader_RW(object): def __init__(self, walks): self.walks = walks self.data_size = len(self.walks) self.sequence_length = np.shape(self.walks)[1] self.check() self.getNeighbors() def __call__(self): idxs = np.random.randint(0, self.data_size, args.batch_size) arrY = [] for walk in self.walks[idxs]: for tmpNode in walk: arrY.append(np.random.choice(self.fullGraph[tmpNode], args.num_neighbors, replace=True)) return self.walks[idxs], np.reshape(np.array(arrY), (args.num_neighbors*self.sequence_length*args.batch_size, -1)) def check(self): _dict = set() for walk in self.walks: for tmp in walk: if tmp not in _dict: _dict.add(int(tmp)) self._dict = _dict def getNeighbors(self): self.fullGraph = {} with open('../data/' + str(args.name).split('.')[0] + '.Full.edgelist', 'r') as f: for line in f: tmpNodes = line.strip().split() if len(tmpNodes) == 2: if int(tmpNodes[0]) not in self.fullGraph: self.fullGraph[int(tmpNodes[0])] = [] self.fullGraph[int(tmpNodes[0])].append(int(tmpNodes[1])) print("Loading data...") with open(args.data + args.name, 'rb') as f: walks = cPickle.load(f) batch_rw = Batch_Loader_RW(walks) with open('../data/' + str(args.name).split('.')[0] + '.128d.feature.pickle', 'rb') as f: features_matrix = cPickle.load(f) feature_dim_size = features_matrix.shape[1] vocab_size = features_matrix.shape[0] print("Loading data... finished!") with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=args.allow_soft_placement, log_device_placement=args.log_device_placement) session_conf.gpu_options.allow_growth = True sess = tf.Session(config=session_conf) with sess.as_default(): global_step = tf.Variable(0, name="global_step", trainable=False) selfG = SANNE(sequence_length=batch_rw.sequence_length, num_hidden_layers=args.num_hidden_layers, vocab_size=vocab_size, batch_size=args.batch_size, num_sampled=args.num_sampled, initialization=features_matrix, feature_dim_size=feature_dim_size, num_heads=args.num_heads, ff_hidden_size=args.ff_hidden_size, num_neighbors=args.num_neighbors, use_pos=args.use_pos ) optimizer = tf.train.AdamOptimizer(learning_rate=args.learning_rate) grads_and_vars = optimizer.compute_gradients(selfG.total_loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) out_dir = os.path.abspath(os.path.join(args.run_folder, "runs_SANNE_trans", args.model_name)) print("Writing to {}\n".format(out_dir)) checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) sess.run(tf.global_variables_initializer()) graph = tf.get_default_graph() def train_step(x_batch, y_batch): feed_dict = { selfG.input_x: x_batch, selfG.input_y: y_batch, selfG.dropout_keep_prob: args.dropout_keep_prob } _, step, loss = sess.run([train_op, global_step, selfG.total_loss], feed_dict) return loss num_batches_per_epoch = int((batch_rw.data_size - 1) / args.batch_size) + 1 for epoch in range(1, args.num_epochs+1): loss = 0 for batch_num in range(num_batches_per_epoch): x_batch, y_batch = batch_rw() loss += train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if epoch % args.saveStep == 0: embeddingW = graph.get_tensor_by_name('W:0') embeddingW_value = sess.run(embeddingW) with open(checkpoint_prefix + '-' + str(epoch), 'wb') as f: cPickle.dump(embeddingW_value, f) print("Save embeddings to {}\n".format(checkpoint_prefix + '-' + str(epoch)))
true
true
1c373bc712a9957c5102c096cfc4e643dc9cdcd9
267
py
Python
options/constants.py
marcosgabarda/django-options
285744850510610f4e5cbad51eefd2461f6d969c
[ "MIT" ]
4
2018-08-09T13:41:25.000Z
2021-03-25T15:47:12.000Z
options/constants.py
marcosgabarda/django-options
285744850510610f4e5cbad51eefd2461f6d969c
[ "MIT" ]
5
2019-06-29T08:19:24.000Z
2021-03-25T08:51:41.000Z
options/constants.py
marcosgabarda/django-options
285744850510610f4e5cbad51eefd2461f6d969c
[ "MIT" ]
2
2019-06-27T22:12:48.000Z
2020-07-10T07:52:24.000Z
from django.utils.translation import gettext_lazy as _ FLOAT, INT, STR, FILE = (0, 1, 2, 3) TYPE_CHOICES = ( (FLOAT, _("Float")), (INT, _("Integer")), (STR, _("String")), (FILE, _("File")), ) CONVERTER = {INT: int, FLOAT: float, STR: str, FILE: str}
24.272727
57
0.588015
from django.utils.translation import gettext_lazy as _ FLOAT, INT, STR, FILE = (0, 1, 2, 3) TYPE_CHOICES = ( (FLOAT, _("Float")), (INT, _("Integer")), (STR, _("String")), (FILE, _("File")), ) CONVERTER = {INT: int, FLOAT: float, STR: str, FILE: str}
true
true
1c373bd2e2abb5a30aa8d41c0d711e13bd89bebf
397
py
Python
djangoDemo/wsgi.py
ttdys108/django-demo
9a1c18b4bf7d92f1b122222d1777424fac2aba2d
[ "Apache-2.0" ]
8
2020-02-04T11:23:26.000Z
2021-10-20T05:38:08.000Z
djangoDemo/wsgi.py
DeSireFire/simpleDjango3-adminLTE
8509b576544b6fe8f0134ae2f5af127a005ab240
[ "MIT" ]
null
null
null
djangoDemo/wsgi.py
DeSireFire/simpleDjango3-adminLTE
8509b576544b6fe8f0134ae2f5af127a005ab240
[ "MIT" ]
null
null
null
""" WSGI config for djangoDemo project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoDemo.settings') application = get_wsgi_application()
23.352941
78
0.788413
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoDemo.settings') application = get_wsgi_application()
true
true
1c373cbe1e3abecb9da944ff3fafb3694b4d1522
48,431
py
Python
raiden/api/python.py
BOR4/raiden
d72e32806fe3b73e5fa6a00843f3f5e41be4448b
[ "MIT" ]
null
null
null
raiden/api/python.py
BOR4/raiden
d72e32806fe3b73e5fa6a00843f3f5e41be4448b
[ "MIT" ]
null
null
null
raiden/api/python.py
BOR4/raiden
d72e32806fe3b73e5fa6a00843f3f5e41be4448b
[ "MIT" ]
null
null
null
import gevent import structlog from eth_utils import is_binary_address from raiden import waiting from raiden.api.exceptions import ChannelNotFound, NonexistingChannel from raiden.constants import NULL_ADDRESS_BYTES, UINT64_MAX, UINT256_MAX from raiden.exceptions import ( AlreadyRegisteredTokenAddress, DepositMismatch, DepositOverLimit, DuplicatedChannelError, InsufficientFunds, InsufficientGasReserve, InvalidAmount, InvalidBinaryAddress, InvalidPaymentIdentifier, InvalidRevealTimeout, InvalidSecret, InvalidSecretHash, InvalidSettleTimeout, InvalidTokenAddress, RaidenRecoverableError, SamePeerAddress, TokenNetworkDeprecated, TokenNotRegistered, UnexpectedChannelState, UnknownTokenAddress, WithdrawMismatch, ) from raiden.settings import DEFAULT_RETRY_TIMEOUT from raiden.storage.utils import TimestampedEvent from raiden.transfer import channel, views from raiden.transfer.architecture import Event, StateChange, TransferTask from raiden.transfer.events import ( EventPaymentReceivedSuccess, EventPaymentSentFailed, EventPaymentSentSuccess, ) from raiden.transfer.mediated_transfer.tasks import InitiatorTask, MediatorTask, TargetTask from raiden.transfer.state import ChainState, ChannelState, NettingChannelState, NetworkState from raiden.transfer.state_change import ActionChannelClose from raiden.transfer.views import get_token_network_by_address from raiden.utils.formatting import to_checksum_address from raiden.utils.gas_reserve import has_enough_gas_reserve from raiden.utils.transfers import create_default_identifier from raiden.utils.typing import ( TYPE_CHECKING, Address, Any, BlockIdentifier, BlockTimeout, ChannelID, Dict, InitiatorAddress, List, LockedTransferType, NetworkTimeout, Optional, PaymentAmount, PaymentID, Secret, SecretHash, T_Secret, T_SecretHash, TargetAddress, TokenAddress, TokenAmount, TokenNetworkAddress, TokenNetworkRegistryAddress, WithdrawAmount, ) if TYPE_CHECKING: from raiden.raiden_service import RaidenService, PaymentStatus log = structlog.get_logger(__name__) EVENTS_PAYMENT_HISTORY_RELATED = ( EventPaymentSentSuccess, EventPaymentSentFailed, EventPaymentReceivedSuccess, ) def event_filter_for_payments( event: Event, chain_state: Optional[ChainState] = None, partner_address: Optional[Address] = None, token_address: Optional[TokenAddress] = None, ) -> bool: """Filters payment history related events depending on given arguments - If no other args are given, all payment related events match. - If a token network identifier is given then only payment events for that match. - If a partner is also given then if the event is a payment sent event and the target matches it's returned. If it's a payment received and the initiator matches. then it's returned. - If a token address is given then all events are filtered to be about that token. """ sent_and_target_matches = isinstance( event, (EventPaymentSentFailed, EventPaymentSentSuccess) ) and (partner_address is None or event.target == TargetAddress(partner_address)) received_and_initiator_matches = isinstance(event, EventPaymentReceivedSuccess) and ( partner_address is None or event.initiator == InitiatorAddress(partner_address) ) token_address_matches = True if token_address: assert chain_state, "Filtering for token_address without a chain state is an error" token_network = get_token_network_by_address( chain_state=chain_state, token_network_address=event.token_network_address, # type: ignore ) if not token_network: token_address_matches = False else: token_address_matches = token_address == token_network.token_address return token_address_matches and (sent_and_target_matches or received_and_initiator_matches) def flatten_transfer(transfer: LockedTransferType, role: str) -> Dict[str, Any]: return { "payment_identifier": str(transfer.payment_identifier), "token_address": to_checksum_address(transfer.token), "token_network_address": to_checksum_address(transfer.balance_proof.token_network_address), "channel_identifier": str(transfer.balance_proof.channel_identifier), "initiator": to_checksum_address(transfer.initiator), "target": to_checksum_address(transfer.target), "transferred_amount": str(transfer.balance_proof.transferred_amount), "locked_amount": str(transfer.balance_proof.locked_amount), "role": role, } def get_transfer_from_task( secrethash: SecretHash, transfer_task: TransferTask ) -> Optional[LockedTransferType]: if isinstance(transfer_task, InitiatorTask): # Work around for https://github.com/raiden-network/raiden/issues/5480, # can be removed when # https://github.com/raiden-network/raiden/issues/5515 is done. if secrethash not in transfer_task.manager_state.initiator_transfers: return None return transfer_task.manager_state.initiator_transfers[secrethash].transfer elif isinstance(transfer_task, MediatorTask): pairs = transfer_task.mediator_state.transfers_pair if pairs: return pairs[-1].payer_transfer assert transfer_task.mediator_state.waiting_transfer, "Invalid mediator_state" return transfer_task.mediator_state.waiting_transfer.transfer elif isinstance(transfer_task, TargetTask): return transfer_task.target_state.transfer raise ValueError("get_transfer_from_task for a non TransferTask argument") def transfer_tasks_view( transfer_tasks: Dict[SecretHash, TransferTask], token_address: TokenAddress = None, channel_id: ChannelID = None, ) -> List[Dict[str, Any]]: view = list() for secrethash, transfer_task in transfer_tasks.items(): transfer = get_transfer_from_task(secrethash, transfer_task) if transfer is None: continue if token_address is not None: if transfer.token != token_address: continue elif channel_id is not None: if transfer.balance_proof.channel_identifier != channel_id: continue role = views.role_from_transfer_task(transfer_task) view.append(flatten_transfer(transfer, role)) return view class RaidenAPI: # pragma: no unittest # pylint: disable=too-many-public-methods def __init__(self, raiden: "RaidenService"): self.raiden = raiden @property def address(self) -> Address: return self.raiden.address def get_channel( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, ) -> NettingChannelState: if not is_binary_address(token_address): raise InvalidBinaryAddress("Expected binary address format for token in get_channel") if not is_binary_address(partner_address): raise InvalidBinaryAddress("Expected binary address format for partner in get_channel") channel_list = self.get_channel_list(registry_address, token_address, partner_address) msg = f"Found {len(channel_list)} channels, but expected 0 or 1." assert len(channel_list) <= 1, msg if not channel_list: msg = ( f"Channel with partner '{to_checksum_address(partner_address)}' " f"for token '{to_checksum_address(token_address)}' could not be " f"found." ) raise ChannelNotFound(msg) return channel_list[0] def token_network_register( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, channel_participant_deposit_limit: TokenAmount, token_network_deposit_limit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetworkAddress: """Register the `token_address` in the blockchain. If the address is already registered but the event has not been processed this function will block until the next block to make sure the event is processed. Raises: InvalidBinaryAddress: If the registry_address or token_address is not a valid address. AlreadyRegisteredTokenAddress: If the token is already registered. RaidenRecoverableError: If the register transaction failed, this may happen because the account has not enough balance to pay for the gas or this register call raced with another transaction and lost. InvalidTokenAddress: If token_address is the null address (0x000000....00). """ if not is_binary_address(registry_address): raise InvalidBinaryAddress("registry_address must be a valid address in binary") if not is_binary_address(token_address): raise InvalidBinaryAddress("token_address must be a valid address in binary") if token_address == NULL_ADDRESS_BYTES: raise InvalidTokenAddress("token_address must be non-zero") # The following check is on the same chain state as the # `chainstate` variable defined below because the chain state does # not change between this line and seven lines below. # views.state_from_raiden() returns the same state again and again # as far as this gevent context is running. if token_address in self.get_tokens_list(registry_address): raise AlreadyRegisteredTokenAddress("Token already registered") chainstate = views.state_from_raiden(self.raiden) registry = self.raiden.proxy_manager.token_network_registry( registry_address, block_identifier=chainstate.block_hash ) token_network_address = registry.add_token( token_address=token_address, channel_participant_deposit_limit=channel_participant_deposit_limit, token_network_deposit_limit=token_network_deposit_limit, given_block_identifier=chainstate.block_hash, ) waiting.wait_for_token_network( raiden=self.raiden, token_network_registry_address=registry_address, token_address=token_address, retry_timeout=retry_timeout, ) return token_network_address def token_network_connect( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, funds: TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ) -> None: """ Automatically maintain channels open for the given token network. Args: token_address: the ERC20 token network to connect to. funds: the amount of funds that can be used by the ConnectionManager. initial_channel_target: number of channels to open proactively. joinable_funds_target: fraction of the funds that will be used to join channels opened by other participants. """ if not is_binary_address(registry_address): raise InvalidBinaryAddress("registry_address must be a valid address in binary") if not is_binary_address(token_address): raise InvalidBinaryAddress("token_address must be a valid address in binary") token_network_address = views.get_token_network_address_by_token_address( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, ) if token_network_address is None: raise UnknownTokenAddress( f"Token {to_checksum_address(token_address)} is not registered " f"with the network {to_checksum_address(registry_address)}." ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_address ) has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( raiden=self.raiden, channels_to_open=initial_channel_target ) if not has_enough_reserve: raise InsufficientGasReserve( "The account balance is below the estimated amount necessary to " "finish the lifecycles of all active channels. A balance of at " f"least {estimated_required_reserve} wei is required." ) connection_manager.connect( funds=funds, initial_channel_target=initial_channel_target, joinable_funds_target=joinable_funds_target, ) def token_network_leave( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress ) -> List[NettingChannelState]: """ Close all channels and wait for settlement. """ if not is_binary_address(registry_address): raise InvalidBinaryAddress("registry_address must be a valid address in binary") if not is_binary_address(token_address): raise InvalidBinaryAddress("token_address must be a valid address in binary") token_network_address = views.get_token_network_address_by_token_address( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, ) if token_network_address is None: raise UnknownTokenAddress( f"Token {to_checksum_address(token_address)} is not registered " f"with the network {to_checksum_address(registry_address)}." ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_address ) return connection_manager.leave(registry_address) def is_already_existing_channel( self, token_network_address: TokenNetworkAddress, partner_address: Address, block_identifier: Optional[BlockIdentifier] = None, ) -> bool: proxy_manager = self.raiden.proxy_manager proxy = proxy_manager.address_to_token_network[token_network_address] channel_identifier = proxy.get_channel_identifier_or_none( participant1=self.raiden.address, participant2=partner_address, block_identifier=block_identifier or proxy_manager.client.get_checking_block(), ) return channel_identifier is not None def channel_open( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, settle_timeout: BlockTimeout = None, reveal_timeout: BlockTimeout = None, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> ChannelID: """ Open a channel with the peer at `partner_address` with the given `token_address`. """ if settle_timeout is None: settle_timeout = self.raiden.config.settle_timeout if reveal_timeout is None: reveal_timeout = self.raiden.config.reveal_timeout if reveal_timeout <= 0: raise InvalidRevealTimeout("reveal_timeout should be larger than zero") if settle_timeout < reveal_timeout * 2: raise InvalidSettleTimeout( "`settle_timeout` can not be smaller than double the " "`reveal_timeout`.\n " "\n " "The setting `reveal_timeout` determines the maximum number of " "blocks it should take a transaction to be mined when the " "blockchain is under congestion. This setting determines the " "when a node must go on-chain to register a secret, and it is " "therefore the lower bound of the lock expiration. The " "`settle_timeout` determines when a channel can be settled " "on-chain, for this operation to be safe all locks must have " "been resolved, for this reason the `settle_timeout` has to be " "larger than `reveal_timeout`." ) if not is_binary_address(registry_address): raise InvalidBinaryAddress( "Expected binary address format for registry in channel open" ) if not is_binary_address(token_address): raise InvalidBinaryAddress("Expected binary address format for token in channel open") if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in channel open" ) confirmed_block_identifier = views.get_confirmed_blockhash(self.raiden) registry = self.raiden.proxy_manager.token_network_registry( registry_address, block_identifier=confirmed_block_identifier ) settlement_timeout_min = registry.settlement_timeout_min( block_identifier=confirmed_block_identifier ) settlement_timeout_max = registry.settlement_timeout_max( block_identifier=confirmed_block_identifier ) if settle_timeout < settlement_timeout_min: raise InvalidSettleTimeout( f"Settlement timeout should be at least {settlement_timeout_min}" ) if settle_timeout > settlement_timeout_max: raise InvalidSettleTimeout( f"Settlement timeout exceeds max of {settlement_timeout_max}" ) token_network_address = registry.get_token_network( token_address=token_address, block_identifier=confirmed_block_identifier ) if token_network_address is None: raise TokenNotRegistered( "Token network for token %s does not exist" % to_checksum_address(token_address) ) token_network = self.raiden.proxy_manager.token_network( address=token_network_address, block_identifier=confirmed_block_identifier ) safety_deprecation_switch = token_network.safety_deprecation_switch( block_identifier=confirmed_block_identifier ) if safety_deprecation_switch: msg = ( "This token_network has been deprecated. New channels cannot be " "open for this network, usage of the newly deployed token " "network contract is highly encouraged." ) raise TokenNetworkDeprecated(msg) duplicated_channel = self.is_already_existing_channel( token_network_address=token_network_address, partner_address=partner_address, block_identifier=confirmed_block_identifier, ) if duplicated_channel: raise DuplicatedChannelError( f"A channel with {to_checksum_address(partner_address)} for token " f"{to_checksum_address(token_address)} already exists. " f"(At blockhash: {confirmed_block_identifier.hex()})" ) has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( self.raiden, channels_to_open=1 ) if not has_enough_reserve: raise InsufficientGasReserve( "The account balance is below the estimated amount necessary to " "finish the lifecycles of all active channels. A balance of at " f"least {estimated_required_reserve} wei is required." ) try: token_network.new_netting_channel( partner=partner_address, settle_timeout=settle_timeout, given_block_identifier=confirmed_block_identifier, ) except DuplicatedChannelError: log.info("partner opened channel first") except RaidenRecoverableError: # The channel may have been created in the pending block. duplicated_channel = self.is_already_existing_channel( token_network_address=token_network_address, partner_address=partner_address ) if duplicated_channel: log.info("Channel has already been opened") else: raise waiting.wait_for_newchannel( raiden=self.raiden, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, retry_timeout=retry_timeout, ) chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) assert channel_state, f"channel {channel_state} is gone" self.raiden.set_channel_reveal_timeout( canonical_identifier=channel_state.canonical_identifier, reveal_timeout=reveal_timeout ) return channel_state.identifier def mint_token_for(self, token_address: TokenAddress, to: Address, value: TokenAmount) -> None: """ Try to mint `value` units of the token at `token_address` and assign them to `to`, using `mintFor`. Raises: MintFailed if the minting fails for any reason. """ confirmed_block_identifier = self.raiden.get_block_number() token_proxy = self.raiden.proxy_manager.custom_token( token_address, block_identifier=confirmed_block_identifier ) token_proxy.mint_for(value, to) def set_total_channel_withdraw( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, total_withdraw: WithdrawAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> None: """ Set the `total_withdraw` in the channel with the peer at `partner_address` and the given `token_address`. Raises: InvalidBinaryAddress: If either token_address or partner_address is not 20 bytes long. RaidenUnrecoverableError: May happen for multiple reasons: - During preconditions checks, if the channel was not open at the time of the approve_and_set_total_deposit call. - If the transaction fails during gas estimation or if a previous withdraw transaction with the same value was already mined. DepositMismatch: The total withdraw amount did not increase. """ chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers(chain_state, registry_address) channel_state = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in channel deposit" ) if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in channel deposit" ) if token_address not in token_addresses: raise UnknownTokenAddress("Unknown token address") if channel_state is None: raise NonexistingChannel("No channel with partner_address for the given token") if total_withdraw <= channel_state.our_total_withdraw: raise WithdrawMismatch(f"Total withdraw {total_withdraw} did not increase") current_balance = channel.get_balance( sender=channel_state.our_state, receiver=channel_state.partner_state ) amount_to_withdraw = total_withdraw - channel_state.our_total_withdraw if amount_to_withdraw > current_balance: raise InsufficientFunds( "The withdraw of {} is bigger than the current balance of {}".format( amount_to_withdraw, current_balance ) ) self.raiden.withdraw( canonical_identifier=channel_state.canonical_identifier, total_withdraw=total_withdraw ) waiting.wait_for_withdraw_complete( raiden=self.raiden, canonical_identifier=channel_state.canonical_identifier, total_withdraw=total_withdraw, retry_timeout=retry_timeout, ) def set_total_channel_deposit( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, total_deposit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> None: """ Set the `total_deposit` in the channel with the peer at `partner_address` and the given `token_address` in order to be able to do transfers. Raises: InvalidBinaryAddress: If either token_address or partner_address is not 20 bytes long. RaidenRecoverableError: May happen for multiple reasons: - If the token approval fails, e.g. the token may validate if account has enough balance for the allowance. - The deposit failed, e.g. the allowance did not set the token aside for use and the user spent it before deposit was called. - The channel was closed/settled between the allowance call and the deposit call. AddressWithoutCode: The channel was settled during the deposit execution. DepositOverLimit: The total deposit amount is higher than the limit. UnexpectedChannelState: The channel is no longer in an open state. """ chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers(chain_state, registry_address) channel_state = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in channel deposit" ) if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in channel deposit" ) if token_address not in token_addresses: raise UnknownTokenAddress("Unknown token address") if channel_state is None: raise NonexistingChannel("No channel with partner_address for the given token") confirmed_block_identifier = chain_state.block_hash token = self.raiden.proxy_manager.token( token_address, block_identifier=confirmed_block_identifier ) token_network_registry = self.raiden.proxy_manager.token_network_registry( registry_address, block_identifier=confirmed_block_identifier ) token_network_address = token_network_registry.get_token_network( token_address=token_address, block_identifier=confirmed_block_identifier ) if token_network_address is None: raise UnknownTokenAddress( f"Token {to_checksum_address(token_address)} is not registered " f"with the network {to_checksum_address(registry_address)}." ) token_network_proxy = self.raiden.proxy_manager.token_network( address=token_network_address, block_identifier=confirmed_block_identifier ) channel_proxy = self.raiden.proxy_manager.payment_channel( channel_state=channel_state, block_identifier=confirmed_block_identifier ) blockhash = chain_state.block_hash token_network_proxy = channel_proxy.token_network safety_deprecation_switch = token_network_proxy.safety_deprecation_switch( block_identifier=blockhash ) balance = token.balance_of(self.raiden.address, block_identifier=blockhash) network_balance = token.balance_of( address=Address(token_network_address), block_identifier=blockhash ) token_network_deposit_limit = token_network_proxy.token_network_deposit_limit( block_identifier=blockhash ) addendum = total_deposit - channel_state.our_state.contract_balance channel_participant_deposit_limit = token_network_proxy.channel_participant_deposit_limit( block_identifier=blockhash ) total_channel_deposit = total_deposit + channel_state.partner_state.contract_balance is_channel_open = channel.get_status(channel_state) == ChannelState.STATE_OPENED if not is_channel_open: raise UnexpectedChannelState("Channel is not in an open state.") if safety_deprecation_switch: msg = ( "This token_network has been deprecated. " "All channels in this network should be closed and " "the usage of the newly deployed token network contract " "is highly encouraged." ) raise TokenNetworkDeprecated(msg) if total_deposit <= channel_state.our_state.contract_balance: raise DepositMismatch("Total deposit did not increase.") # If this check succeeds it does not imply the `deposit` will # succeed, since the `deposit` transaction may race with another # transaction. if not (balance >= addendum): msg = "Not enough balance to deposit. {} Available={} Needed={}".format( to_checksum_address(token_address), balance, addendum ) raise InsufficientFunds(msg) if network_balance + addendum > token_network_deposit_limit: msg = f"Deposit of {addendum} would have exceeded the token network deposit limit." raise DepositOverLimit(msg) if total_deposit > channel_participant_deposit_limit: msg = ( f"Deposit of {total_deposit} is larger than the " f"channel participant deposit limit" ) raise DepositOverLimit(msg) if total_channel_deposit >= UINT256_MAX: raise DepositOverLimit("Deposit overflow") try: channel_proxy.approve_and_set_total_deposit( total_deposit=total_deposit, block_identifier=blockhash ) except RaidenRecoverableError as e: log.info(f"Deposit failed. {str(e)}") target_address = self.raiden.address waiting.wait_for_participant_deposit( raiden=self.raiden, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, target_address=target_address, target_balance=total_deposit, retry_timeout=retry_timeout, ) def set_reveal_timeout( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, reveal_timeout: BlockTimeout, ) -> None: """ Set the `reveal_timeout` in the channel with the peer at `partner_address` and the given `token_address`. Raises: InvalidBinaryAddress: If either token_address or partner_address is not 20 bytes long. InvalidRevealTimeout: If reveal_timeout has an invalid value. """ chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers(chain_state, registry_address) channel_state = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in channel deposit" ) if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in channel deposit" ) if token_address not in token_addresses: raise UnknownTokenAddress("Unknown token address") if channel_state is None: raise NonexistingChannel("No channel with partner_address for the given token") if reveal_timeout <= 0: raise InvalidRevealTimeout("reveal_timeout should be larger than zero.") if channel_state.settle_timeout < reveal_timeout * 2: raise InvalidRevealTimeout( "`settle_timeout` should be at least double the " "provided `reveal_timeout`." ) self.raiden.set_channel_reveal_timeout( canonical_identifier=channel_state.canonical_identifier, reveal_timeout=reveal_timeout ) def channel_close( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> None: """Close a channel opened with `partner_address` for the given `token_address`. Race condition, this can fail if channel was closed externally. """ self.channel_batch_close( registry_address=registry_address, token_address=token_address, partner_addresses=[partner_address], retry_timeout=retry_timeout, ) def channel_batch_close( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_addresses: List[Address], retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> None: """Close a channel opened with `partner_address` for the given `token_address`. Race condition, this can fail if channel was closed externally. """ if not is_binary_address(token_address): raise InvalidBinaryAddress("Expected binary address format for token in channel close") if not all(map(is_binary_address, partner_addresses)): raise InvalidBinaryAddress( "Expected binary address format for partner in channel close" ) valid_tokens = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, ) if token_address not in valid_tokens: raise UnknownTokenAddress("Token address is not known.") chain_state = views.state_from_raiden(self.raiden) channels_to_close = views.filter_channels_by_partneraddress( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_addresses=partner_addresses, ) close_state_changes: List[StateChange] = [ ActionChannelClose(canonical_identifier=channel_state.canonical_identifier) for channel_state in channels_to_close ] greenlets = set(self.raiden.handle_state_changes(close_state_changes)) gevent.joinall(greenlets, raise_error=True) channel_ids = [channel_state.identifier for channel_state in channels_to_close] waiting.wait_for_close( raiden=self.raiden, token_network_registry_address=registry_address, token_address=token_address, channel_ids=channel_ids, retry_timeout=retry_timeout, ) def get_channel_list( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress = None, partner_address: Address = None, ) -> List[NettingChannelState]: """Returns a list of channels associated with the optionally given `token_address` and/or `partner_address`. Args: token_address: an optionally provided token address partner_address: an optionally provided partner address Return: A list containing all channels the node participates. Optionally filtered by a token address and/or partner address. Raises: KeyError: An error occurred when the token address is unknown to the node. """ if registry_address and not is_binary_address(registry_address): raise InvalidBinaryAddress( "Expected binary address format for registry in get_channel_list" ) if token_address and not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in get_channel_list" ) if partner_address: if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in get_channel_list" ) if not token_address: raise UnknownTokenAddress("Provided a partner address but no token address") if token_address and partner_address: channel_state = views.get_channelstate_for( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) if channel_state: result = [channel_state] else: result = [] elif token_address: result = views.list_channelstate_for_tokennetwork( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, ) else: result = views.list_all_channelstate(chain_state=views.state_from_raiden(self.raiden)) return result def get_node_network_state(self, node_address: Address) -> NetworkState: """ Returns the currently network status of `node_address`. """ return views.get_node_network_status( chain_state=views.state_from_raiden(self.raiden), node_address=node_address ) def async_start_health_check_for(self, node_address: Address) -> None: """ Returns the currently network status of `node_address`. """ self.raiden.async_start_health_check_for(node_address) def get_tokens_list(self, registry_address: TokenNetworkRegistryAddress) -> List[TokenAddress]: """Returns a list of tokens the node knows about""" return views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, ) def get_token_network_address_for_token_address( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress ) -> Optional[TokenNetworkAddress]: return views.get_token_network_address_by_token_address( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, ) def transfer_and_wait( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, amount: PaymentAmount, target: TargetAddress, identifier: PaymentID = None, transfer_timeout: int = None, secret: Secret = None, secrethash: SecretHash = None, lock_timeout: BlockTimeout = None, ) -> "PaymentStatus": """ Do a transfer with `target` with the given `amount` of `token_address`. """ # pylint: disable=too-many-arguments payment_status = self.transfer_async( registry_address=registry_address, token_address=token_address, amount=amount, target=target, identifier=identifier, secret=secret, secrethash=secrethash, lock_timeout=lock_timeout, ) payment_status.payment_done.wait(timeout=transfer_timeout) return payment_status def transfer_async( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, amount: PaymentAmount, target: TargetAddress, identifier: PaymentID = None, secret: Secret = None, secrethash: SecretHash = None, lock_timeout: BlockTimeout = None, ) -> "PaymentStatus": current_state = views.state_from_raiden(self.raiden) token_network_registry_address = self.raiden.default_registry.address if not isinstance(amount, int): # pragma: no unittest raise InvalidAmount("Amount not a number") if Address(target) == self.address: raise SamePeerAddress("Address must be different than ours") if amount <= 0: raise InvalidAmount("Amount negative") if amount > UINT256_MAX: raise InvalidAmount("Amount too large") if not is_binary_address(token_address): raise InvalidBinaryAddress("token address is not valid.") if token_address not in views.get_token_identifiers(current_state, registry_address): raise UnknownTokenAddress("Token address is not known.") if not is_binary_address(target): raise InvalidBinaryAddress("target address is not valid.") valid_tokens = views.get_token_identifiers( views.state_from_raiden(self.raiden), registry_address ) if token_address not in valid_tokens: raise UnknownTokenAddress("Token address is not known.") if secret is not None and not isinstance(secret, T_Secret): raise InvalidSecret("secret is not valid.") if secrethash is not None and not isinstance(secrethash, T_SecretHash): raise InvalidSecretHash("secrethash is not valid.") if identifier is None: identifier = create_default_identifier() if identifier <= 0: raise InvalidPaymentIdentifier("Payment identifier cannot be 0 or negative") if identifier > UINT64_MAX: raise InvalidPaymentIdentifier("Payment identifier is too large") log.debug( "Initiating transfer", initiator=to_checksum_address(self.raiden.address), target=to_checksum_address(target), token=to_checksum_address(token_address), amount=amount, identifier=identifier, ) token_network_address = views.get_token_network_address_by_token_address( chain_state=current_state, token_network_registry_address=token_network_registry_address, token_address=token_address, ) if token_network_address is None: raise UnknownTokenAddress( f"Token {to_checksum_address(token_address)} is not registered " f"with the network {to_checksum_address(registry_address)}." ) payment_status = self.raiden.mediated_transfer_async( token_network_address=token_network_address, amount=amount, target=target, identifier=identifier, secret=secret, secrethash=secrethash, lock_timeout=lock_timeout, ) return payment_status def get_raiden_events_payment_history_with_timestamps( self, registry_address: TokenNetworkRegistryAddress, token_address: Optional[TokenAddress] = None, target_address: Address = None, limit: int = None, offset: int = None, ) -> List[TimestampedEvent]: if token_address and not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in get_raiden_events_payment_history" ) chain_state = views.state_from_raiden(self.raiden) token_network_address = None if token_address: token_network_address = views.get_token_network_address_by_token_address( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, ) if not token_network_address: raise InvalidTokenAddress("Token address does not match a Raiden token network") if target_address and not is_binary_address(target_address): raise InvalidBinaryAddress( "Expected binary address format for " "target_address in get_raiden_events_payment_history" ) assert self.raiden.wal, "Raiden service has to be started for the API to be usable." event_types = [ "raiden.transfer.events.EventPaymentReceivedSuccess", "raiden.transfer.events.EventPaymentSentFailed", "raiden.transfer.events.EventPaymentSentSuccess", ] events = self.raiden.wal.storage.get_raiden_events_payment_history_with_timestamps( event_types=event_types, limit=limit, offset=offset, token_network_address=token_network_address, partner_address=target_address, ) events = [ e for e in events if event_filter_for_payments( event=e.wrapped_event, chain_state=chain_state, partner_address=target_address, token_address=token_address, ) ] return events def get_raiden_internal_events_with_timestamps( self, limit: int = None, offset: int = None ) -> List[TimestampedEvent]: assert self.raiden.wal, "Raiden service has to be started for the API to be usable." return self.raiden.wal.storage.get_events_with_timestamps(limit=limit, offset=offset) transfer = transfer_and_wait def get_pending_transfers( self, token_address: TokenAddress = None, partner_address: Address = None ) -> List[Dict[str, Any]]: chain_state = views.state_from_raiden(self.raiden) transfer_tasks = views.get_all_transfer_tasks(chain_state) channel_id = None confirmed_block_identifier = chain_state.block_hash if token_address is not None: token_network = self.raiden.default_registry.get_token_network( token_address=token_address, block_identifier=confirmed_block_identifier ) if token_network is None: raise UnknownTokenAddress(f"Token {to_checksum_address(token_address)} not found.") if partner_address is not None: partner_channel = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=self.raiden.default_registry.address, token_address=token_address, partner_address=partner_address, ) if not partner_channel: raise ChannelNotFound("Channel with partner `partner_address not found.`") channel_id = partner_channel.identifier return transfer_tasks_view(transfer_tasks, token_address, channel_id) def shutdown(self) -> None: self.raiden.stop()
40.091887
99
0.670191
import gevent import structlog from eth_utils import is_binary_address from raiden import waiting from raiden.api.exceptions import ChannelNotFound, NonexistingChannel from raiden.constants import NULL_ADDRESS_BYTES, UINT64_MAX, UINT256_MAX from raiden.exceptions import ( AlreadyRegisteredTokenAddress, DepositMismatch, DepositOverLimit, DuplicatedChannelError, InsufficientFunds, InsufficientGasReserve, InvalidAmount, InvalidBinaryAddress, InvalidPaymentIdentifier, InvalidRevealTimeout, InvalidSecret, InvalidSecretHash, InvalidSettleTimeout, InvalidTokenAddress, RaidenRecoverableError, SamePeerAddress, TokenNetworkDeprecated, TokenNotRegistered, UnexpectedChannelState, UnknownTokenAddress, WithdrawMismatch, ) from raiden.settings import DEFAULT_RETRY_TIMEOUT from raiden.storage.utils import TimestampedEvent from raiden.transfer import channel, views from raiden.transfer.architecture import Event, StateChange, TransferTask from raiden.transfer.events import ( EventPaymentReceivedSuccess, EventPaymentSentFailed, EventPaymentSentSuccess, ) from raiden.transfer.mediated_transfer.tasks import InitiatorTask, MediatorTask, TargetTask from raiden.transfer.state import ChainState, ChannelState, NettingChannelState, NetworkState from raiden.transfer.state_change import ActionChannelClose from raiden.transfer.views import get_token_network_by_address from raiden.utils.formatting import to_checksum_address from raiden.utils.gas_reserve import has_enough_gas_reserve from raiden.utils.transfers import create_default_identifier from raiden.utils.typing import ( TYPE_CHECKING, Address, Any, BlockIdentifier, BlockTimeout, ChannelID, Dict, InitiatorAddress, List, LockedTransferType, NetworkTimeout, Optional, PaymentAmount, PaymentID, Secret, SecretHash, T_Secret, T_SecretHash, TargetAddress, TokenAddress, TokenAmount, TokenNetworkAddress, TokenNetworkRegistryAddress, WithdrawAmount, ) if TYPE_CHECKING: from raiden.raiden_service import RaidenService, PaymentStatus log = structlog.get_logger(__name__) EVENTS_PAYMENT_HISTORY_RELATED = ( EventPaymentSentSuccess, EventPaymentSentFailed, EventPaymentReceivedSuccess, ) def event_filter_for_payments( event: Event, chain_state: Optional[ChainState] = None, partner_address: Optional[Address] = None, token_address: Optional[TokenAddress] = None, ) -> bool: sent_and_target_matches = isinstance( event, (EventPaymentSentFailed, EventPaymentSentSuccess) ) and (partner_address is None or event.target == TargetAddress(partner_address)) received_and_initiator_matches = isinstance(event, EventPaymentReceivedSuccess) and ( partner_address is None or event.initiator == InitiatorAddress(partner_address) ) token_address_matches = True if token_address: assert chain_state, "Filtering for token_address without a chain state is an error" token_network = get_token_network_by_address( chain_state=chain_state, token_network_address=event.token_network_address, ) if not token_network: token_address_matches = False else: token_address_matches = token_address == token_network.token_address return token_address_matches and (sent_and_target_matches or received_and_initiator_matches) def flatten_transfer(transfer: LockedTransferType, role: str) -> Dict[str, Any]: return { "payment_identifier": str(transfer.payment_identifier), "token_address": to_checksum_address(transfer.token), "token_network_address": to_checksum_address(transfer.balance_proof.token_network_address), "channel_identifier": str(transfer.balance_proof.channel_identifier), "initiator": to_checksum_address(transfer.initiator), "target": to_checksum_address(transfer.target), "transferred_amount": str(transfer.balance_proof.transferred_amount), "locked_amount": str(transfer.balance_proof.locked_amount), "role": role, } def get_transfer_from_task( secrethash: SecretHash, transfer_task: TransferTask ) -> Optional[LockedTransferType]: if isinstance(transfer_task, InitiatorTask): if secrethash not in transfer_task.manager_state.initiator_transfers: return None return transfer_task.manager_state.initiator_transfers[secrethash].transfer elif isinstance(transfer_task, MediatorTask): pairs = transfer_task.mediator_state.transfers_pair if pairs: return pairs[-1].payer_transfer assert transfer_task.mediator_state.waiting_transfer, "Invalid mediator_state" return transfer_task.mediator_state.waiting_transfer.transfer elif isinstance(transfer_task, TargetTask): return transfer_task.target_state.transfer raise ValueError("get_transfer_from_task for a non TransferTask argument") def transfer_tasks_view( transfer_tasks: Dict[SecretHash, TransferTask], token_address: TokenAddress = None, channel_id: ChannelID = None, ) -> List[Dict[str, Any]]: view = list() for secrethash, transfer_task in transfer_tasks.items(): transfer = get_transfer_from_task(secrethash, transfer_task) if transfer is None: continue if token_address is not None: if transfer.token != token_address: continue elif channel_id is not None: if transfer.balance_proof.channel_identifier != channel_id: continue role = views.role_from_transfer_task(transfer_task) view.append(flatten_transfer(transfer, role)) return view class RaidenAPI: def __init__(self, raiden: "RaidenService"): self.raiden = raiden @property def address(self) -> Address: return self.raiden.address def get_channel( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, ) -> NettingChannelState: if not is_binary_address(token_address): raise InvalidBinaryAddress("Expected binary address format for token in get_channel") if not is_binary_address(partner_address): raise InvalidBinaryAddress("Expected binary address format for partner in get_channel") channel_list = self.get_channel_list(registry_address, token_address, partner_address) msg = f"Found {len(channel_list)} channels, but expected 0 or 1." assert len(channel_list) <= 1, msg if not channel_list: msg = ( f"Channel with partner '{to_checksum_address(partner_address)}' " f"for token '{to_checksum_address(token_address)}' could not be " f"found." ) raise ChannelNotFound(msg) return channel_list[0] def token_network_register( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, channel_participant_deposit_limit: TokenAmount, token_network_deposit_limit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetworkAddress: if not is_binary_address(registry_address): raise InvalidBinaryAddress("registry_address must be a valid address in binary") if not is_binary_address(token_address): raise InvalidBinaryAddress("token_address must be a valid address in binary") if token_address == NULL_ADDRESS_BYTES: raise InvalidTokenAddress("token_address must be non-zero") if token_address in self.get_tokens_list(registry_address): raise AlreadyRegisteredTokenAddress("Token already registered") chainstate = views.state_from_raiden(self.raiden) registry = self.raiden.proxy_manager.token_network_registry( registry_address, block_identifier=chainstate.block_hash ) token_network_address = registry.add_token( token_address=token_address, channel_participant_deposit_limit=channel_participant_deposit_limit, token_network_deposit_limit=token_network_deposit_limit, given_block_identifier=chainstate.block_hash, ) waiting.wait_for_token_network( raiden=self.raiden, token_network_registry_address=registry_address, token_address=token_address, retry_timeout=retry_timeout, ) return token_network_address def token_network_connect( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, funds: TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ) -> None: if not is_binary_address(registry_address): raise InvalidBinaryAddress("registry_address must be a valid address in binary") if not is_binary_address(token_address): raise InvalidBinaryAddress("token_address must be a valid address in binary") token_network_address = views.get_token_network_address_by_token_address( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, ) if token_network_address is None: raise UnknownTokenAddress( f"Token {to_checksum_address(token_address)} is not registered " f"with the network {to_checksum_address(registry_address)}." ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_address ) has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( raiden=self.raiden, channels_to_open=initial_channel_target ) if not has_enough_reserve: raise InsufficientGasReserve( "The account balance is below the estimated amount necessary to " "finish the lifecycles of all active channels. A balance of at " f"least {estimated_required_reserve} wei is required." ) connection_manager.connect( funds=funds, initial_channel_target=initial_channel_target, joinable_funds_target=joinable_funds_target, ) def token_network_leave( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress ) -> List[NettingChannelState]: if not is_binary_address(registry_address): raise InvalidBinaryAddress("registry_address must be a valid address in binary") if not is_binary_address(token_address): raise InvalidBinaryAddress("token_address must be a valid address in binary") token_network_address = views.get_token_network_address_by_token_address( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, ) if token_network_address is None: raise UnknownTokenAddress( f"Token {to_checksum_address(token_address)} is not registered " f"with the network {to_checksum_address(registry_address)}." ) connection_manager = self.raiden.connection_manager_for_token_network( token_network_address ) return connection_manager.leave(registry_address) def is_already_existing_channel( self, token_network_address: TokenNetworkAddress, partner_address: Address, block_identifier: Optional[BlockIdentifier] = None, ) -> bool: proxy_manager = self.raiden.proxy_manager proxy = proxy_manager.address_to_token_network[token_network_address] channel_identifier = proxy.get_channel_identifier_or_none( participant1=self.raiden.address, participant2=partner_address, block_identifier=block_identifier or proxy_manager.client.get_checking_block(), ) return channel_identifier is not None def channel_open( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, settle_timeout: BlockTimeout = None, reveal_timeout: BlockTimeout = None, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> ChannelID: if settle_timeout is None: settle_timeout = self.raiden.config.settle_timeout if reveal_timeout is None: reveal_timeout = self.raiden.config.reveal_timeout if reveal_timeout <= 0: raise InvalidRevealTimeout("reveal_timeout should be larger than zero") if settle_timeout < reveal_timeout * 2: raise InvalidSettleTimeout( "`settle_timeout` can not be smaller than double the " "`reveal_timeout`.\n " "\n " "The setting `reveal_timeout` determines the maximum number of " "blocks it should take a transaction to be mined when the " "blockchain is under congestion. This setting determines the " "when a node must go on-chain to register a secret, and it is " "therefore the lower bound of the lock expiration. The " "`settle_timeout` determines when a channel can be settled " "on-chain, for this operation to be safe all locks must have " "been resolved, for this reason the `settle_timeout` has to be " "larger than `reveal_timeout`." ) if not is_binary_address(registry_address): raise InvalidBinaryAddress( "Expected binary address format for registry in channel open" ) if not is_binary_address(token_address): raise InvalidBinaryAddress("Expected binary address format for token in channel open") if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in channel open" ) confirmed_block_identifier = views.get_confirmed_blockhash(self.raiden) registry = self.raiden.proxy_manager.token_network_registry( registry_address, block_identifier=confirmed_block_identifier ) settlement_timeout_min = registry.settlement_timeout_min( block_identifier=confirmed_block_identifier ) settlement_timeout_max = registry.settlement_timeout_max( block_identifier=confirmed_block_identifier ) if settle_timeout < settlement_timeout_min: raise InvalidSettleTimeout( f"Settlement timeout should be at least {settlement_timeout_min}" ) if settle_timeout > settlement_timeout_max: raise InvalidSettleTimeout( f"Settlement timeout exceeds max of {settlement_timeout_max}" ) token_network_address = registry.get_token_network( token_address=token_address, block_identifier=confirmed_block_identifier ) if token_network_address is None: raise TokenNotRegistered( "Token network for token %s does not exist" % to_checksum_address(token_address) ) token_network = self.raiden.proxy_manager.token_network( address=token_network_address, block_identifier=confirmed_block_identifier ) safety_deprecation_switch = token_network.safety_deprecation_switch( block_identifier=confirmed_block_identifier ) if safety_deprecation_switch: msg = ( "This token_network has been deprecated. New channels cannot be " "open for this network, usage of the newly deployed token " "network contract is highly encouraged." ) raise TokenNetworkDeprecated(msg) duplicated_channel = self.is_already_existing_channel( token_network_address=token_network_address, partner_address=partner_address, block_identifier=confirmed_block_identifier, ) if duplicated_channel: raise DuplicatedChannelError( f"A channel with {to_checksum_address(partner_address)} for token " f"{to_checksum_address(token_address)} already exists. " f"(At blockhash: {confirmed_block_identifier.hex()})" ) has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( self.raiden, channels_to_open=1 ) if not has_enough_reserve: raise InsufficientGasReserve( "The account balance is below the estimated amount necessary to " "finish the lifecycles of all active channels. A balance of at " f"least {estimated_required_reserve} wei is required." ) try: token_network.new_netting_channel( partner=partner_address, settle_timeout=settle_timeout, given_block_identifier=confirmed_block_identifier, ) except DuplicatedChannelError: log.info("partner opened channel first") except RaidenRecoverableError: duplicated_channel = self.is_already_existing_channel( token_network_address=token_network_address, partner_address=partner_address ) if duplicated_channel: log.info("Channel has already been opened") else: raise waiting.wait_for_newchannel( raiden=self.raiden, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, retry_timeout=retry_timeout, ) chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) assert channel_state, f"channel {channel_state} is gone" self.raiden.set_channel_reveal_timeout( canonical_identifier=channel_state.canonical_identifier, reveal_timeout=reveal_timeout ) return channel_state.identifier def mint_token_for(self, token_address: TokenAddress, to: Address, value: TokenAmount) -> None: confirmed_block_identifier = self.raiden.get_block_number() token_proxy = self.raiden.proxy_manager.custom_token( token_address, block_identifier=confirmed_block_identifier ) token_proxy.mint_for(value, to) def set_total_channel_withdraw( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, total_withdraw: WithdrawAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> None: chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers(chain_state, registry_address) channel_state = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in channel deposit" ) if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in channel deposit" ) if token_address not in token_addresses: raise UnknownTokenAddress("Unknown token address") if channel_state is None: raise NonexistingChannel("No channel with partner_address for the given token") if total_withdraw <= channel_state.our_total_withdraw: raise WithdrawMismatch(f"Total withdraw {total_withdraw} did not increase") current_balance = channel.get_balance( sender=channel_state.our_state, receiver=channel_state.partner_state ) amount_to_withdraw = total_withdraw - channel_state.our_total_withdraw if amount_to_withdraw > current_balance: raise InsufficientFunds( "The withdraw of {} is bigger than the current balance of {}".format( amount_to_withdraw, current_balance ) ) self.raiden.withdraw( canonical_identifier=channel_state.canonical_identifier, total_withdraw=total_withdraw ) waiting.wait_for_withdraw_complete( raiden=self.raiden, canonical_identifier=channel_state.canonical_identifier, total_withdraw=total_withdraw, retry_timeout=retry_timeout, ) def set_total_channel_deposit( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, total_deposit: TokenAmount, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> None: chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers(chain_state, registry_address) channel_state = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in channel deposit" ) if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in channel deposit" ) if token_address not in token_addresses: raise UnknownTokenAddress("Unknown token address") if channel_state is None: raise NonexistingChannel("No channel with partner_address for the given token") confirmed_block_identifier = chain_state.block_hash token = self.raiden.proxy_manager.token( token_address, block_identifier=confirmed_block_identifier ) token_network_registry = self.raiden.proxy_manager.token_network_registry( registry_address, block_identifier=confirmed_block_identifier ) token_network_address = token_network_registry.get_token_network( token_address=token_address, block_identifier=confirmed_block_identifier ) if token_network_address is None: raise UnknownTokenAddress( f"Token {to_checksum_address(token_address)} is not registered " f"with the network {to_checksum_address(registry_address)}." ) token_network_proxy = self.raiden.proxy_manager.token_network( address=token_network_address, block_identifier=confirmed_block_identifier ) channel_proxy = self.raiden.proxy_manager.payment_channel( channel_state=channel_state, block_identifier=confirmed_block_identifier ) blockhash = chain_state.block_hash token_network_proxy = channel_proxy.token_network safety_deprecation_switch = token_network_proxy.safety_deprecation_switch( block_identifier=blockhash ) balance = token.balance_of(self.raiden.address, block_identifier=blockhash) network_balance = token.balance_of( address=Address(token_network_address), block_identifier=blockhash ) token_network_deposit_limit = token_network_proxy.token_network_deposit_limit( block_identifier=blockhash ) addendum = total_deposit - channel_state.our_state.contract_balance channel_participant_deposit_limit = token_network_proxy.channel_participant_deposit_limit( block_identifier=blockhash ) total_channel_deposit = total_deposit + channel_state.partner_state.contract_balance is_channel_open = channel.get_status(channel_state) == ChannelState.STATE_OPENED if not is_channel_open: raise UnexpectedChannelState("Channel is not in an open state.") if safety_deprecation_switch: msg = ( "This token_network has been deprecated. " "All channels in this network should be closed and " "the usage of the newly deployed token network contract " "is highly encouraged." ) raise TokenNetworkDeprecated(msg) if total_deposit <= channel_state.our_state.contract_balance: raise DepositMismatch("Total deposit did not increase.") if not (balance >= addendum): msg = "Not enough balance to deposit. {} Available={} Needed={}".format( to_checksum_address(token_address), balance, addendum ) raise InsufficientFunds(msg) if network_balance + addendum > token_network_deposit_limit: msg = f"Deposit of {addendum} would have exceeded the token network deposit limit." raise DepositOverLimit(msg) if total_deposit > channel_participant_deposit_limit: msg = ( f"Deposit of {total_deposit} is larger than the " f"channel participant deposit limit" ) raise DepositOverLimit(msg) if total_channel_deposit >= UINT256_MAX: raise DepositOverLimit("Deposit overflow") try: channel_proxy.approve_and_set_total_deposit( total_deposit=total_deposit, block_identifier=blockhash ) except RaidenRecoverableError as e: log.info(f"Deposit failed. {str(e)}") target_address = self.raiden.address waiting.wait_for_participant_deposit( raiden=self.raiden, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, target_address=target_address, target_balance=total_deposit, retry_timeout=retry_timeout, ) def set_reveal_timeout( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, reveal_timeout: BlockTimeout, ) -> None: chain_state = views.state_from_raiden(self.raiden) token_addresses = views.get_token_identifiers(chain_state, registry_address) channel_state = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) if not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in channel deposit" ) if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in channel deposit" ) if token_address not in token_addresses: raise UnknownTokenAddress("Unknown token address") if channel_state is None: raise NonexistingChannel("No channel with partner_address for the given token") if reveal_timeout <= 0: raise InvalidRevealTimeout("reveal_timeout should be larger than zero.") if channel_state.settle_timeout < reveal_timeout * 2: raise InvalidRevealTimeout( "`settle_timeout` should be at least double the " "provided `reveal_timeout`." ) self.raiden.set_channel_reveal_timeout( canonical_identifier=channel_state.canonical_identifier, reveal_timeout=reveal_timeout ) def channel_close( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_address: Address, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> None: self.channel_batch_close( registry_address=registry_address, token_address=token_address, partner_addresses=[partner_address], retry_timeout=retry_timeout, ) def channel_batch_close( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, partner_addresses: List[Address], retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> None: if not is_binary_address(token_address): raise InvalidBinaryAddress("Expected binary address format for token in channel close") if not all(map(is_binary_address, partner_addresses)): raise InvalidBinaryAddress( "Expected binary address format for partner in channel close" ) valid_tokens = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, ) if token_address not in valid_tokens: raise UnknownTokenAddress("Token address is not known.") chain_state = views.state_from_raiden(self.raiden) channels_to_close = views.filter_channels_by_partneraddress( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, partner_addresses=partner_addresses, ) close_state_changes: List[StateChange] = [ ActionChannelClose(canonical_identifier=channel_state.canonical_identifier) for channel_state in channels_to_close ] greenlets = set(self.raiden.handle_state_changes(close_state_changes)) gevent.joinall(greenlets, raise_error=True) channel_ids = [channel_state.identifier for channel_state in channels_to_close] waiting.wait_for_close( raiden=self.raiden, token_network_registry_address=registry_address, token_address=token_address, channel_ids=channel_ids, retry_timeout=retry_timeout, ) def get_channel_list( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress = None, partner_address: Address = None, ) -> List[NettingChannelState]: if registry_address and not is_binary_address(registry_address): raise InvalidBinaryAddress( "Expected binary address format for registry in get_channel_list" ) if token_address and not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in get_channel_list" ) if partner_address: if not is_binary_address(partner_address): raise InvalidBinaryAddress( "Expected binary address format for partner in get_channel_list" ) if not token_address: raise UnknownTokenAddress("Provided a partner address but no token address") if token_address and partner_address: channel_state = views.get_channelstate_for( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, partner_address=partner_address, ) if channel_state: result = [channel_state] else: result = [] elif token_address: result = views.list_channelstate_for_tokennetwork( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, ) else: result = views.list_all_channelstate(chain_state=views.state_from_raiden(self.raiden)) return result def get_node_network_state(self, node_address: Address) -> NetworkState: return views.get_node_network_status( chain_state=views.state_from_raiden(self.raiden), node_address=node_address ) def async_start_health_check_for(self, node_address: Address) -> None: self.raiden.async_start_health_check_for(node_address) def get_tokens_list(self, registry_address: TokenNetworkRegistryAddress) -> List[TokenAddress]: return views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, ) def get_token_network_address_for_token_address( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress ) -> Optional[TokenNetworkAddress]: return views.get_token_network_address_by_token_address( chain_state=views.state_from_raiden(self.raiden), token_network_registry_address=registry_address, token_address=token_address, ) def transfer_and_wait( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, amount: PaymentAmount, target: TargetAddress, identifier: PaymentID = None, transfer_timeout: int = None, secret: Secret = None, secrethash: SecretHash = None, lock_timeout: BlockTimeout = None, ) -> "PaymentStatus": payment_status = self.transfer_async( registry_address=registry_address, token_address=token_address, amount=amount, target=target, identifier=identifier, secret=secret, secrethash=secrethash, lock_timeout=lock_timeout, ) payment_status.payment_done.wait(timeout=transfer_timeout) return payment_status def transfer_async( self, registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, amount: PaymentAmount, target: TargetAddress, identifier: PaymentID = None, secret: Secret = None, secrethash: SecretHash = None, lock_timeout: BlockTimeout = None, ) -> "PaymentStatus": current_state = views.state_from_raiden(self.raiden) token_network_registry_address = self.raiden.default_registry.address if not isinstance(amount, int): raise InvalidAmount("Amount not a number") if Address(target) == self.address: raise SamePeerAddress("Address must be different than ours") if amount <= 0: raise InvalidAmount("Amount negative") if amount > UINT256_MAX: raise InvalidAmount("Amount too large") if not is_binary_address(token_address): raise InvalidBinaryAddress("token address is not valid.") if token_address not in views.get_token_identifiers(current_state, registry_address): raise UnknownTokenAddress("Token address is not known.") if not is_binary_address(target): raise InvalidBinaryAddress("target address is not valid.") valid_tokens = views.get_token_identifiers( views.state_from_raiden(self.raiden), registry_address ) if token_address not in valid_tokens: raise UnknownTokenAddress("Token address is not known.") if secret is not None and not isinstance(secret, T_Secret): raise InvalidSecret("secret is not valid.") if secrethash is not None and not isinstance(secrethash, T_SecretHash): raise InvalidSecretHash("secrethash is not valid.") if identifier is None: identifier = create_default_identifier() if identifier <= 0: raise InvalidPaymentIdentifier("Payment identifier cannot be 0 or negative") if identifier > UINT64_MAX: raise InvalidPaymentIdentifier("Payment identifier is too large") log.debug( "Initiating transfer", initiator=to_checksum_address(self.raiden.address), target=to_checksum_address(target), token=to_checksum_address(token_address), amount=amount, identifier=identifier, ) token_network_address = views.get_token_network_address_by_token_address( chain_state=current_state, token_network_registry_address=token_network_registry_address, token_address=token_address, ) if token_network_address is None: raise UnknownTokenAddress( f"Token {to_checksum_address(token_address)} is not registered " f"with the network {to_checksum_address(registry_address)}." ) payment_status = self.raiden.mediated_transfer_async( token_network_address=token_network_address, amount=amount, target=target, identifier=identifier, secret=secret, secrethash=secrethash, lock_timeout=lock_timeout, ) return payment_status def get_raiden_events_payment_history_with_timestamps( self, registry_address: TokenNetworkRegistryAddress, token_address: Optional[TokenAddress] = None, target_address: Address = None, limit: int = None, offset: int = None, ) -> List[TimestampedEvent]: if token_address and not is_binary_address(token_address): raise InvalidBinaryAddress( "Expected binary address format for token in get_raiden_events_payment_history" ) chain_state = views.state_from_raiden(self.raiden) token_network_address = None if token_address: token_network_address = views.get_token_network_address_by_token_address( chain_state=chain_state, token_network_registry_address=registry_address, token_address=token_address, ) if not token_network_address: raise InvalidTokenAddress("Token address does not match a Raiden token network") if target_address and not is_binary_address(target_address): raise InvalidBinaryAddress( "Expected binary address format for " "target_address in get_raiden_events_payment_history" ) assert self.raiden.wal, "Raiden service has to be started for the API to be usable." event_types = [ "raiden.transfer.events.EventPaymentReceivedSuccess", "raiden.transfer.events.EventPaymentSentFailed", "raiden.transfer.events.EventPaymentSentSuccess", ] events = self.raiden.wal.storage.get_raiden_events_payment_history_with_timestamps( event_types=event_types, limit=limit, offset=offset, token_network_address=token_network_address, partner_address=target_address, ) events = [ e for e in events if event_filter_for_payments( event=e.wrapped_event, chain_state=chain_state, partner_address=target_address, token_address=token_address, ) ] return events def get_raiden_internal_events_with_timestamps( self, limit: int = None, offset: int = None ) -> List[TimestampedEvent]: assert self.raiden.wal, "Raiden service has to be started for the API to be usable." return self.raiden.wal.storage.get_events_with_timestamps(limit=limit, offset=offset) transfer = transfer_and_wait def get_pending_transfers( self, token_address: TokenAddress = None, partner_address: Address = None ) -> List[Dict[str, Any]]: chain_state = views.state_from_raiden(self.raiden) transfer_tasks = views.get_all_transfer_tasks(chain_state) channel_id = None confirmed_block_identifier = chain_state.block_hash if token_address is not None: token_network = self.raiden.default_registry.get_token_network( token_address=token_address, block_identifier=confirmed_block_identifier ) if token_network is None: raise UnknownTokenAddress(f"Token {to_checksum_address(token_address)} not found.") if partner_address is not None: partner_channel = views.get_channelstate_for( chain_state=chain_state, token_network_registry_address=self.raiden.default_registry.address, token_address=token_address, partner_address=partner_address, ) if not partner_channel: raise ChannelNotFound("Channel with partner `partner_address not found.`") channel_id = partner_channel.identifier return transfer_tasks_view(transfer_tasks, token_address, channel_id) def shutdown(self) -> None: self.raiden.stop()
true
true
1c373dd0d127a633c7497cc5b0d9eec268b0977d
4,534
py
Python
data/train/python/c6121a7ca78a1a55a7232b13b709dce7aac3c5c9intelliRepository.py
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/python/c6121a7ca78a1a55a7232b13b709dce7aac3c5c9intelliRepository.py
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/python/c6121a7ca78a1a55a7232b13b709dce7aac3c5c9intelliRepository.py
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
''' Represents a GitHub repository @since 1.0 @author Oskar Jarczyk ''' class MyRepository(): element_type = 'Team' key = None def __init__(self): self.data = [] repository_branches = None repository_commits = None repository_contributors = None repository_created_at = None repository_description = None repository_fork = None repository_forks = None repository_forks_count = None repository_has_downloads = None repository_has_issues = None repository_has_wiki = None repository_homepage = None repository_integrate_branch = None repository_issues = None repository_labels = None repository_language = None repository_master_branch = None repository_name = None repository_open_issues = None repository_organization = None repository_owner = None repository_private = None repository_pulls = None repository_pushed_at = None repository_size = None repository_stargazers = None repository_subscribers = None repository_watchers = None repository_url = None repo_object = None def setRepoObject(self, repoobject): self.repo_object = repoobject def getRepoObject(self): return self.repo_object def setKey(self, key): self.key = key def getKey(self): return self.key def purge(self): 'TO DO: implement this method' 'basicly first init of data transcripted from input (csvs)' 'name with owner, and count of forks and watchers' def setInitials(self, name, owner): self.repository_name = name self.repository_owner = owner def setName(self, name): self.repository_name = name def getName(self): return self.repository_name def setOwner(self, owner): self.repository_owner = owner def getOwner(self): return self.repository_owner def setForks(self, forks): self.repository_forks = forks def setCommits(self, commits): self.repository_commits = commits def getCommits(self): return self.repository_commits def getCommitsCount(self): return (len(self.repository_commits) if self.repository_commits is not None else 0) def getForks(self): return self.repository_forks def getForksCount(self): return self.repository_forks_count def setWatchers(self, watchers): self.repository_watchers = watchers def getWatchers(self): return self.repository_watchers def getWatchersCount(self): return self.repository_watchers_count def setContributors(self, contributors): self.repository_contributors = contributors def getContributors(self): return self.repository_contributors def getContributorsCount(self): return (len(self.repository_contributors) if self.repository_contributors is not None else 0) def setSubscribers(self, subscribers): self.repository_subscribers = subscribers def getSubscribers(self,): return self.repository_subscribers def getSubscribersCount(self): return (len(self.repository_subscribers) if self.repository_subscribers is not None else 0) def setStargazers(self, stargazers): self.repository_stargazers = stargazers def getStargazers(self): return self.repository_stargazers def getStargazersCount(self): return (len(self.repository_stargazers) if self.repository_stargazers is not None else 0) def setLanguage(self, languages): self.repository_language = languages def setLabels(self, labels): self.repository_labels = labels def getLabels(self): return self.repository_labels def getLabelsCount(self): return (len(self.repository_labels) if self.repository_labels is not None else 0) def setIssues(self, issues): self.repository_issues = issues def getIssues(self): return self.repository_issues def getIssuesCount(self): return (len(self.repository_issues) if self.repository_issues is not None else 0) def setBranches(self, branches): self.repository_branches = branches def setPulls(self, pulls): self.repository_pulls = pulls def getPulls(self): return self.repository_pulls def getPullsCount(self): return (len(self.repository_pulls) if self.repository_pulls is not None else 0) def getLanguages(self): return self.repository_language
26.670588
101
0.701147
class MyRepository(): element_type = 'Team' key = None def __init__(self): self.data = [] repository_branches = None repository_commits = None repository_contributors = None repository_created_at = None repository_description = None repository_fork = None repository_forks = None repository_forks_count = None repository_has_downloads = None repository_has_issues = None repository_has_wiki = None repository_homepage = None repository_integrate_branch = None repository_issues = None repository_labels = None repository_language = None repository_master_branch = None repository_name = None repository_open_issues = None repository_organization = None repository_owner = None repository_private = None repository_pulls = None repository_pushed_at = None repository_size = None repository_stargazers = None repository_subscribers = None repository_watchers = None repository_url = None repo_object = None def setRepoObject(self, repoobject): self.repo_object = repoobject def getRepoObject(self): return self.repo_object def setKey(self, key): self.key = key def getKey(self): return self.key def purge(self): def setInitials(self, name, owner): self.repository_name = name self.repository_owner = owner def setName(self, name): self.repository_name = name def getName(self): return self.repository_name def setOwner(self, owner): self.repository_owner = owner def getOwner(self): return self.repository_owner def setForks(self, forks): self.repository_forks = forks def setCommits(self, commits): self.repository_commits = commits def getCommits(self): return self.repository_commits def getCommitsCount(self): return (len(self.repository_commits) if self.repository_commits is not None else 0) def getForks(self): return self.repository_forks def getForksCount(self): return self.repository_forks_count def setWatchers(self, watchers): self.repository_watchers = watchers def getWatchers(self): return self.repository_watchers def getWatchersCount(self): return self.repository_watchers_count def setContributors(self, contributors): self.repository_contributors = contributors def getContributors(self): return self.repository_contributors def getContributorsCount(self): return (len(self.repository_contributors) if self.repository_contributors is not None else 0) def setSubscribers(self, subscribers): self.repository_subscribers = subscribers def getSubscribers(self,): return self.repository_subscribers def getSubscribersCount(self): return (len(self.repository_subscribers) if self.repository_subscribers is not None else 0) def setStargazers(self, stargazers): self.repository_stargazers = stargazers def getStargazers(self): return self.repository_stargazers def getStargazersCount(self): return (len(self.repository_stargazers) if self.repository_stargazers is not None else 0) def setLanguage(self, languages): self.repository_language = languages def setLabels(self, labels): self.repository_labels = labels def getLabels(self): return self.repository_labels def getLabelsCount(self): return (len(self.repository_labels) if self.repository_labels is not None else 0) def setIssues(self, issues): self.repository_issues = issues def getIssues(self): return self.repository_issues def getIssuesCount(self): return (len(self.repository_issues) if self.repository_issues is not None else 0) def setBranches(self, branches): self.repository_branches = branches def setPulls(self, pulls): self.repository_pulls = pulls def getPulls(self): return self.repository_pulls def getPullsCount(self): return (len(self.repository_pulls) if self.repository_pulls is not None else 0) def getLanguages(self): return self.repository_language
true
true
1c373ec95eda5483719d28073d1e4fe47ee6d6e0
2,252
py
Python
openGaussBase/testcase/SQL/DML/set/Opengauss_Function_DML_Set_Case0132.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/SQL/DML/set/Opengauss_Function_DML_Set_Case0132.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/SQL/DML/set/Opengauss_Function_DML_Set_Case0132.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ ''' -- @testpoint:explain analyze语句分析delete语句 ''' import sys import unittest sys.path.append(sys.path[0]+"/../") from testcase.utils.Logger import Logger from testcase.utils.Constant import Constant from testcase.utils.CommonSH import CommonSH logger = Logger() commonsh = CommonSH('dbuser') constant = Constant() class SYS_Operation(unittest.TestCase): def setUp(self): logger.info('------------------------Opengauss_Function_DML_Set_Case0132开始执行-----------------------------') def test_explain(self): # 建表并插入数据 sql_cmd1 = commonsh.execut_db_sql('''drop table if exists my_table; create table my_table (id int,name varchar(20)); insert into my_table values(1,'Wiliian'),(2,'Nakli'),(3,'uisvc'),(4,'yuiy');''') logger.info(sql_cmd1) self.assertIn(constant.TABLE_CREATE_SUCCESS, sql_cmd1) self.assertIn(constant.INSERT_SUCCESS_MSG, sql_cmd1) # explain analyze语句执行delete语句;回滚(id为3的数据恢复) sql_cmd2 = commonsh.execut_db_sql('''explain analyze delete from my_table where id =4; start transaction; explain analyze VERBOSE delete from my_table where id =3; select * from my_table; rollback;''') logger.info(sql_cmd2) self.assertIn(constant.EXPLAIN_SUCCESS_MSG, sql_cmd2) self.assertIn(constant.START_TRANSACTION_SUCCESS_MSG, sql_cmd2) self.assertIn(constant.ROLLBACK_MSG, sql_cmd2) # 清理环境 def tearDown(self): logger.info('----------this is teardown-------') sql_cmd3 = commonsh.execut_db_sql('''drop table my_table;''') logger.info(sql_cmd3) logger.info('------------------------Opengauss_Function_DML_Set_Case0132执行结束--------------------------')
38.169492
115
0.6754
import sys import unittest sys.path.append(sys.path[0]+"/../") from testcase.utils.Logger import Logger from testcase.utils.Constant import Constant from testcase.utils.CommonSH import CommonSH logger = Logger() commonsh = CommonSH('dbuser') constant = Constant() class SYS_Operation(unittest.TestCase): def setUp(self): logger.info('------------------------Opengauss_Function_DML_Set_Case0132开始执行-----------------------------') def test_explain(self): sql_cmd1 = commonsh.execut_db_sql('''drop table if exists my_table; create table my_table (id int,name varchar(20)); insert into my_table values(1,'Wiliian'),(2,'Nakli'),(3,'uisvc'),(4,'yuiy');''') logger.info(sql_cmd1) self.assertIn(constant.TABLE_CREATE_SUCCESS, sql_cmd1) self.assertIn(constant.INSERT_SUCCESS_MSG, sql_cmd1) sql_cmd2 = commonsh.execut_db_sql('''explain analyze delete from my_table where id =4; start transaction; explain analyze VERBOSE delete from my_table where id =3; select * from my_table; rollback;''') logger.info(sql_cmd2) self.assertIn(constant.EXPLAIN_SUCCESS_MSG, sql_cmd2) self.assertIn(constant.START_TRANSACTION_SUCCESS_MSG, sql_cmd2) self.assertIn(constant.ROLLBACK_MSG, sql_cmd2) def tearDown(self): logger.info('----------this is teardown-------') sql_cmd3 = commonsh.execut_db_sql('''drop table my_table;''') logger.info(sql_cmd3) logger.info('------------------------Opengauss_Function_DML_Set_Case0132执行结束--------------------------')
true
true
1c373f5fc0448b5ede6756285a99d5e803ce14b2
2,169
py
Python
rbig/_src/model.py
IPL-UV/rb
092d78a0ea5f9670c5cd4f70ff054ec58ff309af
[ "MIT" ]
6
2020-10-14T08:35:29.000Z
2022-02-18T23:26:30.000Z
rbig/_src/model.py
IPL-UV/rb
092d78a0ea5f9670c5cd4f70ff054ec58ff309af
[ "MIT" ]
11
2020-10-08T10:02:38.000Z
2021-03-26T16:00:41.000Z
rbig/_src/model.py
IPL-UV/rbig
092d78a0ea5f9670c5cd4f70ff054ec58ff309af
[ "MIT" ]
null
null
null
from typing import Union import numpy as np from scipy.stats import multivariate_normal from rbig._src.total_corr import information_reduction from rbig._src.training import train_rbig_info_loss from rbig._src.uniform import MarginalHistogramUniformization from rbig._src.invcdf import InverseGaussCDF from rbig._src.rotation import PCARotation, RandomRotation from rbig._src.base import FlowModel from tqdm import trange from sklearn.base import BaseEstimator, TransformerMixin class RBIG(BaseEstimator, TransformerMixin): def __init__( self, uniformizer: str = "hist", bins: Union[int, str] = "auto", alpha: float = 1e-10, bound_ext: float = 0.3, eps: float = 1e-10, rotation: str = "PCA", zero_tolerance: int = 60, max_layers: int = 1_000, max_iter: int = 10, ): self.uniformizer = uniformizer self.bins = bins self.alpha = alpha self.bound_ext = bound_ext self.eps = eps self.rotation = rotation self.zero_tolerance = zero_tolerance self.max_layers = max_layers self.max_iter = max_iter def fit(self, X, y=None): gf_model = train_rbig_info_loss( X=X, uniformizer=self.uniformizer, bins=self.bins, alpha=self.alpha, bound_ext=self.bound_ext, eps=self.eps, rotation=self.rotation, zero_tolerance=self.zero_tolerance, max_layers=self.max_layers, max_iter=self.max_iter, ) self.gf_model = gf_model self.info_loss = gf_model.info_loss return self def transform(self, X, y=None): return self.gf_model.forward(X) def inverse_transform(self, X, y=None): return self.gf_model.inverse(X) def log_det_jacobian(self, X, y=None): return self.gf_model.gradient(X) def predict_proba(self, X, y=None): return self.gf_model.predict_proba(X) def sample(self, n_samples: int = 10): return self.gf_model.sample(n_samples) def total_correlation(self): return self.info_loss.sum()
30.125
61
0.646842
from typing import Union import numpy as np from scipy.stats import multivariate_normal from rbig._src.total_corr import information_reduction from rbig._src.training import train_rbig_info_loss from rbig._src.uniform import MarginalHistogramUniformization from rbig._src.invcdf import InverseGaussCDF from rbig._src.rotation import PCARotation, RandomRotation from rbig._src.base import FlowModel from tqdm import trange from sklearn.base import BaseEstimator, TransformerMixin class RBIG(BaseEstimator, TransformerMixin): def __init__( self, uniformizer: str = "hist", bins: Union[int, str] = "auto", alpha: float = 1e-10, bound_ext: float = 0.3, eps: float = 1e-10, rotation: str = "PCA", zero_tolerance: int = 60, max_layers: int = 1_000, max_iter: int = 10, ): self.uniformizer = uniformizer self.bins = bins self.alpha = alpha self.bound_ext = bound_ext self.eps = eps self.rotation = rotation self.zero_tolerance = zero_tolerance self.max_layers = max_layers self.max_iter = max_iter def fit(self, X, y=None): gf_model = train_rbig_info_loss( X=X, uniformizer=self.uniformizer, bins=self.bins, alpha=self.alpha, bound_ext=self.bound_ext, eps=self.eps, rotation=self.rotation, zero_tolerance=self.zero_tolerance, max_layers=self.max_layers, max_iter=self.max_iter, ) self.gf_model = gf_model self.info_loss = gf_model.info_loss return self def transform(self, X, y=None): return self.gf_model.forward(X) def inverse_transform(self, X, y=None): return self.gf_model.inverse(X) def log_det_jacobian(self, X, y=None): return self.gf_model.gradient(X) def predict_proba(self, X, y=None): return self.gf_model.predict_proba(X) def sample(self, n_samples: int = 10): return self.gf_model.sample(n_samples) def total_correlation(self): return self.info_loss.sum()
true
true
1c373fccd56b7e01a344247d3f3023ebcbaa5996
5,989
py
Python
speech/google/cloud/speech_v1p1beta1/gapic/transports/speech_grpc_transport.py
ryanyuan/google-cloud-python
db481bfdd6816d020d99df0d4caa307358ab1141
[ "Apache-2.0" ]
2
2021-11-26T07:08:43.000Z
2022-03-07T20:20:04.000Z
speech/google/cloud/speech_v1p1beta1/gapic/transports/speech_grpc_transport.py
ryanyuan/google-cloud-python
db481bfdd6816d020d99df0d4caa307358ab1141
[ "Apache-2.0" ]
null
null
null
speech/google/cloud/speech_v1p1beta1/gapic/transports/speech_grpc_transport.py
ryanyuan/google-cloud-python
db481bfdd6816d020d99df0d4caa307358ab1141
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import google.api_core.grpc_helpers import google.api_core.operations_v1 from google.cloud.speech_v1p1beta1.proto import cloud_speech_pb2_grpc class SpeechGrpcTransport(object): """gRPC transport class providing stubs for google.cloud.speech.v1p1beta1 Speech API. The transport provides access to the raw gRPC stubs, which can be used to take advantage of advanced features of gRPC. """ # The scopes needed to make gRPC calls to all of the methods defined # in this service. _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) def __init__( self, channel=None, credentials=None, address="speech.googleapis.com:443" ): """Instantiate the transport class. Args: channel (grpc.Channel): A ``Channel`` instance through which to make calls. This argument is mutually exclusive with ``credentials``; providing both will raise an exception. credentials (google.auth.credentials.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. address (str): The address where the service is hosted. """ # If both `channel` and `credentials` are specified, raise an # exception (channels come with credentials baked in already). if channel is not None and credentials is not None: raise ValueError( "The `channel` and `credentials` arguments are mutually " "exclusive." ) # Create the channel. if channel is None: channel = self.create_channel( address=address, credentials=credentials, options={ "grpc.max_send_message_length": -1, "grpc.max_receive_message_length": -1, }.items(), ) self._channel = channel # gRPC uses objects called "stubs" that are bound to the # channel and provide a basic method for each RPC. self._stubs = {"speech_stub": cloud_speech_pb2_grpc.SpeechStub(channel)} # Because this API includes a method that returns a # long-running operation (proto: google.longrunning.Operation), # instantiate an LRO client. self._operations_client = google.api_core.operations_v1.OperationsClient( channel ) @classmethod def create_channel( cls, address="speech.googleapis.com:443", credentials=None, **kwargs ): """Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. kwargs (dict): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. """ return google.api_core.grpc_helpers.create_channel( address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs ) @property def channel(self): """The gRPC channel used by the transport. Returns: grpc.Channel: A gRPC channel object. """ return self._channel @property def recognize(self): """Return the gRPC stub for :meth:`SpeechClient.recognize`. Performs synchronous speech recognition: receive results after all audio has been sent and processed. Returns: Callable: A callable which accepts the appropriate deserialized request object and returns a deserialized response object. """ return self._stubs["speech_stub"].Recognize @property def long_running_recognize(self): """Return the gRPC stub for :meth:`SpeechClient.long_running_recognize`. Performs asynchronous speech recognition: receive results via the google.longrunning.Operations interface. Returns either an ``Operation.error`` or an ``Operation.response`` which contains a ``LongRunningRecognizeResponse`` message. Returns: Callable: A callable which accepts the appropriate deserialized request object and returns a deserialized response object. """ return self._stubs["speech_stub"].LongRunningRecognize @property def streaming_recognize(self): """Return the gRPC stub for :meth:`SpeechClient.streaming_recognize`. Performs bidirectional streaming speech recognition: receive results while sending audio. This method is only available via the gRPC API (not REST). Returns: Callable: A callable which accepts the appropriate deserialized request object and returns a deserialized response object. """ return self._stubs["speech_stub"].StreamingRecognize
37.666667
86
0.648355
import google.api_core.grpc_helpers import google.api_core.operations_v1 from google.cloud.speech_v1p1beta1.proto import cloud_speech_pb2_grpc class SpeechGrpcTransport(object): _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) def __init__( self, channel=None, credentials=None, address="speech.googleapis.com:443" ): if channel is not None and credentials is not None: raise ValueError( "The `channel` and `credentials` arguments are mutually " "exclusive." ) if channel is None: channel = self.create_channel( address=address, credentials=credentials, options={ "grpc.max_send_message_length": -1, "grpc.max_receive_message_length": -1, }.items(), ) self._channel = channel self._stubs = {"speech_stub": cloud_speech_pb2_grpc.SpeechStub(channel)} self._operations_client = google.api_core.operations_v1.OperationsClient( channel ) @classmethod def create_channel( cls, address="speech.googleapis.com:443", credentials=None, **kwargs ): return google.api_core.grpc_helpers.create_channel( address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs ) @property def channel(self): return self._channel @property def recognize(self): return self._stubs["speech_stub"].Recognize @property def long_running_recognize(self): return self._stubs["speech_stub"].LongRunningRecognize @property def streaming_recognize(self): return self._stubs["speech_stub"].StreamingRecognize
true
true
1c374061e51e46e86b91f48bd6e4f6110154e3f5
661
py
Python
Basic/DataType.py
samreachyan/programiz-python
cc518e196569918560276369046d755def7957fc
[ "MIT" ]
null
null
null
Basic/DataType.py
samreachyan/programiz-python
cc518e196569918560276369046d755def7957fc
[ "MIT" ]
null
null
null
Basic/DataType.py
samreachyan/programiz-python
cc518e196569918560276369046d755def7957fc
[ "MIT" ]
null
null
null
from fractions import Fraction as F import math print(F(1,3) + F(1,3)) print(1 / F(5, 6)) print(F(-3, 10) > 0) print(F(-3, 10) < 0) print(math.cos(math.pi * 2)) # list with mixed data types my_list = [1, "Hello", 3.4] print(my_list[1]) x = [1, 2, 4, 3, 16, 32, 64, 128, 256, 512] pow = [2 ** v for v in x] # pow = pow(2, x) for i in pow: print(i) ## String #Accessing string characters in Python str = 'programiz' print('str = ', str) #first character print('str[0] = ', str[0]) #last character print('str[-1] = ', str[-1]) #slicing 2nd to 5th character print('str[1:5] = ', str[1:5]) #slicing 6th to 2nd last character print('str[5:-2] = ', str[5:-2])
19.441176
43
0.606657
from fractions import Fraction as F import math print(F(1,3) + F(1,3)) print(1 / F(5, 6)) print(F(-3, 10) > 0) print(F(-3, 10) < 0) print(math.cos(math.pi * 2)) my_list = [1, "Hello", 3.4] print(my_list[1]) x = [1, 2, 4, 3, 16, 32, 64, 128, 256, 512] pow = [2 ** v for v in x] for i in pow: print(i) 'programiz' print('str = ', str) print('str[0] = ', str[0]) print('str[-1] = ', str[-1]) print('str[1:5] = ', str[1:5]) print('str[5:-2] = ', str[5:-2])
true
true
1c37408d1343db5b7eb476dd0f0b7517d4bd1379
1,138
py
Python
djimix/bin/get_uuid.py
carthage-college/django-djimix
8febd4ba9934f6830b7ff6d2dbfb6c1faec3eed5
[ "MIT" ]
null
null
null
djimix/bin/get_uuid.py
carthage-college/django-djimix
8febd4ba9934f6830b7ff6d2dbfb6c1faec3eed5
[ "MIT" ]
9
2020-03-29T15:01:10.000Z
2021-12-01T21:23:02.000Z
djimix/bin/get_uuid.py
carthage-college/django-djimix
8febd4ba9934f6830b7ff6d2dbfb6c1faec3eed5
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import argparse import os import sys from django.conf import settings from djimix.core.database import get_connection from djimix.core.database import xsql # set up command-line options desc = """ Accepts as input an email. """ # RawTextHelpFormatter method allows for new lines in help text parser = argparse.ArgumentParser( description=desc, formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument( '-e', '--email', required=True, help="User ID", dest='email', ) parser.add_argument( '--test', action='store_true', help="Dry run?", dest='test', ) def main(): """Fetch the UUID from the database based on the email provided.""" sql = "SELECT * FROM fwk_user WHERE email='{}'".format(email) connection = get_connection(settings.MSSQL_EARL, encoding=False) with connection: results = xsql(sql, connection, key='debug') row = results.fetchone() print(row) if __name__ == '__main__': args = parser.parse_args() email = args.email test = args.test if test: print(args) sys.exit(main())
20.321429
71
0.665202
import argparse import os import sys from django.conf import settings from djimix.core.database import get_connection from djimix.core.database import xsql desc = """ Accepts as input an email. """ parser = argparse.ArgumentParser( description=desc, formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument( '-e', '--email', required=True, help="User ID", dest='email', ) parser.add_argument( '--test', action='store_true', help="Dry run?", dest='test', ) def main(): sql = "SELECT * FROM fwk_user WHERE email='{}'".format(email) connection = get_connection(settings.MSSQL_EARL, encoding=False) with connection: results = xsql(sql, connection, key='debug') row = results.fetchone() print(row) if __name__ == '__main__': args = parser.parse_args() email = args.email test = args.test if test: print(args) sys.exit(main())
true
true
1c37410ce90da7bcb198a62afb542c9b8a091ca7
860
py
Python
units/prefix/loader/compile.py
hoefkensj/BTRWin
1432868ad60155f5ae26f33903a890497e089480
[ "MIT" ]
null
null
null
units/prefix/loader/compile.py
hoefkensj/BTRWin
1432868ad60155f5ae26f33903a890497e089480
[ "MIT" ]
null
null
null
units/prefix/loader/compile.py
hoefkensj/BTRWin
1432868ad60155f5ae26f33903a890497e089480
[ "MIT" ]
null
null
null
#!/usr/bin/env python import subprocess,argparse def getargs(): #get arguments from commandline parser=argparse.ArgumentParser() parser.add_argument('-i','--follow-imports',action='store_true' ,help='--follow imports') parser.add_argument('-1', '--onefile', action='store_true' ,help='--onefile') parser.add_argument('script', help='script.py|SCRIPT.PY') args = parser.parse_args() return args # MSOffice2010_EXCEL.PY' def main(): a=getargs() cmd=f'python -m nuitka {"--follow-imports" if a.follow_imports else ""} {"--onefile" if a.onefile else ""}{a.script}'# --follow-imports proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE,universal_newlines=True) while True: print(proc.stdout.readline().strip()) if proc.poll() is not None: print(proc.stdout.readlines()) break print(a) if __name__ == '__main__': getargs() main()
30.714286
136
0.716279
import subprocess,argparse def getargs(): parser=argparse.ArgumentParser() parser.add_argument('-i','--follow-imports',action='store_true' ,help='--follow imports') parser.add_argument('-1', '--onefile', action='store_true' ,help='--onefile') parser.add_argument('script', help='script.py|SCRIPT.PY') args = parser.parse_args() return args def main(): a=getargs() cmd=f'python -m nuitka {"--follow-imports" if a.follow_imports else ""} {"--onefile" if a.onefile else ""}{a.script}'# --follow-imports proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE,universal_newlines=True) while True: print(proc.stdout.readline().strip()) if proc.poll() is not None: print(proc.stdout.readlines()) break print(a) if __name__ == '__main__': getargs() main()
true
true
1c3741d9e4e783a4521c779baabc5897b77fcaf9
431
py
Python
workflow/scripts/sample_phrases.py
CambridgeSemiticsLab/BH_time_collocations
2d1864b6e9cd26624c769ee1e970d69d19da7fbf
[ "CC-BY-4.0" ]
5
2019-06-19T19:42:21.000Z
2021-04-20T22:43:45.000Z
workflow/scripts/sample_phrases.py
CambridgeSemiticsLab/BHTenseAndAspect
2d1864b6e9cd26624c769ee1e970d69d19da7fbf
[ "CC-BY-4.0" ]
2
2020-02-25T10:19:40.000Z
2020-03-13T15:29:01.000Z
workflow/scripts/sample_phrases.py
CambridgeSemiticsLab/BHTenseAndAspect
2d1864b6e9cd26624c769ee1e970d69d19da7fbf
[ "CC-BY-4.0" ]
null
null
null
""" In this module we generate a sample of phrases drawn in from the ETCBC's BHSA Hebrew database. The database is accessed using Text-Fabric. It is subsequently processed using the scripts and modules indicated below. """ from sampling.phrase_sampling import get_phrase_samples # execute with snakemake arguments get_phrase_samples( snakemake.input.bhsadata, snakemake.output.samples, snakemake.output.nosamples, )
26.9375
75
0.793503
from sampling.phrase_sampling import get_phrase_samples get_phrase_samples( snakemake.input.bhsadata, snakemake.output.samples, snakemake.output.nosamples, )
true
true
1c37423dd47e435e0b3d39951736bfdca710e735
777
py
Python
Foresite/foresite/views.py
khoamb/Foresite
97b155452d92fe1c487e7cbeffbc867604a1e726
[ "MIT" ]
null
null
null
Foresite/foresite/views.py
khoamb/Foresite
97b155452d92fe1c487e7cbeffbc867604a1e726
[ "MIT" ]
6
2018-11-29T23:25:16.000Z
2018-11-30T01:17:33.000Z
Foresite/foresite/views.py
PricelessAntonio/Foresite
4eec1ab5bf588b1ef6ec176a612bc62e8d55b424
[ "MIT" ]
3
2018-09-05T18:57:03.000Z
2020-03-22T02:19:58.000Z
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.views.generic import CreateView, TemplateView, View from .forms import SignUpForm # Create your views here. class IndexView(TemplateView): template_name = "index.html" class SignupView(CreateView): form_class = SignUpForm template_name = "registration/signup.html" def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() return render(request, self.template_name, {'form': form})
27.75
66
0.685972
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.views.generic import CreateView, TemplateView, View from .forms import SignUpForm class IndexView(TemplateView): template_name = "index.html" class SignupView(CreateView): form_class = SignUpForm template_name = "registration/signup.html" def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() return render(request, self.template_name, {'form': form})
true
true
1c37426f59607c88ddc2fa145f8df2759ae486dd
1,935
py
Python
dizoo/d4rl/config/hopper_cql_default_config.py
lichuminglcm/DI-engine
e9052f195d231a9875afb053ba815c6341857571
[ "Apache-2.0" ]
null
null
null
dizoo/d4rl/config/hopper_cql_default_config.py
lichuminglcm/DI-engine
e9052f195d231a9875afb053ba815c6341857571
[ "Apache-2.0" ]
null
null
null
dizoo/d4rl/config/hopper_cql_default_config.py
lichuminglcm/DI-engine
e9052f195d231a9875afb053ba815c6341857571
[ "Apache-2.0" ]
null
null
null
from easydict import EasyDict hopper_cql_default_config = dict( env=dict( env_id='hopper-expert-v0', norm_obs=dict(use_norm=False, ), norm_reward=dict(use_norm=False, ), collector_env_num=1, evaluator_env_num=8, use_act_scale=True, n_evaluator_episode=8, stop_value=6000, ), policy=dict( cuda=True, on_policy=False, model=dict( obs_shape=11, action_shape=3, twin_critic=True, actor_head_type='reparameterization', actor_head_hidden_size=256, critic_head_hidden_size=256, ), learn=dict( data_path=None, train_epoch=30000, batch_size=256, learning_rate_q=3e-4, learning_rate_policy=1e-4, learning_rate_alpha=1e-4, ignore_done=False, target_theta=0.005, discount_factor=0.99, alpha=0.2, reparameterization=True, auto_alpha=False, lagrange_thresh=-1.0, min_q_weight=5.0, ), collect=dict( n_sample=1, unroll_len=1, data_type='d4rl', ), command=dict(), eval=dict(evaluator=dict(eval_freq=500, )), other=dict(replay_buffer=dict(replay_buffer_size=2000000, ), ), ), ) hopper_cql_default_config = EasyDict(hopper_cql_default_config) main_config = hopper_cql_default_config hopper_cql_default_create_config = dict( env=dict( type='d4rl', import_names=['dizoo.d4rl.envs.d4rl_env'], ), env_manager=dict(type='base'), policy=dict( type='cql', import_names=['ding.policy.cql'], ), replay_buffer=dict(type='naive', ), ) hopper_cql_default_create_config = EasyDict(hopper_cql_default_create_config) create_config = hopper_cql_default_create_config
28.043478
77
0.594315
from easydict import EasyDict hopper_cql_default_config = dict( env=dict( env_id='hopper-expert-v0', norm_obs=dict(use_norm=False, ), norm_reward=dict(use_norm=False, ), collector_env_num=1, evaluator_env_num=8, use_act_scale=True, n_evaluator_episode=8, stop_value=6000, ), policy=dict( cuda=True, on_policy=False, model=dict( obs_shape=11, action_shape=3, twin_critic=True, actor_head_type='reparameterization', actor_head_hidden_size=256, critic_head_hidden_size=256, ), learn=dict( data_path=None, train_epoch=30000, batch_size=256, learning_rate_q=3e-4, learning_rate_policy=1e-4, learning_rate_alpha=1e-4, ignore_done=False, target_theta=0.005, discount_factor=0.99, alpha=0.2, reparameterization=True, auto_alpha=False, lagrange_thresh=-1.0, min_q_weight=5.0, ), collect=dict( n_sample=1, unroll_len=1, data_type='d4rl', ), command=dict(), eval=dict(evaluator=dict(eval_freq=500, )), other=dict(replay_buffer=dict(replay_buffer_size=2000000, ), ), ), ) hopper_cql_default_config = EasyDict(hopper_cql_default_config) main_config = hopper_cql_default_config hopper_cql_default_create_config = dict( env=dict( type='d4rl', import_names=['dizoo.d4rl.envs.d4rl_env'], ), env_manager=dict(type='base'), policy=dict( type='cql', import_names=['ding.policy.cql'], ), replay_buffer=dict(type='naive', ), ) hopper_cql_default_create_config = EasyDict(hopper_cql_default_create_config) create_config = hopper_cql_default_create_config
true
true
1c3743d9e4589f25e08ba8da50e7690e20a6951b
836
py
Python
hyp3lib/__init__.py
washreve/hyp3-lib
5e7f11f1de9576a519b25fb56ccdb40e72ca9982
[ "BSD-3-Clause" ]
null
null
null
hyp3lib/__init__.py
washreve/hyp3-lib
5e7f11f1de9576a519b25fb56ccdb40e72ca9982
[ "BSD-3-Clause" ]
null
null
null
hyp3lib/__init__.py
washreve/hyp3-lib
5e7f11f1de9576a519b25fb56ccdb40e72ca9982
[ "BSD-3-Clause" ]
null
null
null
"""Common library for HyP3 plugins""" from __future__ import print_function, absolute_import, division, unicode_literals # FIXME: Python 3.8+ this should be `from importlib.metadata...` from importlib_metadata import PackageNotFoundError, version from hyp3lib.exceptions import ( DemError, ExecuteError, GeometryError, GranuleError, OrbitDownloadError, ) try: __version__ = version(__name__) except PackageNotFoundError: print('package is not installed!\n' 'Install in editable/develop mode via (from the top of this repo):\n' ' pip install -e .\n' 'Or, to just get the version number use:\n' ' python setup.py --version') __all__ = [ '__version__', 'DemError', 'ExecuteError', 'GeometryError', 'GranuleError', 'OrbitDownloadError', ]
25.333333
82
0.680622
from __future__ import print_function, absolute_import, division, unicode_literals from importlib_metadata import PackageNotFoundError, version from hyp3lib.exceptions import ( DemError, ExecuteError, GeometryError, GranuleError, OrbitDownloadError, ) try: __version__ = version(__name__) except PackageNotFoundError: print('package is not installed!\n' 'Install in editable/develop mode via (from the top of this repo):\n' ' pip install -e .\n' 'Or, to just get the version number use:\n' ' python setup.py --version') __all__ = [ '__version__', 'DemError', 'ExecuteError', 'GeometryError', 'GranuleError', 'OrbitDownloadError', ]
true
true
1c3743eedea7ac0acb51912c5bed08e5d3050199
47
py
Python
beaver/__init__.py
nullck/beaver-chef
85780d45cf5bbec5b609048ca4558e0e8d6d9898
[ "MIT" ]
null
null
null
beaver/__init__.py
nullck/beaver-chef
85780d45cf5bbec5b609048ca4558e0e8d6d9898
[ "MIT" ]
null
null
null
beaver/__init__.py
nullck/beaver-chef
85780d45cf5bbec5b609048ca4558e0e8d6d9898
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- __version__ = '36.1.0'
15.666667
23
0.531915
__version__ = '36.1.0'
true
true
1c3745ee664cb016dfde8a4e5d56995b890d54fb
1,900
py
Python
yoti_python_sdk/tests/doc_scan/session/create/filter/test_document_restrictions_filter.py
getyoti/python
3df169145d5c818d0e79743768dde78e482eec9b
[ "MIT" ]
9
2017-11-12T05:38:58.000Z
2021-08-04T16:33:26.000Z
yoti_python_sdk/tests/doc_scan/session/create/filter/test_document_restrictions_filter.py
getyoti/python
3df169145d5c818d0e79743768dde78e482eec9b
[ "MIT" ]
237
2017-04-26T09:40:44.000Z
2022-02-24T10:29:43.000Z
yoti_python_sdk/tests/doc_scan/session/create/filter/test_document_restrictions_filter.py
getyoti/python
3df169145d5c818d0e79743768dde78e482eec9b
[ "MIT" ]
9
2017-05-02T11:41:44.000Z
2021-04-28T13:49:20.000Z
import json from mock import Mock from yoti_python_sdk.doc_scan.session.create.filter import ( DocumentRestrictionsFilterBuilder, ) from yoti_python_sdk.doc_scan.session.create.filter.document_restrictions_filter import ( DocumentRestriction, ) from yoti_python_sdk.utils import YotiEncoder def test_should_set_inclusion_to_whitelist(): result = DocumentRestrictionsFilterBuilder().for_whitelist().build() assert result.inclusion == "WHITELIST" def test_should_set_inclusion_to_blacklist(): result = DocumentRestrictionsFilterBuilder().for_blacklist().build() assert result.inclusion == "BLACKLIST" def test_should_accept_document_restriction(): document_restriction_mock = Mock(spec=DocumentRestriction) result = ( DocumentRestrictionsFilterBuilder() .for_whitelist() .with_document_restriction(document_restriction_mock) .build() ) assert len(result.documents) == 1 assert result.documents[0] == document_restriction_mock def test_should_accept_multiple_document_restrictions(): document_restriction_mock = Mock(spec=DocumentRestriction) other_document_restriction_mock = Mock(spec=DocumentRestriction) result = ( DocumentRestrictionsFilterBuilder() .for_whitelist() .with_document_restriction(document_restriction_mock) .with_document_restriction(other_document_restriction_mock) .build() ) assert len(result.documents) == 2 def test_to_json_should_not_throw_exception(): document_restriction_mock = Mock(spec=DocumentRestriction) document_restriction_mock.to_json.return_value = {} result = ( DocumentRestrictionsFilterBuilder() .for_whitelist() .with_document_restriction(document_restriction_mock) .build() ) s = json.dumps(result, cls=YotiEncoder) assert s is not None and s != ""
27.941176
89
0.751053
import json from mock import Mock from yoti_python_sdk.doc_scan.session.create.filter import ( DocumentRestrictionsFilterBuilder, ) from yoti_python_sdk.doc_scan.session.create.filter.document_restrictions_filter import ( DocumentRestriction, ) from yoti_python_sdk.utils import YotiEncoder def test_should_set_inclusion_to_whitelist(): result = DocumentRestrictionsFilterBuilder().for_whitelist().build() assert result.inclusion == "WHITELIST" def test_should_set_inclusion_to_blacklist(): result = DocumentRestrictionsFilterBuilder().for_blacklist().build() assert result.inclusion == "BLACKLIST" def test_should_accept_document_restriction(): document_restriction_mock = Mock(spec=DocumentRestriction) result = ( DocumentRestrictionsFilterBuilder() .for_whitelist() .with_document_restriction(document_restriction_mock) .build() ) assert len(result.documents) == 1 assert result.documents[0] == document_restriction_mock def test_should_accept_multiple_document_restrictions(): document_restriction_mock = Mock(spec=DocumentRestriction) other_document_restriction_mock = Mock(spec=DocumentRestriction) result = ( DocumentRestrictionsFilterBuilder() .for_whitelist() .with_document_restriction(document_restriction_mock) .with_document_restriction(other_document_restriction_mock) .build() ) assert len(result.documents) == 2 def test_to_json_should_not_throw_exception(): document_restriction_mock = Mock(spec=DocumentRestriction) document_restriction_mock.to_json.return_value = {} result = ( DocumentRestrictionsFilterBuilder() .for_whitelist() .with_document_restriction(document_restriction_mock) .build() ) s = json.dumps(result, cls=YotiEncoder) assert s is not None and s != ""
true
true
1c37465f5578e6657eeac80c5145d09a42acd6c9
4,144
py
Python
poseidon/dags/water_tests/indicator_bacteria_jobs.py
panda-tech/poseidon-airflow
bce5bc02b55f15330635a436056d99acb93488ef
[ "Apache-2.0" ]
null
null
null
poseidon/dags/water_tests/indicator_bacteria_jobs.py
panda-tech/poseidon-airflow
bce5bc02b55f15330635a436056d99acb93488ef
[ "Apache-2.0" ]
null
null
null
poseidon/dags/water_tests/indicator_bacteria_jobs.py
panda-tech/poseidon-airflow
bce5bc02b55f15330635a436056d99acb93488ef
[ "Apache-2.0" ]
null
null
null
import cx_Oracle import pandas as pd import os import string import logging import re from datetime import datetime, timedelta from trident.util import general conf = general.config def get_indicator_bacteria_tests(date_start='01-JAN-2014', date_end='15-JUN-2017', **kwargs): # For test mode if kwargs['test_mode'] == True: logging.warning("RUNNING IN TEST MODE, PULLING LAST YEAR ONLY!!!!") date_start = (kwargs['execution_date'] - timedelta(days=365)).strftime('%d-%b-%Y') db = cx_Oracle.connect(conf['oracle_wpl']) logging.info("Starting Indicator Bac Tests: " + date_start + " to " + date_end) jzn_1_q = string.Template(general.file_to_string('./sql/jzn1.sql', __file__))\ .substitute(ds=date_start, de=date_end) jzn_2_q = string.Template(general.file_to_string('./sql/jzn2.sql', __file__))\ .substitute(ds=date_start, de=date_end) jzn_3_q = string.Template(general.file_to_string('./sql/jzn3.sql', __file__))\ .substitute(ds=date_start, de=date_end) jzn_4_q = string.Template(general.file_to_string('./sql/jzn4.sql', __file__))\ .substitute(ds=date_start, de=date_end) logging.info("Reading JZN1") jzn_1 = pd.read_sql_query(jzn_1_q, db, coerce_float=True, index_col='F_FIELD_RECORD') jzn_1.F_VALUE = pd.to_numeric(jzn_1.F_VALUE, errors='coerce') jzn_1 = jzn_1[jzn_1.F_VALUE.notnull()] logging.info("Reading JZN2") jzn_2 = pd.read_sql_query(jzn_2_q, db, coerce_float=True, index_col='F_FIELD_RECORD') jzn_2.F_VALUE = pd.to_numeric(jzn_2.F_VALUE, errors='coerce') jzn_2 = jzn_2[jzn_2.F_VALUE.notnull()] logging.info("Reading JZN3") jzn_3 = pd.read_sql_query(jzn_3_q, db, coerce_float=True, index_col='F_FIELD_RECORD') jzn_3.F_VALUE = pd.to_numeric(jzn_3.F_VALUE, errors='coerce') jzn_3 = jzn_3[jzn_3.F_VALUE.notnull()] logging.info("Reading JZN4") jzn_4 = pd.read_sql_query(jzn_4_q, db, coerce_float=True, index_col='F_FIELD_RECORD') jzn_4.F_VALUE = pd.to_numeric(jzn_4.F_VALUE, errors='coerce') jzn_4 = jzn_4[jzn_4.F_VALUE.notnull()] jn_1 = jzn_1.rename(columns={ 'SOURCE':'V5_SOURCE', 'SAMPLE_DATE':'V5_SAMPLE_DATE', 'SAMPLE_ID':'V5_SAMPLE_ID', 'F_VALUE':'V5_CL2_TOTAL', 'L_VALUE':'V5_T_COLIFORM' }).filter(like='V5',axis=1) jn_2 = jzn_2.rename(columns={ 'L_VALUE':'V5_E_COLI' }).filter(like='V5',axis=1) jn_3 = jzn_3.rename(columns={ 'F_QUAL':'V5_TEMP_PART1', 'F_VALUE':'V5_TEMP_PART2' }).filter(like='V5',axis=1) jn_4 = jzn_4.rename(columns={ 'F_QUAL':'V5_PH_PART1', 'F_VALUE':'V5_PH_PART2' }).filter(like='V5',axis=1) df = jn_1.join([jn_2, jn_3, jn_4], how='inner') df = df.rename(columns={ 'V5_PH_PART2':'V5_PH', 'V5_TEMP_PART2':'V5_TEMPERATURE', }) del df['V5_PH_PART1'] del df['V5_TEMP_PART1'] df.columns = [re.sub('V5\_','',x) for x in df.columns] df.columns = [x.lower() for x in df.columns] df = df.rename(columns={'sample_date':'date_sampled'}) df.index.rename(name='FR_NUM', inplace=True) new_file_path = conf['prod_data_dir'] + '/indicator_bacteria_tests_datasd_v1.csv' logging.info("Writing to " + new_file_path) df.to_csv(new_file_path, index=True, encoding='utf-8', doublequote=True, date_format=conf['date_format_ymd']) return "Indicator bacteria tests written to " + new_file_path def get_latest_bac_tests(): full_bacs_path = conf['prod_data_dir'] + "/indicator_bacteria_tests_datasd_v1.csv" bac_tests = pd.read_csv(full_bacs_path) bac_tests.date_sampled = pd.to_datetime(bac_tests.date_sampled, infer_datetime_format=True) df = bac_tests[bac_tests.date_sampled == max(bac_tests.date_sampled)] new_file_path = conf['prod_data_dir'] + '/latest_indicator_bac_tests_datasd_v1.csv' df.to_csv(new_file_path, index=False, encoding='utf-8', doublequote=True, date_format=conf['date_format_ymd']) return "Latest indicator bacteria tests written to " + new_file_path
34.247934
95
0.677847
import cx_Oracle import pandas as pd import os import string import logging import re from datetime import datetime, timedelta from trident.util import general conf = general.config def get_indicator_bacteria_tests(date_start='01-JAN-2014', date_end='15-JUN-2017', **kwargs): if kwargs['test_mode'] == True: logging.warning("RUNNING IN TEST MODE, PULLING LAST YEAR ONLY!!!!") date_start = (kwargs['execution_date'] - timedelta(days=365)).strftime('%d-%b-%Y') db = cx_Oracle.connect(conf['oracle_wpl']) logging.info("Starting Indicator Bac Tests: " + date_start + " to " + date_end) jzn_1_q = string.Template(general.file_to_string('./sql/jzn1.sql', __file__))\ .substitute(ds=date_start, de=date_end) jzn_2_q = string.Template(general.file_to_string('./sql/jzn2.sql', __file__))\ .substitute(ds=date_start, de=date_end) jzn_3_q = string.Template(general.file_to_string('./sql/jzn3.sql', __file__))\ .substitute(ds=date_start, de=date_end) jzn_4_q = string.Template(general.file_to_string('./sql/jzn4.sql', __file__))\ .substitute(ds=date_start, de=date_end) logging.info("Reading JZN1") jzn_1 = pd.read_sql_query(jzn_1_q, db, coerce_float=True, index_col='F_FIELD_RECORD') jzn_1.F_VALUE = pd.to_numeric(jzn_1.F_VALUE, errors='coerce') jzn_1 = jzn_1[jzn_1.F_VALUE.notnull()] logging.info("Reading JZN2") jzn_2 = pd.read_sql_query(jzn_2_q, db, coerce_float=True, index_col='F_FIELD_RECORD') jzn_2.F_VALUE = pd.to_numeric(jzn_2.F_VALUE, errors='coerce') jzn_2 = jzn_2[jzn_2.F_VALUE.notnull()] logging.info("Reading JZN3") jzn_3 = pd.read_sql_query(jzn_3_q, db, coerce_float=True, index_col='F_FIELD_RECORD') jzn_3.F_VALUE = pd.to_numeric(jzn_3.F_VALUE, errors='coerce') jzn_3 = jzn_3[jzn_3.F_VALUE.notnull()] logging.info("Reading JZN4") jzn_4 = pd.read_sql_query(jzn_4_q, db, coerce_float=True, index_col='F_FIELD_RECORD') jzn_4.F_VALUE = pd.to_numeric(jzn_4.F_VALUE, errors='coerce') jzn_4 = jzn_4[jzn_4.F_VALUE.notnull()] jn_1 = jzn_1.rename(columns={ 'SOURCE':'V5_SOURCE', 'SAMPLE_DATE':'V5_SAMPLE_DATE', 'SAMPLE_ID':'V5_SAMPLE_ID', 'F_VALUE':'V5_CL2_TOTAL', 'L_VALUE':'V5_T_COLIFORM' }).filter(like='V5',axis=1) jn_2 = jzn_2.rename(columns={ 'L_VALUE':'V5_E_COLI' }).filter(like='V5',axis=1) jn_3 = jzn_3.rename(columns={ 'F_QUAL':'V5_TEMP_PART1', 'F_VALUE':'V5_TEMP_PART2' }).filter(like='V5',axis=1) jn_4 = jzn_4.rename(columns={ 'F_QUAL':'V5_PH_PART1', 'F_VALUE':'V5_PH_PART2' }).filter(like='V5',axis=1) df = jn_1.join([jn_2, jn_3, jn_4], how='inner') df = df.rename(columns={ 'V5_PH_PART2':'V5_PH', 'V5_TEMP_PART2':'V5_TEMPERATURE', }) del df['V5_PH_PART1'] del df['V5_TEMP_PART1'] df.columns = [re.sub('V5\_','',x) for x in df.columns] df.columns = [x.lower() for x in df.columns] df = df.rename(columns={'sample_date':'date_sampled'}) df.index.rename(name='FR_NUM', inplace=True) new_file_path = conf['prod_data_dir'] + '/indicator_bacteria_tests_datasd_v1.csv' logging.info("Writing to " + new_file_path) df.to_csv(new_file_path, index=True, encoding='utf-8', doublequote=True, date_format=conf['date_format_ymd']) return "Indicator bacteria tests written to " + new_file_path def get_latest_bac_tests(): full_bacs_path = conf['prod_data_dir'] + "/indicator_bacteria_tests_datasd_v1.csv" bac_tests = pd.read_csv(full_bacs_path) bac_tests.date_sampled = pd.to_datetime(bac_tests.date_sampled, infer_datetime_format=True) df = bac_tests[bac_tests.date_sampled == max(bac_tests.date_sampled)] new_file_path = conf['prod_data_dir'] + '/latest_indicator_bac_tests_datasd_v1.csv' df.to_csv(new_file_path, index=False, encoding='utf-8', doublequote=True, date_format=conf['date_format_ymd']) return "Latest indicator bacteria tests written to " + new_file_path
true
true
1c3748250a5fdb92f1fd736156c1b95e83caaa8c
4,544
py
Python
tests/helpers/test_translation.py
petewill/home-assistant
5859dba4344f05fb8774aa1207e47ac28f627a67
[ "Apache-2.0" ]
3
2020-10-23T14:39:11.000Z
2021-02-17T14:40:17.000Z
tests/helpers/test_translation.py
petewill/home-assistant
5859dba4344f05fb8774aa1207e47ac28f627a67
[ "Apache-2.0" ]
39
2016-12-16T12:40:34.000Z
2017-02-13T17:53:42.000Z
tests/helpers/test_translation.py
petewill/home-assistant
5859dba4344f05fb8774aa1207e47ac28f627a67
[ "Apache-2.0" ]
6
2020-04-10T06:21:11.000Z
2021-07-01T08:53:38.000Z
"""Test the translation helper.""" # pylint: disable=protected-access from os import path from unittest.mock import patch import pytest import homeassistant.helpers.translation as translation from homeassistant.setup import async_setup_component from homeassistant.generated import config_flows from tests.common import mock_coro @pytest.fixture def mock_config_flows(): """Mock the config flows.""" flows = [] with patch.object(config_flows, "FLOWS", flows): yield flows def test_flatten(): """Test the flatten function.""" data = {"parent1": {"child1": "data1", "child2": "data2"}, "parent2": "data3"} flattened = translation.flatten(data) assert flattened == { "parent1.child1": "data1", "parent1.child2": "data2", "parent2": "data3", } async def test_component_translation_file(hass): """Test the component translation file function.""" assert await async_setup_component( hass, "switch", {"switch": [{"platform": "test"}, {"platform": "test_embedded"}]}, ) assert await async_setup_component(hass, "test_standalone", {"test_standalone"}) assert await async_setup_component(hass, "test_package", {"test_package"}) assert path.normpath( await translation.component_translation_file(hass, "switch.test", "en") ) == path.normpath( hass.config.path("custom_components", "test", ".translations", "switch.en.json") ) assert path.normpath( await translation.component_translation_file(hass, "switch.test_embedded", "en") ) == path.normpath( hass.config.path( "custom_components", "test_embedded", ".translations", "switch.en.json" ) ) assert ( await translation.component_translation_file(hass, "test_standalone", "en") is None ) assert path.normpath( await translation.component_translation_file(hass, "test_package", "en") ) == path.normpath( hass.config.path( "custom_components", "test_package", ".translations", "en.json" ) ) def test_load_translations_files(hass): """Test the load translation files function.""" # Test one valid and one invalid file file1 = hass.config.path( "custom_components", "test", ".translations", "switch.en.json" ) file2 = hass.config.path( "custom_components", "test", ".translations", "invalid.json" ) assert translation.load_translations_files( {"switch.test": file1, "invalid": file2} ) == { "switch.test": {"state": {"string1": "Value 1", "string2": "Value 2"}}, "invalid": {}, } async def test_get_translations(hass, mock_config_flows): """Test the get translations helper.""" translations = await translation.async_get_translations(hass, "en") assert translations == {} assert await async_setup_component(hass, "switch", {"switch": {"platform": "test"}}) translations = await translation.async_get_translations(hass, "en") assert translations["component.switch.state.string1"] == "Value 1" assert translations["component.switch.state.string2"] == "Value 2" translations = await translation.async_get_translations(hass, "de") assert translations["component.switch.state.string1"] == "German Value 1" assert translations["component.switch.state.string2"] == "German Value 2" # Test a partial translation translations = await translation.async_get_translations(hass, "es") assert translations["component.switch.state.string1"] == "Spanish Value 1" assert translations["component.switch.state.string2"] == "Value 2" # Test that an untranslated language falls back to English. translations = await translation.async_get_translations(hass, "invalid-language") assert translations["component.switch.state.string1"] == "Value 1" assert translations["component.switch.state.string2"] == "Value 2" async def test_get_translations_loads_config_flows(hass, mock_config_flows): """Test the get translations helper loads config flow translations.""" mock_config_flows.append("component1") with patch.object( translation, "component_translation_file", return_value=mock_coro("bla.json") ), patch.object( translation, "load_translations_files", return_value={"component1": {"hello": "world"}}, ): translations = await translation.async_get_translations(hass, "en") assert translations == {"component.component1.hello": "world"}
34.953846
88
0.680238
from os import path from unittest.mock import patch import pytest import homeassistant.helpers.translation as translation from homeassistant.setup import async_setup_component from homeassistant.generated import config_flows from tests.common import mock_coro @pytest.fixture def mock_config_flows(): flows = [] with patch.object(config_flows, "FLOWS", flows): yield flows def test_flatten(): data = {"parent1": {"child1": "data1", "child2": "data2"}, "parent2": "data3"} flattened = translation.flatten(data) assert flattened == { "parent1.child1": "data1", "parent1.child2": "data2", "parent2": "data3", } async def test_component_translation_file(hass): assert await async_setup_component( hass, "switch", {"switch": [{"platform": "test"}, {"platform": "test_embedded"}]}, ) assert await async_setup_component(hass, "test_standalone", {"test_standalone"}) assert await async_setup_component(hass, "test_package", {"test_package"}) assert path.normpath( await translation.component_translation_file(hass, "switch.test", "en") ) == path.normpath( hass.config.path("custom_components", "test", ".translations", "switch.en.json") ) assert path.normpath( await translation.component_translation_file(hass, "switch.test_embedded", "en") ) == path.normpath( hass.config.path( "custom_components", "test_embedded", ".translations", "switch.en.json" ) ) assert ( await translation.component_translation_file(hass, "test_standalone", "en") is None ) assert path.normpath( await translation.component_translation_file(hass, "test_package", "en") ) == path.normpath( hass.config.path( "custom_components", "test_package", ".translations", "en.json" ) ) def test_load_translations_files(hass): file1 = hass.config.path( "custom_components", "test", ".translations", "switch.en.json" ) file2 = hass.config.path( "custom_components", "test", ".translations", "invalid.json" ) assert translation.load_translations_files( {"switch.test": file1, "invalid": file2} ) == { "switch.test": {"state": {"string1": "Value 1", "string2": "Value 2"}}, "invalid": {}, } async def test_get_translations(hass, mock_config_flows): translations = await translation.async_get_translations(hass, "en") assert translations == {} assert await async_setup_component(hass, "switch", {"switch": {"platform": "test"}}) translations = await translation.async_get_translations(hass, "en") assert translations["component.switch.state.string1"] == "Value 1" assert translations["component.switch.state.string2"] == "Value 2" translations = await translation.async_get_translations(hass, "de") assert translations["component.switch.state.string1"] == "German Value 1" assert translations["component.switch.state.string2"] == "German Value 2" translations = await translation.async_get_translations(hass, "es") assert translations["component.switch.state.string1"] == "Spanish Value 1" assert translations["component.switch.state.string2"] == "Value 2" translations = await translation.async_get_translations(hass, "invalid-language") assert translations["component.switch.state.string1"] == "Value 1" assert translations["component.switch.state.string2"] == "Value 2" async def test_get_translations_loads_config_flows(hass, mock_config_flows): mock_config_flows.append("component1") with patch.object( translation, "component_translation_file", return_value=mock_coro("bla.json") ), patch.object( translation, "load_translations_files", return_value={"component1": {"hello": "world"}}, ): translations = await translation.async_get_translations(hass, "en") assert translations == {"component.component1.hello": "world"}
true
true
1c374898cda456a3b4514d9c1c42bda9eec6f425
16,120
py
Python
tutorials/3_reinforce/experiments/Solve_BipedalWalker/DDPG.py
wull566/tensorflow_demo
c2c45050867cb056b8193eb53466d26b80b0ec13
[ "MIT" ]
2
2019-03-24T12:58:17.000Z
2021-05-18T06:21:21.000Z
tutorials/3_reinforce/experiments/Solve_BipedalWalker/DDPG.py
wull566/tensorflow_demo
c2c45050867cb056b8193eb53466d26b80b0ec13
[ "MIT" ]
null
null
null
tutorials/3_reinforce/experiments/Solve_BipedalWalker/DDPG.py
wull566/tensorflow_demo
c2c45050867cb056b8193eb53466d26b80b0ec13
[ "MIT" ]
null
null
null
import tensorflow as tf import numpy as np import gym import os import shutil np.random.seed(1) tf.set_random_seed(1) MAX_EPISODES = 2000 LR_A = 0.0005 # 1_tensorflow_new rate for actor LR_C = 0.0005 # 1_tensorflow_new rate for critic GAMMA = 0.999 # reward discount REPLACE_ITER_A = 1700 REPLACE_ITER_C = 1500 MEMORY_CAPACITY = 200000 BATCH_SIZE = 32 DISPLAY_THRESHOLD = 100 # display until the running reward > 100 DATA_PATH = './data' LOAD_MODEL = False SAVE_MODEL_ITER = 100000 RENDER = False OUTPUT_GRAPH = False ENV_NAME = 'BipedalWalker-v2' GLOBAL_STEP = tf.Variable(0, trainable=False) INCREASE_GS = GLOBAL_STEP.assign(tf.add(GLOBAL_STEP, 1)) LR_A = tf.train.exponential_decay(LR_A, GLOBAL_STEP, 10000, .97, staircase=True) LR_C = tf.train.exponential_decay(LR_C, GLOBAL_STEP, 10000, .97, staircase=True) END_POINT = (200 - 10) * (14/30) # from game env = gym.make(ENV_NAME) env.seed(1) STATE_DIM = env.observation_space.shape[0] # 24 ACTION_DIM = env.action_space.shape[0] # 4 ACTION_BOUND = env.action_space.high # [1, 1, 1, 1] # all placeholder for tf with tf.name_scope('S'): S = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s') with tf.name_scope('R'): R = tf.placeholder(tf.float32, [None, 1], name='r') with tf.name_scope('S_'): S_ = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s_') ############################### Actor #################################### class Actor(object): def __init__(self, sess, action_dim, action_bound, learning_rate, t_replace_iter): self.sess = sess self.a_dim = action_dim self.action_bound = action_bound self.lr = learning_rate self.t_replace_iter = t_replace_iter self.t_replace_counter = 0 with tf.variable_scope('Actor'): # input s, output a self.a = self._build_net(S, scope='eval_net', trainable=True) # input s_, output a, get a_ for critic self.a_ = self._build_net(S_, scope='target_net', trainable=False) self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Actor/eval_net') self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Actor/target_net') def _build_net(self, s, scope, trainable): with tf.variable_scope(scope): init_w = tf.random_normal_initializer(0., 0.01) init_b = tf.constant_initializer(0.01) net = tf.layers.dense(s, 500, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l1', trainable=trainable) net = tf.layers.dense(net, 200, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable) with tf.variable_scope('a'): actions = tf.layers.dense(net, self.a_dim, activation=tf.nn.tanh, kernel_initializer=init_w, bias_initializer=init_b, name='a', trainable=trainable) scaled_a = tf.multiply(actions, self.action_bound, name='scaled_a') # Scale output to -action_bound to action_bound return scaled_a def learn(self, s): # batch update self.sess.run(self.train_op, feed_dict={S: s}) if self.t_replace_counter % self.t_replace_iter == 0: self.sess.run([tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]) self.t_replace_counter += 1 def choose_action(self, s): s = s[np.newaxis, :] # single state return self.sess.run(self.a, feed_dict={S: s})[0] # single action def add_grad_to_graph(self, a_grads): with tf.variable_scope('policy_grads'): # ys = policy; # xs = policy's parameters; # self.a_grads = the gradients of the policy to get more Q # tf.gradients will calculate dys/dxs with a initial gradients for ys, so this is dq/da * da/dparams self.policy_grads_and_vars = tf.gradients(ys=self.a, xs=self.e_params, grad_ys=a_grads) with tf.variable_scope('A_train'): opt = tf.train.RMSPropOptimizer(-self.lr) # (- 1_tensorflow_new rate) for ascent policy self.train_op = opt.apply_gradients(zip(self.policy_grads_and_vars, self.e_params), global_step=GLOBAL_STEP) ############################### Critic #################################### class Critic(object): def __init__(self, sess, state_dim, action_dim, learning_rate, gamma, t_replace_iter, a, a_): self.sess = sess self.s_dim = state_dim self.a_dim = action_dim self.lr = learning_rate self.gamma = gamma self.t_replace_iter = t_replace_iter self.t_replace_counter = 0 with tf.variable_scope('Critic'): # Input (s, a), output q self.a = a self.q = self._build_net(S, self.a, 'eval_net', trainable=True) # Input (s_, a_), output q_ for q_target self.q_ = self._build_net(S_, a_, 'target_net', trainable=False) # target_q is based on a_ from Actor's target_net self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/eval_net') self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/target_net') with tf.variable_scope('target_q'): self.target_q = R + self.gamma * self.q_ with tf.variable_scope('abs_TD'): self.abs_td = tf.abs(self.target_q - self.q) self.ISWeights = tf.placeholder(tf.float32, [None, 1], name='IS_weights') with tf.variable_scope('TD_error'): self.loss = tf.reduce_mean(self.ISWeights * tf.squared_difference(self.target_q, self.q)) with tf.variable_scope('C_train'): self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss, global_step=GLOBAL_STEP) with tf.variable_scope('a_grad'): self.a_grads = tf.gradients(self.q, a)[0] # tensor of gradients of each sample (None, a_dim) def _build_net(self, s, a, scope, trainable): with tf.variable_scope(scope): init_w = tf.random_normal_initializer(0., 0.01) init_b = tf.constant_initializer(0.01) with tf.variable_scope('l1'): n_l1 = 700 # combine the action and states together in this way w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable) w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], initializer=init_w, trainable=trainable) b1 = tf.get_variable('b1', [1, n_l1], initializer=init_b, trainable=trainable) net = tf.nn.relu(tf.matmul(s, w1_s) + tf.matmul(a, w1_a) + b1) with tf.variable_scope('l2'): net = tf.layers.dense(net, 20, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable) with tf.variable_scope('q'): q = tf.layers.dense(net, 1, kernel_initializer=init_w, bias_initializer=init_b, trainable=trainable) # Q(s,a) return q def learn(self, s, a, r, s_, ISW): _, abs_td = self.sess.run([self.train_op, self.abs_td], feed_dict={S: s, self.a: a, R: r, S_: s_, self.ISWeights: ISW}) if self.t_replace_counter % self.t_replace_iter == 0: self.sess.run([tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]) self.t_replace_counter += 1 return abs_td class SumTree(object): """ This SumTree code is modified version and the original code is from: https://github.com/jaara/AI-blog/blob/master/SumTree.py Story the data with it priority in tree and data frameworks. """ data_pointer = 0 def __init__(self, capacity): self.capacity = capacity # for all priority values self.tree = np.zeros(2 * capacity - 1)+1e-5 # [--------------Parent nodes-------------][-------leaves to recode priority-------] # size: capacity - 1 size: capacity self.data = np.zeros(capacity, dtype=object) # for all transitions # [--------------data frame-------------] # size: capacity def add_new_priority(self, p, data): leaf_idx = self.data_pointer + self.capacity - 1 self.data[self.data_pointer] = data # update data_frame self.update(leaf_idx, p) # update tree_frame self.data_pointer += 1 if self.data_pointer >= self.capacity: # replace when exceed the capacity self.data_pointer = 0 def update(self, tree_idx, p): change = p - self.tree[tree_idx] self.tree[tree_idx] = p self._propagate_change(tree_idx, change) def _propagate_change(self, tree_idx, change): """change the sum of priority value in all parent nodes""" parent_idx = (tree_idx - 1) // 2 self.tree[parent_idx] += change if parent_idx != 0: self._propagate_change(parent_idx, change) def get_leaf(self, lower_bound): leaf_idx = self._retrieve(lower_bound) # search the max leaf priority based on the lower_bound data_idx = leaf_idx - self.capacity + 1 return [leaf_idx, self.tree[leaf_idx], self.data[data_idx]] def _retrieve(self, lower_bound, parent_idx=0): """ Tree structure and array storage: Tree index: 0 -> storing priority sum / \ 1 2 / \ / \ 3 4 5 6 -> storing priority for transitions Array type for storing: [0,1,2,3,4,5,6] """ left_child_idx = 2 * parent_idx + 1 right_child_idx = left_child_idx + 1 if left_child_idx >= len(self.tree): # end search when no more child return parent_idx if self.tree[left_child_idx] == self.tree[right_child_idx]: return self._retrieve(lower_bound, np.random.choice([left_child_idx, right_child_idx])) if lower_bound <= self.tree[left_child_idx]: # downward search, always search for a higher priority node return self._retrieve(lower_bound, left_child_idx) else: return self._retrieve(lower_bound - self.tree[left_child_idx], right_child_idx) @property def root_priority(self): return self.tree[0] # the root class Memory(object): # stored as ( s, a, r, s_ ) in SumTree """ This SumTree code is modified version and the original code is from: https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py """ epsilon = 0.001 # small amount to avoid zero priority alpha = 0.6 # [0~1] convert the importance of TD error to priority beta = 0.4 # importance-sampling, from initial value increasing to 1 beta_increment_per_sampling = 1e-5 # annealing the bias abs_err_upper = 1 # for stability refer to paper def __init__(self, capacity): self.tree = SumTree(capacity) def store(self, error, transition): p = self._get_priority(error) self.tree.add_new_priority(p, transition) def prio_sample(self, n): batch_idx, batch_memory, ISWeights = [], [], [] segment = self.tree.root_priority / n self.beta = np.min([1, self.beta + self.beta_increment_per_sampling]) # max = 1 min_prob = np.min(self.tree.tree[-self.tree.capacity:]) / self.tree.root_priority maxiwi = np.power(self.tree.capacity * min_prob, -self.beta) # for later normalizing ISWeights for i in range(n): a = segment * i b = segment * (i + 1) lower_bound = np.random.uniform(a, b) while True: idx, p, data = self.tree.get_leaf(lower_bound) if type(data) is int: i -= 1 lower_bound = np.random.uniform(segment * i, segment * (i+1)) else: break prob = p / self.tree.root_priority ISWeights.append(self.tree.capacity * prob) batch_idx.append(idx) batch_memory.append(data) ISWeights = np.vstack(ISWeights) ISWeights = np.power(ISWeights, -self.beta) / maxiwi # normalize return batch_idx, np.vstack(batch_memory), ISWeights def random_sample(self, n): idx = np.random.randint(0, self.tree.capacity, size=n, dtype=np.int) return np.vstack(self.tree.data[idx]) def update(self, idx, error): p = self._get_priority(error) self.tree.update(idx, p) def _get_priority(self, error): error += self.epsilon # avoid 0 clipped_error = np.clip(error, 0, self.abs_err_upper) return np.power(clipped_error, self.alpha) sess = tf.Session() # Create actor and critic. actor = Actor(sess, ACTION_DIM, ACTION_BOUND, LR_A, REPLACE_ITER_A) critic = Critic(sess, STATE_DIM, ACTION_DIM, LR_C, GAMMA, REPLACE_ITER_C, actor.a, actor.a_) actor.add_grad_to_graph(critic.a_grads) M = Memory(MEMORY_CAPACITY) saver = tf.train.Saver(max_to_keep=100) if LOAD_MODEL: all_ckpt = tf.train.get_checkpoint_state('./data', 'checkpoint').all_model_checkpoint_paths saver.restore(sess, all_ckpt[-1]) else: if os.path.isdir(DATA_PATH): shutil.rmtree(DATA_PATH) os.mkdir(DATA_PATH) sess.run(tf.global_variables_initializer()) if OUTPUT_GRAPH: tf.summary.FileWriter('logs', graph=sess.graph) var = 3 # control exploration var_min = 0.01 for i_episode in range(MAX_EPISODES): # s = (hull angle speed, angular velocity, horizontal speed, vertical speed, position of joints and joints angular speed, legs contact with ground, and 10 lidar rangefinder measurements.) s = env.reset() ep_r = 0 while True: if RENDER: env.render() a = actor.choose_action(s) a = np.clip(np.random.normal(a, var), -1, 1) # add randomness to action selection for exploration s_, r, done, _ = env.step(a) # r = total 300+ points up to the far end. If the robot falls, it gets -100. if r == -100: r = -2 ep_r += r transition = np.hstack((s, a, [r], s_)) max_p = np.max(M.tree.tree[-M.tree.capacity:]) M.store(max_p, transition) if GLOBAL_STEP.eval(sess) > MEMORY_CAPACITY/20: var = max([var*0.9999, var_min]) # decay the action randomness tree_idx, b_M, ISWeights = M.prio_sample(BATCH_SIZE) # for critic update b_s = b_M[:, :STATE_DIM] b_a = b_M[:, STATE_DIM: STATE_DIM + ACTION_DIM] b_r = b_M[:, -STATE_DIM - 1: -STATE_DIM] b_s_ = b_M[:, -STATE_DIM:] abs_td = critic.learn(b_s, b_a, b_r, b_s_, ISWeights) actor.learn(b_s) for i in range(len(tree_idx)): # update priority idx = tree_idx[i] M.update(idx, abs_td[i]) if GLOBAL_STEP.eval(sess) % SAVE_MODEL_ITER == 0: ckpt_path = os.path.join(DATA_PATH, 'DDPG.ckpt') save_path = saver.save(sess, ckpt_path, global_step=GLOBAL_STEP, write_meta_graph=False) print("\nSave Model %s\n" % save_path) if done: if "running_r" not in globals(): running_r = ep_r else: running_r = 0.95*running_r + 0.05*ep_r if running_r > DISPLAY_THRESHOLD: RENDER = True else: RENDER = False done = '| Achieve ' if env.unwrapped.hull.position[0] >= END_POINT else '| -----' print('Episode:', i_episode, done, '| Running_r: %i' % int(running_r), '| Epi_r: %.2f' % ep_r, '| Exploration: %.3f' % var, '| Pos: %.i' % int(env.unwrapped.hull.position[0]), '| LR_A: %.6f' % sess.run(LR_A), '| LR_C: %.6f' % sess.run(LR_C), ) break s = s_ sess.run(INCREASE_GS)
41.439589
191
0.611787
import tensorflow as tf import numpy as np import gym import os import shutil np.random.seed(1) tf.set_random_seed(1) MAX_EPISODES = 2000 LR_A = 0.0005 LR_C = 0.0005 GAMMA = 0.999 REPLACE_ITER_A = 1700 REPLACE_ITER_C = 1500 MEMORY_CAPACITY = 200000 BATCH_SIZE = 32 DISPLAY_THRESHOLD = 100 DATA_PATH = './data' LOAD_MODEL = False SAVE_MODEL_ITER = 100000 RENDER = False OUTPUT_GRAPH = False ENV_NAME = 'BipedalWalker-v2' GLOBAL_STEP = tf.Variable(0, trainable=False) INCREASE_GS = GLOBAL_STEP.assign(tf.add(GLOBAL_STEP, 1)) LR_A = tf.train.exponential_decay(LR_A, GLOBAL_STEP, 10000, .97, staircase=True) LR_C = tf.train.exponential_decay(LR_C, GLOBAL_STEP, 10000, .97, staircase=True) END_POINT = (200 - 10) * (14/30) env = gym.make(ENV_NAME) env.seed(1) STATE_DIM = env.observation_space.shape[0] ACTION_DIM = env.action_space.shape[0] ACTION_BOUND = env.action_space.high with tf.name_scope('S'): S = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s') with tf.name_scope('R'): R = tf.placeholder(tf.float32, [None, 1], name='r') with tf.name_scope('S_'): S_ = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s_') riable_scope('A_train'): opt = tf.train.RMSPropOptimizer(-self.lr) # (- 1_tensorflow_new rate) for ascent policy self.train_op = opt.apply_gradients(zip(self.policy_grads_and_vars, self.e_params), global_step=GLOBAL_STEP) ############################### Critic #################################### class Critic(object): def __init__(self, sess, state_dim, action_dim, learning_rate, gamma, t_replace_iter, a, a_): self.sess = sess self.s_dim = state_dim self.a_dim = action_dim self.lr = learning_rate self.gamma = gamma self.t_replace_iter = t_replace_iter self.t_replace_counter = 0 with tf.variable_scope('Critic'): # Input (s, a), output q self.a = a self.q = self._build_net(S, self.a, 'eval_net', trainable=True) # Input (s_, a_), output q_ for q_target self.q_ = self._build_net(S_, a_, 'target_net', trainable=False) # target_q is based on a_ from Actor's target_net self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/eval_net') self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/target_net') with tf.variable_scope('target_q'): self.target_q = R + self.gamma * self.q_ with tf.variable_scope('abs_TD'): self.abs_td = tf.abs(self.target_q - self.q) self.ISWeights = tf.placeholder(tf.float32, [None, 1], name='IS_weights') with tf.variable_scope('TD_error'): self.loss = tf.reduce_mean(self.ISWeights * tf.squared_difference(self.target_q, self.q)) with tf.variable_scope('C_train'): self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss, global_step=GLOBAL_STEP) with tf.variable_scope('a_grad'): self.a_grads = tf.gradients(self.q, a)[0] def _build_net(self, s, a, scope, trainable): with tf.variable_scope(scope): init_w = tf.random_normal_initializer(0., 0.01) init_b = tf.constant_initializer(0.01) with tf.variable_scope('l1'): n_l1 = 700 w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable) w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], initializer=init_w, trainable=trainable) b1 = tf.get_variable('b1', [1, n_l1], initializer=init_b, trainable=trainable) net = tf.nn.relu(tf.matmul(s, w1_s) + tf.matmul(a, w1_a) + b1) with tf.variable_scope('l2'): net = tf.layers.dense(net, 20, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable) with tf.variable_scope('q'): q = tf.layers.dense(net, 1, kernel_initializer=init_w, bias_initializer=init_b, trainable=trainable) return q def learn(self, s, a, r, s_, ISW): _, abs_td = self.sess.run([self.train_op, self.abs_td], feed_dict={S: s, self.a: a, R: r, S_: s_, self.ISWeights: ISW}) if self.t_replace_counter % self.t_replace_iter == 0: self.sess.run([tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]) self.t_replace_counter += 1 return abs_td class SumTree(object): data_pointer = 0 def __init__(self, capacity): self.capacity = capacity self.tree = np.zeros(2 * capacity - 1)+1e-5 self.data = np.zeros(capacity, dtype=object) def add_new_priority(self, p, data): leaf_idx = self.data_pointer + self.capacity - 1 self.data[self.data_pointer] = data self.update(leaf_idx, p) self.data_pointer += 1 if self.data_pointer >= self.capacity: self.data_pointer = 0 def update(self, tree_idx, p): change = p - self.tree[tree_idx] self.tree[tree_idx] = p self._propagate_change(tree_idx, change) def _propagate_change(self, tree_idx, change): parent_idx = (tree_idx - 1) // 2 self.tree[parent_idx] += change if parent_idx != 0: self._propagate_change(parent_idx, change) def get_leaf(self, lower_bound): leaf_idx = self._retrieve(lower_bound) data_idx = leaf_idx - self.capacity + 1 return [leaf_idx, self.tree[leaf_idx], self.data[data_idx]] def _retrieve(self, lower_bound, parent_idx=0): left_child_idx = 2 * parent_idx + 1 right_child_idx = left_child_idx + 1 if left_child_idx >= len(self.tree): return parent_idx if self.tree[left_child_idx] == self.tree[right_child_idx]: return self._retrieve(lower_bound, np.random.choice([left_child_idx, right_child_idx])) if lower_bound <= self.tree[left_child_idx]: return self._retrieve(lower_bound, left_child_idx) else: return self._retrieve(lower_bound - self.tree[left_child_idx], right_child_idx) @property def root_priority(self): return self.tree[0] class Memory(object): epsilon = 0.001 alpha = 0.6 beta = 0.4 beta_increment_per_sampling = 1e-5 abs_err_upper = 1 def __init__(self, capacity): self.tree = SumTree(capacity) def store(self, error, transition): p = self._get_priority(error) self.tree.add_new_priority(p, transition) def prio_sample(self, n): batch_idx, batch_memory, ISWeights = [], [], [] segment = self.tree.root_priority / n self.beta = np.min([1, self.beta + self.beta_increment_per_sampling]) min_prob = np.min(self.tree.tree[-self.tree.capacity:]) / self.tree.root_priority maxiwi = np.power(self.tree.capacity * min_prob, -self.beta) for i in range(n): a = segment * i b = segment * (i + 1) lower_bound = np.random.uniform(a, b) while True: idx, p, data = self.tree.get_leaf(lower_bound) if type(data) is int: i -= 1 lower_bound = np.random.uniform(segment * i, segment * (i+1)) else: break prob = p / self.tree.root_priority ISWeights.append(self.tree.capacity * prob) batch_idx.append(idx) batch_memory.append(data) ISWeights = np.vstack(ISWeights) ISWeights = np.power(ISWeights, -self.beta) / maxiwi return batch_idx, np.vstack(batch_memory), ISWeights def random_sample(self, n): idx = np.random.randint(0, self.tree.capacity, size=n, dtype=np.int) return np.vstack(self.tree.data[idx]) def update(self, idx, error): p = self._get_priority(error) self.tree.update(idx, p) def _get_priority(self, error): error += self.epsilon clipped_error = np.clip(error, 0, self.abs_err_upper) return np.power(clipped_error, self.alpha) sess = tf.Session() actor = Actor(sess, ACTION_DIM, ACTION_BOUND, LR_A, REPLACE_ITER_A) critic = Critic(sess, STATE_DIM, ACTION_DIM, LR_C, GAMMA, REPLACE_ITER_C, actor.a, actor.a_) actor.add_grad_to_graph(critic.a_grads) M = Memory(MEMORY_CAPACITY) saver = tf.train.Saver(max_to_keep=100) if LOAD_MODEL: all_ckpt = tf.train.get_checkpoint_state('./data', 'checkpoint').all_model_checkpoint_paths saver.restore(sess, all_ckpt[-1]) else: if os.path.isdir(DATA_PATH): shutil.rmtree(DATA_PATH) os.mkdir(DATA_PATH) sess.run(tf.global_variables_initializer()) if OUTPUT_GRAPH: tf.summary.FileWriter('logs', graph=sess.graph) var = 3 var_min = 0.01 for i_episode in range(MAX_EPISODES): s = env.reset() ep_r = 0 while True: if RENDER: env.render() a = actor.choose_action(s) a = np.clip(np.random.normal(a, var), -1, 1) s_, r, done, _ = env.step(a) if r == -100: r = -2 ep_r += r transition = np.hstack((s, a, [r], s_)) max_p = np.max(M.tree.tree[-M.tree.capacity:]) M.store(max_p, transition) if GLOBAL_STEP.eval(sess) > MEMORY_CAPACITY/20: var = max([var*0.9999, var_min]) tree_idx, b_M, ISWeights = M.prio_sample(BATCH_SIZE) b_s = b_M[:, :STATE_DIM] b_a = b_M[:, STATE_DIM: STATE_DIM + ACTION_DIM] b_r = b_M[:, -STATE_DIM - 1: -STATE_DIM] b_s_ = b_M[:, -STATE_DIM:] abs_td = critic.learn(b_s, b_a, b_r, b_s_, ISWeights) actor.learn(b_s) for i in range(len(tree_idx)): idx = tree_idx[i] M.update(idx, abs_td[i]) if GLOBAL_STEP.eval(sess) % SAVE_MODEL_ITER == 0: ckpt_path = os.path.join(DATA_PATH, 'DDPG.ckpt') save_path = saver.save(sess, ckpt_path, global_step=GLOBAL_STEP, write_meta_graph=False) print("\nSave Model %s\n" % save_path) if done: if "running_r" not in globals(): running_r = ep_r else: running_r = 0.95*running_r + 0.05*ep_r if running_r > DISPLAY_THRESHOLD: RENDER = True else: RENDER = False done = '| Achieve ' if env.unwrapped.hull.position[0] >= END_POINT else '| -----' print('Episode:', i_episode, done, '| Running_r: %i' % int(running_r), '| Epi_r: %.2f' % ep_r, '| Exploration: %.3f' % var, '| Pos: %.i' % int(env.unwrapped.hull.position[0]), '| LR_A: %.6f' % sess.run(LR_A), '| LR_C: %.6f' % sess.run(LR_C), ) break s = s_ sess.run(INCREASE_GS)
true
true
1c3748bdc31f4ffd0824fa09ca24a8aa14103931
253
py
Python
src/sentry/mediators/token_exchange/__init__.py
pierredup/sentry
0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80
[ "BSD-3-Clause" ]
4
2019-05-27T13:55:07.000Z
2021-03-30T07:05:09.000Z
src/sentry/mediators/token_exchange/__init__.py
pierredup/sentry
0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80
[ "BSD-3-Clause" ]
196
2019-06-10T08:34:10.000Z
2022-02-22T01:26:13.000Z
src/sentry/mediators/token_exchange/__init__.py
pierredup/sentry
0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80
[ "BSD-3-Clause" ]
1
2020-08-10T07:55:40.000Z
2020-08-10T07:55:40.000Z
from __future__ import absolute_import from .grant_exchanger import GrantExchanger # NOQA from .refresher import Refresher # NOQA from .validator import Validator # NOQA from .util import AUTHORIZATION, REFRESH, GrantTypes, token_expiration # NOQA
36.142857
78
0.814229
from __future__ import absolute_import from .grant_exchanger import GrantExchanger from .refresher import Refresher from .validator import Validator from .util import AUTHORIZATION, REFRESH, GrantTypes, token_expiration
true
true
1c3748edac428870193dde4d179105c3b3eea934
5,905
py
Python
deepspeed/utils/distributed.py
ConnollyLeon/DeepSpeed
2d84d1c185ef0345eaf43a7240d61b33eda43497
[ "MIT" ]
6,728
2020-02-07T23:53:18.000Z
2022-03-31T20:02:53.000Z
deepspeed/utils/distributed.py
ConnollyLeon/DeepSpeed
2d84d1c185ef0345eaf43a7240d61b33eda43497
[ "MIT" ]
1,104
2020-02-08T00:26:15.000Z
2022-03-31T22:33:56.000Z
deepspeed/utils/distributed.py
ConnollyLeon/DeepSpeed
2d84d1c185ef0345eaf43a7240d61b33eda43497
[ "MIT" ]
801
2020-02-10T15:33:42.000Z
2022-03-29T16:32:33.000Z
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import os import torch from datetime import timedelta from .logging import logger from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout def init_distributed(dist_backend="nccl", auto_mpi_discovery=True, distributed_port=TORCH_DISTRIBUTED_DEFAULT_PORT, verbose=True, timeout=default_pg_timeout, init_method=None): """Initialize torch.distributed backend, potentially performing MPI discovery if needed Arguments: dist_backend: Optional (str). torch distributed backend, e.g., nccl, mpi, gloo auto_mpi_discovery Optional (bool). if distributed environment variables are not set, attempt to discover them from MPI distributed_port: Optional (int). torch distributed backend port verbose: Optional (bool). verbose logging timeout: Optional (timedelta). Timeout for operations executed against the process group. Default value equals 30 minutes. init_method: Optional (string). Torch distributed, URL specifying how to initialize the process group. Default is “env://” if no init_method or store is specified. """ required_env = ["RANK", "WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT", "LOCAL_RANK"] if auto_mpi_discovery and not all(map(lambda v: v in os.environ, required_env)): if verbose: logger.info( "Not using the DeepSpeed or torch.distributed launchers, attempting to detect MPI environment..." ) if in_aml() and not in_dlts(): patch_aml_env_for_torch_nccl_backend(verbose=verbose) else: mpi_discovery(distributed_port=distributed_port, verbose=verbose) if not torch.distributed.is_initialized(): if verbose: logger.info( "Initializing torch distributed with backend: {}".format(dist_backend)) assert isinstance(timeout, timedelta) torch.distributed.init_process_group(backend=dist_backend, timeout=timeout, init_method=init_method) def mpi_discovery(distributed_port=TORCH_DISTRIBUTED_DEFAULT_PORT, verbose=True): """ Discovery MPI environment via mpi4py and map to relevant torch.distributed state """ from mpi4py import MPI import subprocess comm = MPI.COMM_WORLD rank = comm.Get_rank() world_size = comm.Get_size() master_addr = None if rank == 0: hostname_cmd = ["hostname -I"] result = subprocess.check_output(hostname_cmd, shell=True) master_addr = result.decode('utf-8').split()[0] master_addr = comm.bcast(master_addr, root=0) # Determine local rank by assuming hostnames are unique proc_name = MPI.Get_processor_name() all_procs = comm.allgather(proc_name) local_rank = sum([i == proc_name for i in all_procs[:rank]]) os.environ['RANK'] = str(rank) os.environ['WORLD_SIZE'] = str(world_size) os.environ['LOCAL_RANK'] = str(local_rank) os.environ['MASTER_ADDR'] = master_addr os.environ['MASTER_PORT'] = str(distributed_port) if verbose: logger.info( "Discovered MPI settings of world_rank={}, local_rank={}, world_size={}, master_addr={}, master_port={}" .format(os.environ['RANK'], os.environ['LOCAL_RANK'], os.environ['WORLD_SIZE'], os.environ['MASTER_ADDR'], os.environ['MASTER_PORT'])) if torch.distributed.is_initialized(): assert torch.distributed.get_rank() == rank, "MPI rank {} does not match torch rank {}".format( rank, torch.distributed.get_rank()) assert torch.distributed.get_world_size() == world_size, "MPI world size {} does not match torch world size {}".format( world_size, torch.distributed.get_world_size()) def in_aml(): # Are we running inside an Azure Machine Learning (AML) environment? return 'AZUREML_EXPERIMENT_ID' in os.environ def in_dlts(): # Are we running on a DLTS cluster? return 'DLTS_JOB_ID' in os.environ def patch_aml_env_for_torch_nccl_backend(master_port=6105, verbose=True): """Helper routine to get and set environment variables. This is adapted from Azure ML's documentation available from: https://azure.github.io/azureml-web/docs/cheatsheet/distributed-training/#environment-variables-from-openmpi """ os.environ["RANK"] = os.environ["OMPI_COMM_WORLD_RANK"] os.environ["WORLD_SIZE"] = os.environ["OMPI_COMM_WORLD_SIZE"] single_node = int(os.environ["OMPI_COMM_WORLD_LOCAL_SIZE"]) == int( os.environ["WORLD_SIZE"]) if not single_node: master_node_params = os.environ["AZ_BATCH_MASTER_NODE"].split(":") os.environ["MASTER_ADDR"] = master_node_params[0] # Do not overwrite master port with that defined in AZ_BATCH_MASTER_NODE if "MASTER_PORT" not in os.environ: os.environ["MASTER_PORT"] = str(master_port) else: os.environ["MASTER_ADDR"] = os.environ["AZ_BATCHAI_MPI_MASTER_NODE"] os.environ["MASTER_PORT"] = "54965" if verbose: logger.info("NCCL_SOCKET_IFNAME original value = {}".format( os.environ["NCCL_SOCKET_IFNAME"])) os.environ["NCCL_SOCKET_IFNAME"] = "^docker0,lo" os.environ['LOCAL_RANK'] = os.environ["OMPI_COMM_WORLD_LOCAL_RANK"] if verbose: logger.info( "Discovered AzureML settings of world_rank={}, local_rank={}, world_size={}, master_addr={}, master_port={}" .format(os.environ['RANK'], os.environ['LOCAL_RANK'], os.environ['WORLD_SIZE'], os.environ['MASTER_ADDR'], os.environ['MASTER_PORT']))
41.293706
171
0.656393
import os import torch from datetime import timedelta from .logging import logger from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout def init_distributed(dist_backend="nccl", auto_mpi_discovery=True, distributed_port=TORCH_DISTRIBUTED_DEFAULT_PORT, verbose=True, timeout=default_pg_timeout, init_method=None): required_env = ["RANK", "WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT", "LOCAL_RANK"] if auto_mpi_discovery and not all(map(lambda v: v in os.environ, required_env)): if verbose: logger.info( "Not using the DeepSpeed or torch.distributed launchers, attempting to detect MPI environment..." ) if in_aml() and not in_dlts(): patch_aml_env_for_torch_nccl_backend(verbose=verbose) else: mpi_discovery(distributed_port=distributed_port, verbose=verbose) if not torch.distributed.is_initialized(): if verbose: logger.info( "Initializing torch distributed with backend: {}".format(dist_backend)) assert isinstance(timeout, timedelta) torch.distributed.init_process_group(backend=dist_backend, timeout=timeout, init_method=init_method) def mpi_discovery(distributed_port=TORCH_DISTRIBUTED_DEFAULT_PORT, verbose=True): from mpi4py import MPI import subprocess comm = MPI.COMM_WORLD rank = comm.Get_rank() world_size = comm.Get_size() master_addr = None if rank == 0: hostname_cmd = ["hostname -I"] result = subprocess.check_output(hostname_cmd, shell=True) master_addr = result.decode('utf-8').split()[0] master_addr = comm.bcast(master_addr, root=0) proc_name = MPI.Get_processor_name() all_procs = comm.allgather(proc_name) local_rank = sum([i == proc_name for i in all_procs[:rank]]) os.environ['RANK'] = str(rank) os.environ['WORLD_SIZE'] = str(world_size) os.environ['LOCAL_RANK'] = str(local_rank) os.environ['MASTER_ADDR'] = master_addr os.environ['MASTER_PORT'] = str(distributed_port) if verbose: logger.info( "Discovered MPI settings of world_rank={}, local_rank={}, world_size={}, master_addr={}, master_port={}" .format(os.environ['RANK'], os.environ['LOCAL_RANK'], os.environ['WORLD_SIZE'], os.environ['MASTER_ADDR'], os.environ['MASTER_PORT'])) if torch.distributed.is_initialized(): assert torch.distributed.get_rank() == rank, "MPI rank {} does not match torch rank {}".format( rank, torch.distributed.get_rank()) assert torch.distributed.get_world_size() == world_size, "MPI world size {} does not match torch world size {}".format( world_size, torch.distributed.get_world_size()) def in_aml(): return 'AZUREML_EXPERIMENT_ID' in os.environ def in_dlts(): return 'DLTS_JOB_ID' in os.environ def patch_aml_env_for_torch_nccl_backend(master_port=6105, verbose=True): os.environ["RANK"] = os.environ["OMPI_COMM_WORLD_RANK"] os.environ["WORLD_SIZE"] = os.environ["OMPI_COMM_WORLD_SIZE"] single_node = int(os.environ["OMPI_COMM_WORLD_LOCAL_SIZE"]) == int( os.environ["WORLD_SIZE"]) if not single_node: master_node_params = os.environ["AZ_BATCH_MASTER_NODE"].split(":") os.environ["MASTER_ADDR"] = master_node_params[0] if "MASTER_PORT" not in os.environ: os.environ["MASTER_PORT"] = str(master_port) else: os.environ["MASTER_ADDR"] = os.environ["AZ_BATCHAI_MPI_MASTER_NODE"] os.environ["MASTER_PORT"] = "54965" if verbose: logger.info("NCCL_SOCKET_IFNAME original value = {}".format( os.environ["NCCL_SOCKET_IFNAME"])) os.environ["NCCL_SOCKET_IFNAME"] = "^docker0,lo" os.environ['LOCAL_RANK'] = os.environ["OMPI_COMM_WORLD_LOCAL_RANK"] if verbose: logger.info( "Discovered AzureML settings of world_rank={}, local_rank={}, world_size={}, master_addr={}, master_port={}" .format(os.environ['RANK'], os.environ['LOCAL_RANK'], os.environ['WORLD_SIZE'], os.environ['MASTER_ADDR'], os.environ['MASTER_PORT']))
true
true
1c374964dab8d3056ee1d1c3367fda275b2446d2
11,714
py
Python
bitcoinscript/shell.py
fungibit/bitcoinscript
ced6fb37dfa40eac7341826c758842e0ed7e7475
[ "MIT" ]
1
2017-10-25T17:11:44.000Z
2017-10-25T17:11:44.000Z
bitcoinscript/shell.py
fungibit/bitcoinscript
ced6fb37dfa40eac7341826c758842e0ed7e7475
[ "MIT" ]
3
2017-03-10T05:27:29.000Z
2017-04-07T16:06:28.000Z
bitcoinscript/shell.py
fungibit/bitcoinscript
ced6fb37dfa40eac7341826c758842e0ed7e7475
[ "MIT" ]
null
null
null
""" Definition (and activation) of BitcoinScript ipython-magics, for interactively composing bitcoin-scripts in a ipython session. BitcoinScript magics can be activated by invoking ipython like:: ipython -i bitcoinscript.shell or by importing this module in the ipython session:: import bitcoinscript.shell """ from IPython.core import magic as _MAGIC from IPython.core.magic import line_magic as _line_magic from bitcoin.core import _bignum from bitcoin.core import scripteval as _scripteval from bitcoinscript import opcode as _OPCODE import bitcoinscript as _BS from bitcoinscript.format import parse_formatted_script as _parse_formatted_script from bitcoinscript.verify import verify_script as _verify_script from bitcoinscript.debugger import run_in_debugger as _run_in_debugger from bitcoinscript.samples import get_sample_exec_args as _get_sample_exec_args ############################################################################### _SCRIPT_VERIFY_FLAG_TO_NAME = { v:k for k,v in _scripteval.SCRIPT_VERIFY_FLAGS_BY_NAME.items() } ############################################################################### class BitcoinScriptMagics(_MAGIC.Magics): def __init__(self, *a, **kw): super().__init__(*a, **kw) self._reset() self._echoing = True def _reset(self): self._scripts = { 'out': b'', 'in': b'' } self._active_script = 'out' self._ctx = { 'rawtx': None, 'input_idx': None } self._flags = () ############################################################################### # properties and basic operations @property def outscript_blob(self): return self._scripts['out'] @property def inscript_blob(self): return self._scripts['in'] @property def active_blob(self): return self._scripts[self._active_script] @property def outscript(self): return _BS.outscript_from_raw(self.outscript_blob) @property def inscript(self): return _BS.inscript_from_raw(self.inscript_blob, self.outscript) @property def active_script(self): if self._active_script == 'in': return self.inscript else: return self.outscript ############################################################################### # MAGICS -- display / echo @_line_magic def Sechoon(self, line): """ Turn script-echoing ON """ self._echoing = True print('ECHO is now ON') @_line_magic def Sechooff(self, line): """ Turn script-echoing OFF """ self._echoing = False print('ECHO is now OFF') @_line_magic def Sshow(self, line): """ Display current scripts, along with flags and context """ self.print_scripts(force = True) def print_scripts(self, force = False): if not self._echoing and not force: return self._print_script(self.inscript, role = 'in') self._print_script(self.outscript, role = 'out') if self._flags: print(' Flags: %s' % ' '.join(_SCRIPT_VERIFY_FLAG_TO_NAME[f] for f in self._flags)) for k, v in sorted(self._ctx.items()): if v is None: continue if isinstance(v, bytes): v = v.hex() print(' Context: %s = %s' % (k, v)) def _print_script(self, script, role): if script is None: return active_marker = '*' if role == self._active_script else ' ' role_str = '%-9s ' % (role.capitalize() + 'Script') script_str = str(script) print('%s%s: [%s]' % (active_marker, role_str, script_str)) ############################################################################### # MAGICS -- modify script, control @_line_magic def Sinscript(self, line): """ Set InScript as the active script """ self._active_script = 'in' print('INSCRIPT is now active') @_line_magic def Soutscript(self, line): """ Set OutScript as the active script """ self._active_script = 'out' print('OUTSCRIPT is now active') @_line_magic def Sclear(self, line): """ Clear the active script """ self._scripts[self._active_script] = b'' self.print_scripts() @_line_magic def Sreset(self, line): """ Clear all script-related data. Affects scripts, flags, and context. """ self._reset() self.print_scripts() @_line_magic def Ssetscript(self, line): """ Set script from human readable string (overwriting active script) """ blob = _parse_formatted_script(line) self._scripts[self._active_script] = blob self.print_scripts() @_line_magic def Sloadsample(self, line): """ Set scripts from a sample """ script_types = line.split() (inscript, outscript), ctx = _get_sample_exec_args(*script_types) self._scripts['in'] = inscript.raw self._scripts['out'] = outscript.raw self._ctx['rawtx'] = ctx['rawtx'] self._ctx['input_idx'] = ctx['input_idx'] self._flags = ctx['flags'] self.print_scripts() @_line_magic def Spushdata(self, line): """ Push data using an appropriate OP_PUSHDATA op (OP_PUSHDATA/1/2/4) """ data = self._arg_to_data(line) if data is None: return if isinstance(data, int): # int -> bytes data = _bignum.bn2vch(data) if not isinstance(data, bytes): raise TypeError('Cannot push data of type %s' % type(data).__name__) self._append(_OPCODE.encode_op_pushdata(data)) self.print_scripts() def _append(self, b): self._scripts[self._active_script] += b def _append_opcode(self, opcode): self._append(opcode.to_bytes(1, byteorder = 'little')) def _arg_to_data(self, line): line = line.strip() if not line: return None if line.startswith('0x'): # interpret as hex data v = bytes.fromhex(line[2:]) else: v = eval(line) return v ############################################################################### # MAGICS -- flags and context @_line_magic def Sflagset(self, line): """ Enable a script-execution flag. E.g., SCRIPT_VERIFY_CLEANSTACK """ flagname, flag = self._get_flag(line) if flag is None: return if flag not in self._flags: self._flags += (flag,) print('Flag enabled: %s' % flagname) self.print_scripts() @_line_magic def Sflagunset(self, line): """ Disable a script-execution flag. E.g., SCRIPT_VERIFY_CLEANSTACK """ flagname, flag = self._get_flag(line) if flag is None: return self._flags = tuple([ f for f in self._flags if f != flag ]) print('Flag disabled: %s' % flagname) self.print_scripts() def _get_flag(self, line): flagname = line.strip() if not flagname: return None, None if not flagname.startswith('SCRIPT_VERIFY_'): flagname = 'SCRIPT_VERIFY_' + flagname flag = getattr(_scripteval, flagname, None) if flag is None: print('No such flag: %s' % flagname) return flagname, flag @_line_magic def Stxset(self, line): """ Set the raw Tx to use for signature-related OPs """ data = self._arg_to_data(line) if not isinstance(data, bytes): raise TypeError('Cannot set tx of type %s' % type(data).__name__) self._ctx['rawtx'] = data self.print_scripts() @_line_magic def Stxunset(self, line): """ Unset the raw Tx """ self._ctx.pop('rawtx', None) self.print_scripts() @_line_magic def Siidxset(self, line): """ Set input_idx to use for signature-related OPs """ data = self._arg_to_data(line) if not isinstance(data, int): raise TypeError('Cannot set input_idx of type %s' % type(data).__name__) self._ctx['input_idx'] = data self.print_scripts() @_line_magic def Siidxunset(self, line): """ Unset input_idx """ self._ctx.pop('input_idx', None) self.print_scripts() ############################################################################### # MAGICS -- verify and debug @_line_magic def Sdebug(self, line): """ Start a debugger session with current scripts """ a, kw = self._get_exec_args() _run_in_debugger(*a, **kw) @_line_magic def Sverify(self, line): """ Run the scripts, and print the result (sucess or error) """ a, kw = self._get_exec_args() try: _verify_script(*a, **kw) except Exception as e: print('*ERROR* [%s] %s' % ( type(e).__name__, e )) else: print('SUCCESS') def _get_exec_args(self): flags = self._flags if self.outscript.type == _BS.ScriptType.P2SH and _scripteval.SCRIPT_VERIFY_P2SH not in flags: flags += (_scripteval.SCRIPT_VERIFY_P2SH,) return (self.inscript, self.outscript), dict(flags = flags, **self._ctx) ############################################################################### # MAGICS -- other @_line_magic def Sp2shify(self, line): """ Transform scripts to a P2SH form """ p2sh_inscript = _BS.InScriptP2SH.from_redeem_scripts(self.outscript, self.inscript) p2sh_outscript = _BS.OutScriptP2SH.from_script(self.outscript) self._scripts['in'] = p2sh_inscript.raw self._scripts['out'] = p2sh_outscript.raw self.print_scripts() @_line_magic def Shelp(self, line): """ List all BitcoinScript shell magics """ all_magics = self.magics['line'] op_magics = [ m for m in all_magics if m.startswith('OP_') ] other_magics = [ m for m in all_magics if m not in op_magics ] print() print('Sxxx MAGICS:') for magicname in sorted(other_magics): magicfunc = all_magics[magicname] print(' %-24s %s' % (magicname, magicfunc.__doc__)) print() print('OP_xxx MAGICS:') for magicname in sorted(op_magics): magicfunc = all_magics[magicname] print(' %-24s %s' % (magicname, magicfunc.__doc__)) print() ############################################################################### # Automatically add all OP_xxx consts as magics: def _op_push_func(opname): def op_push(self, line): self._append_opcode(getattr(_OPCODE, opname)) self.print_scripts() op_push.__name__ = opname op_push.__doc__ = "Push %s to active script" % opname return op_push for _opname in dir(_OPCODE): if _opname.startswith('OP_'): setattr(BitcoinScriptMagics, _opname, _line_magic(_op_push_func(_opname))) ############################################################################### # Register magics with IPython: if 0: get_ipython = None # Avoid pyflakes warnings try: get_ipython except NameError: # Not running in an ipython session. Do nothing. pass else: BitcoinScriptMagics = _MAGIC.magics_class(BitcoinScriptMagics) ip = get_ipython() ip.register_magics(BitcoinScriptMagics) print('*** BitcoinScript shell magics are Enabled. Enter `%Shelp` for more details. ***') ###############################################################################
33.278409
102
0.566331
from IPython.core import magic as _MAGIC from IPython.core.magic import line_magic as _line_magic from bitcoin.core import _bignum from bitcoin.core import scripteval as _scripteval from bitcoinscript import opcode as _OPCODE import bitcoinscript as _BS from bitcoinscript.format import parse_formatted_script as _parse_formatted_script from bitcoinscript.verify import verify_script as _verify_script from bitcoinscript.debugger import run_in_debugger as _run_in_debugger from bitcoinscript.samples import get_sample_exec_args as _get_sample_exec_args
true
true
1c374b8bb42dcb373790b92d993e9916fdaac311
11,805
py
Python
CodeAnalysis/SourceMeter_Interface/SourceMeter-8.2.0-x64-linux/Python/Demo/ceilometer/ceilometer/tests/alarm/test_notifier.py
ishtjot/susereumutep
56e20c1777e0c938ac42bd8056f84af9e0b76e46
[ "Apache-2.0" ]
2
2018-11-07T20:52:53.000Z
2019-10-20T15:57:01.000Z
CodeAnalysis/SourceMeter_Interface/SourceMeter-8.2.0-x64-linux/Python/Demo/ceilometer/ceilometer/tests/alarm/test_notifier.py
ishtjot/susereumutep
56e20c1777e0c938ac42bd8056f84af9e0b76e46
[ "Apache-2.0" ]
3
2021-12-14T20:57:54.000Z
2022-01-21T23:50:36.000Z
CodeAnalysis/SourceMeter_Interface/SourceMeter-8.2.0-x64-linux/Python/Demo/ceilometer/ceilometer/tests/alarm/test_notifier.py
ishtjot/susereumutep
56e20c1777e0c938ac42bd8056f84af9e0b76e46
[ "Apache-2.0" ]
2
2018-11-16T04:20:06.000Z
2019-03-28T23:49:13.000Z
# # Copyright 2013-2014 eNovance # # Author: Julien Danjou <julien@danjou.info> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import anyjson import mock from oslo.config import fixture as fixture_config from oslotest import mockpatch import requests import six.moves.urllib.parse as urlparse from ceilometer.alarm import service from ceilometer.openstack.common import context from ceilometer.tests import base as tests_base DATA_JSON = anyjson.loads( '{"current": "ALARM", "alarm_id": "foobar",' ' "reason": "what ?", "reason_data": {"test": "test"},' ' "previous": "OK"}' ) NOTIFICATION = dict(alarm_id='foobar', condition=dict(threshold=42), reason='what ?', reason_data={'test': 'test'}, previous='OK', current='ALARM') class TestAlarmNotifier(tests_base.BaseTestCase): def setUp(self): super(TestAlarmNotifier, self).setUp() self.CONF = self.useFixture(fixture_config.Config()).conf self.setup_messaging(self.CONF) self.service = service.AlarmNotifierService() self.useFixture(mockpatch.Patch( 'ceilometer.openstack.common.context.generate_request_id', self._fake_generate_request_id)) @mock.patch('ceilometer.pipeline.setup_pipeline', mock.MagicMock()) def test_init_host(self): # If we try to create a real RPC connection, init_host() never # returns. Mock it out so we can establish the service # configuration. with mock.patch.object(self.service.rpc_server, 'start'): self.service.start() def test_notify_alarm(self): data = { 'actions': ['test://'], 'alarm_id': 'foobar', 'previous': 'OK', 'current': 'ALARM', 'reason': 'Everything is on fire', 'reason_data': {'fire': 'everywhere'} } self.service.notify_alarm(context.get_admin_context(), data) notifications = self.service.notifiers['test'].obj.notifications self.assertEqual(1, len(notifications)) self.assertEqual((urlparse.urlsplit(data['actions'][0]), data['alarm_id'], data['previous'], data['current'], data['reason'], data['reason_data']), notifications[0]) def test_notify_alarm_no_action(self): self.service.notify_alarm(context.get_admin_context(), {}) def test_notify_alarm_log_action(self): self.service.notify_alarm(context.get_admin_context(), { 'actions': ['log://'], 'alarm_id': 'foobar', 'condition': {'threshold': 42}}) @staticmethod def _fake_spawn_n(func, *args, **kwargs): func(*args, **kwargs) @staticmethod def _notification(action): notification = {} notification.update(NOTIFICATION) notification['actions'] = [action] return notification HTTP_HEADERS = {'x-openstack-request-id': 'fake_request_id', 'content-type': 'application/json'} def _fake_generate_request_id(self): return self.HTTP_HEADERS['x-openstack-request-id'] def test_notify_alarm_rest_action_ok(self): action = 'http://host/action' with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_client_cert(self): action = 'https://host/action' certificate = "/etc/ssl/cert/whatever.pem" self.CONF.set_override("rest_notifier_certificate_file", certificate, group='alarm') with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, cert=certificate, verify=True) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_client_cert_and_key(self): action = 'https://host/action' certificate = "/etc/ssl/cert/whatever.pem" key = "/etc/ssl/cert/whatever.key" self.CONF.set_override("rest_notifier_certificate_file", certificate, group='alarm') self.CONF.set_override("rest_notifier_certificate_key", key, group='alarm') with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, cert=(certificate, key), verify=True) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_verify_disable_by_cfg(self): action = 'https://host/action' self.CONF.set_override("rest_notifier_ssl_verify", False, group='alarm') with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, verify=False) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_verify_disable(self): action = 'https://host/action?ceilometer-alarm-ssl-verify=0' with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, verify=False) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_verify_enable_by_user(self): action = 'https://host/action?ceilometer-alarm-ssl-verify=1' self.CONF.set_override("rest_notifier_ssl_verify", False, group='alarm') with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, verify=True) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) @staticmethod def _fake_urlsplit(*args, **kwargs): raise Exception("Evil urlsplit!") def test_notify_alarm_invalid_url(self): with mock.patch('oslo.utils.netutils.urlsplit', self._fake_urlsplit): LOG = mock.MagicMock() with mock.patch('ceilometer.alarm.service.LOG', LOG): self.service.notify_alarm( context.get_admin_context(), { 'actions': ['no-such-action-i-am-sure'], 'alarm_id': 'foobar', 'condition': {'threshold': 42}, }) self.assertTrue(LOG.error.called) def test_notify_alarm_invalid_action(self): LOG = mock.MagicMock() with mock.patch('ceilometer.alarm.service.LOG', LOG): self.service.notify_alarm( context.get_admin_context(), { 'actions': ['no-such-action-i-am-sure://'], 'alarm_id': 'foobar', 'condition': {'threshold': 42}, }) self.assertTrue(LOG.error.called) def test_notify_alarm_trust_action(self): action = 'trust+http://trust-1234@host/action' url = 'http://host/action' client = mock.MagicMock() client.auth_token = 'token_1234' headers = {'X-Auth-Token': 'token_1234'} headers.update(self.HTTP_HEADERS) self.useFixture(mockpatch.Patch('keystoneclient.v3.client.Client', lambda **kwargs: client)) with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) headers = {'X-Auth-Token': 'token_1234'} headers.update(self.HTTP_HEADERS) poster.assert_called_with( url, data=mock.ANY, headers=mock.ANY) args, kwargs = poster.call_args self.assertEqual(headers, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data']))
45.057252
80
0.559085
import anyjson import mock from oslo.config import fixture as fixture_config from oslotest import mockpatch import requests import six.moves.urllib.parse as urlparse from ceilometer.alarm import service from ceilometer.openstack.common import context from ceilometer.tests import base as tests_base DATA_JSON = anyjson.loads( '{"current": "ALARM", "alarm_id": "foobar",' ' "reason": "what ?", "reason_data": {"test": "test"},' ' "previous": "OK"}' ) NOTIFICATION = dict(alarm_id='foobar', condition=dict(threshold=42), reason='what ?', reason_data={'test': 'test'}, previous='OK', current='ALARM') class TestAlarmNotifier(tests_base.BaseTestCase): def setUp(self): super(TestAlarmNotifier, self).setUp() self.CONF = self.useFixture(fixture_config.Config()).conf self.setup_messaging(self.CONF) self.service = service.AlarmNotifierService() self.useFixture(mockpatch.Patch( 'ceilometer.openstack.common.context.generate_request_id', self._fake_generate_request_id)) @mock.patch('ceilometer.pipeline.setup_pipeline', mock.MagicMock()) def test_init_host(self): with mock.patch.object(self.service.rpc_server, 'start'): self.service.start() def test_notify_alarm(self): data = { 'actions': ['test://'], 'alarm_id': 'foobar', 'previous': 'OK', 'current': 'ALARM', 'reason': 'Everything is on fire', 'reason_data': {'fire': 'everywhere'} } self.service.notify_alarm(context.get_admin_context(), data) notifications = self.service.notifiers['test'].obj.notifications self.assertEqual(1, len(notifications)) self.assertEqual((urlparse.urlsplit(data['actions'][0]), data['alarm_id'], data['previous'], data['current'], data['reason'], data['reason_data']), notifications[0]) def test_notify_alarm_no_action(self): self.service.notify_alarm(context.get_admin_context(), {}) def test_notify_alarm_log_action(self): self.service.notify_alarm(context.get_admin_context(), { 'actions': ['log://'], 'alarm_id': 'foobar', 'condition': {'threshold': 42}}) @staticmethod def _fake_spawn_n(func, *args, **kwargs): func(*args, **kwargs) @staticmethod def _notification(action): notification = {} notification.update(NOTIFICATION) notification['actions'] = [action] return notification HTTP_HEADERS = {'x-openstack-request-id': 'fake_request_id', 'content-type': 'application/json'} def _fake_generate_request_id(self): return self.HTTP_HEADERS['x-openstack-request-id'] def test_notify_alarm_rest_action_ok(self): action = 'http://host/action' with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_client_cert(self): action = 'https://host/action' certificate = "/etc/ssl/cert/whatever.pem" self.CONF.set_override("rest_notifier_certificate_file", certificate, group='alarm') with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, cert=certificate, verify=True) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_client_cert_and_key(self): action = 'https://host/action' certificate = "/etc/ssl/cert/whatever.pem" key = "/etc/ssl/cert/whatever.key" self.CONF.set_override("rest_notifier_certificate_file", certificate, group='alarm') self.CONF.set_override("rest_notifier_certificate_key", key, group='alarm') with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, cert=(certificate, key), verify=True) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_verify_disable_by_cfg(self): action = 'https://host/action' self.CONF.set_override("rest_notifier_ssl_verify", False, group='alarm') with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, verify=False) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_verify_disable(self): action = 'https://host/action?ceilometer-alarm-ssl-verify=0' with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, verify=False) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) def test_notify_alarm_rest_action_with_ssl_verify_enable_by_user(self): action = 'https://host/action?ceilometer-alarm-ssl-verify=1' self.CONF.set_override("rest_notifier_ssl_verify", False, group='alarm') with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) poster.assert_called_with(action, data=mock.ANY, headers=mock.ANY, verify=True) args, kwargs = poster.call_args self.assertEqual(self.HTTP_HEADERS, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data'])) @staticmethod def _fake_urlsplit(*args, **kwargs): raise Exception("Evil urlsplit!") def test_notify_alarm_invalid_url(self): with mock.patch('oslo.utils.netutils.urlsplit', self._fake_urlsplit): LOG = mock.MagicMock() with mock.patch('ceilometer.alarm.service.LOG', LOG): self.service.notify_alarm( context.get_admin_context(), { 'actions': ['no-such-action-i-am-sure'], 'alarm_id': 'foobar', 'condition': {'threshold': 42}, }) self.assertTrue(LOG.error.called) def test_notify_alarm_invalid_action(self): LOG = mock.MagicMock() with mock.patch('ceilometer.alarm.service.LOG', LOG): self.service.notify_alarm( context.get_admin_context(), { 'actions': ['no-such-action-i-am-sure://'], 'alarm_id': 'foobar', 'condition': {'threshold': 42}, }) self.assertTrue(LOG.error.called) def test_notify_alarm_trust_action(self): action = 'trust+http://trust-1234@host/action' url = 'http://host/action' client = mock.MagicMock() client.auth_token = 'token_1234' headers = {'X-Auth-Token': 'token_1234'} headers.update(self.HTTP_HEADERS) self.useFixture(mockpatch.Patch('keystoneclient.v3.client.Client', lambda **kwargs: client)) with mock.patch('eventlet.spawn_n', self._fake_spawn_n): with mock.patch.object(requests.Session, 'post') as poster: self.service.notify_alarm(context.get_admin_context(), self._notification(action)) headers = {'X-Auth-Token': 'token_1234'} headers.update(self.HTTP_HEADERS) poster.assert_called_with( url, data=mock.ANY, headers=mock.ANY) args, kwargs = poster.call_args self.assertEqual(headers, kwargs['headers']) self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data']))
true
true
1c374d160b1a7756eac4211a6e2f99baca4e1e95
4,253
py
Python
infer.py
Aleksa14/DeepRecommender
39716087ab18cfa7d42a042451b0b9bad7701359
[ "MIT" ]
1
2020-05-27T21:14:45.000Z
2020-05-27T21:14:45.000Z
infer.py
Aleksa14/DeepRecommender
39716087ab18cfa7d42a042451b0b9bad7701359
[ "MIT" ]
null
null
null
infer.py
Aleksa14/DeepRecommender
39716087ab18cfa7d42a042451b0b9bad7701359
[ "MIT" ]
null
null
null
# Copyright (c) 2017 NVIDIA Corporation import torch import argparse import copy from reco_encoder.data import input_layer from reco_encoder.model import model from torch.autograd import Variable from pathlib import Path parser = argparse.ArgumentParser(description='RecoEncoder') parser.add_argument('--drop_prob', type=float, default=0.0, metavar='N', help='dropout drop probability') parser.add_argument('--constrained', action='store_true', help='constrained autoencoder') parser.add_argument('--skip_last_layer_nl', action='store_true', help='if present, decoder\'s last layer will not apply non-linearity function') parser.add_argument('--hidden_layers', type=str, default="1024,512,512,128", metavar='N', help='hidden layer sizes, comma-separated') parser.add_argument('--path_to_train_data', type=str, default="", metavar='N', help='Path to training data') parser.add_argument('--path_to_eval_data', type=str, default="", metavar='N', help='Path to evaluation data') parser.add_argument('--non_linearity_type', type=str, default="selu", metavar='N', help='type of the non-linearity used in activations') parser.add_argument('--save_path', type=str, default="autorec.pt", metavar='N', help='where to save model') parser.add_argument('--predictions_path', type=str, default="out.txt", metavar='N', help='where to save predictions') args = parser.parse_args() print(args) def main(): params = dict() params['batch_size'] = 1 params['data_dir'] = args.path_to_train_data params['major'] = 'users' params['itemIdInd'] = 1 params['userIdInd'] = 0 print("Loading training data") data_layer = input_layer.UserItemRecDataProvider(params=params) print("Data loaded") print("Total items found: {}".format(len(data_layer.data.keys()))) print("Vector dim: {}".format(data_layer.vector_dim)) print("Loading eval data") eval_params = copy.deepcopy(params) # must set eval batch size to 1 to make sure no examples are missed eval_params['batch_size'] = 1 eval_params['data_dir'] = args.path_to_eval_data eval_data_layer = input_layer.UserItemRecDataProvider(params=eval_params, user_id_map=data_layer.userIdMap, item_id_map=data_layer.itemIdMap) rencoder = model.AutoEncoder(layer_sizes=[data_layer.vector_dim] + [int(l) for l in args.hidden_layers.split(',')], nl_type=args.non_linearity_type, is_constrained=args.constrained, dp_drop_prob=args.drop_prob, last_layer_activations=not args.skip_last_layer_nl) path_to_model = Path(args.save_path) if path_to_model.is_file(): print("Loading model from: {}".format(path_to_model)) rencoder.load_state_dict(torch.load(args.save_path)) print('######################################################') print('######################################################') print('############# AutoEncoder Model: #####################') print(rencoder) print('######################################################') print('######################################################') rencoder.eval() rencoder = rencoder.cuda() inv_userIdMap = {v: k for k, v in data_layer.userIdMap.items()} inv_itemIdMap = {v: k for k, v in data_layer.itemIdMap.items()} eval_data_layer.src_data = data_layer.data with open(args.predictions_path, 'w') as outf: for i, ((out, src), majorInd) in enumerate(eval_data_layer.iterate_one_epoch_eval(for_inf=True)): inputs = Variable(src.cuda().to_dense()) targets_np = out.to_dense().numpy()[0, :] outputs = rencoder(inputs).cpu().data.numpy()[0, :] non_zeros = targets_np.nonzero()[0].tolist() major_key = inv_userIdMap [majorInd] for ind in non_zeros: outf.write("{}\t{}\t{}\t{}\n".format(major_key, inv_itemIdMap[ind], outputs[ind], targets_np[ind])) if i % 10000 == 0: print("Done: {}".format(i)) if __name__ == '__main__': main()
44.768421
117
0.61486
import torch import argparse import copy from reco_encoder.data import input_layer from reco_encoder.model import model from torch.autograd import Variable from pathlib import Path parser = argparse.ArgumentParser(description='RecoEncoder') parser.add_argument('--drop_prob', type=float, default=0.0, metavar='N', help='dropout drop probability') parser.add_argument('--constrained', action='store_true', help='constrained autoencoder') parser.add_argument('--skip_last_layer_nl', action='store_true', help='if present, decoder\'s last layer will not apply non-linearity function') parser.add_argument('--hidden_layers', type=str, default="1024,512,512,128", metavar='N', help='hidden layer sizes, comma-separated') parser.add_argument('--path_to_train_data', type=str, default="", metavar='N', help='Path to training data') parser.add_argument('--path_to_eval_data', type=str, default="", metavar='N', help='Path to evaluation data') parser.add_argument('--non_linearity_type', type=str, default="selu", metavar='N', help='type of the non-linearity used in activations') parser.add_argument('--save_path', type=str, default="autorec.pt", metavar='N', help='where to save model') parser.add_argument('--predictions_path', type=str, default="out.txt", metavar='N', help='where to save predictions') args = parser.parse_args() print(args) def main(): params = dict() params['batch_size'] = 1 params['data_dir'] = args.path_to_train_data params['major'] = 'users' params['itemIdInd'] = 1 params['userIdInd'] = 0 print("Loading training data") data_layer = input_layer.UserItemRecDataProvider(params=params) print("Data loaded") print("Total items found: {}".format(len(data_layer.data.keys()))) print("Vector dim: {}".format(data_layer.vector_dim)) print("Loading eval data") eval_params = copy.deepcopy(params) # must set eval batch size to 1 to make sure no examples are missed eval_params['batch_size'] = 1 eval_params['data_dir'] = args.path_to_eval_data eval_data_layer = input_layer.UserItemRecDataProvider(params=eval_params, user_id_map=data_layer.userIdMap, item_id_map=data_layer.itemIdMap) rencoder = model.AutoEncoder(layer_sizes=[data_layer.vector_dim] + [int(l) for l in args.hidden_layers.split(',')], nl_type=args.non_linearity_type, is_constrained=args.constrained, dp_drop_prob=args.drop_prob, last_layer_activations=not args.skip_last_layer_nl) path_to_model = Path(args.save_path) if path_to_model.is_file(): print("Loading model from: {}".format(path_to_model)) rencoder.load_state_dict(torch.load(args.save_path)) print('
true
true
1c374d6ae3a88dac9c6729534d9d1bfafdca28de
90
py
Python
myauth/apps.py
dedol1/verauth_api
ca242abfdcc5296ca4c459e4e92c5dd313cd7160
[ "MIT" ]
null
null
null
myauth/apps.py
dedol1/verauth_api
ca242abfdcc5296ca4c459e4e92c5dd313cd7160
[ "MIT" ]
null
null
null
myauth/apps.py
dedol1/verauth_api
ca242abfdcc5296ca4c459e4e92c5dd313cd7160
[ "MIT" ]
1
2021-11-02T11:55:26.000Z
2021-11-02T11:55:26.000Z
from django.apps import AppConfig class AuthConfig(AppConfig): name = 'myauth'
15
34
0.7
from django.apps import AppConfig class AuthConfig(AppConfig): name = 'myauth'
true
true
1c374e31513a7c62f466af4a87dc098db92f3f28
147
py
Python
08-built-in/08-sys.py
ralexrivero/python_fundation
34a855db7380d3d91db6a8f02d97f287d038ef5f
[ "Apache-2.0" ]
1
2021-09-19T04:09:48.000Z
2021-09-19T04:09:48.000Z
08-built-in/08-sys.py
ralexrivero/python_fundation
34a855db7380d3d91db6a8f02d97f287d038ef5f
[ "Apache-2.0" ]
null
null
null
08-built-in/08-sys.py
ralexrivero/python_fundation
34a855db7380d3d91db6a8f02d97f287d038ef5f
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # Execute ./filename argument1 argument2 import sys first = sys.argv[1] second = sys.argv[2] print(f"Hi {first} {second}")
18.375
40
0.707483
import sys first = sys.argv[1] second = sys.argv[2] print(f"Hi {first} {second}")
true
true
1c374e6a9426ed89d62da42b094b8f0e787764e6
7,359
py
Python
userbot/__init__.py
Neha1000000/userbot
3b88708da229f7d1e5163e64250b3cfde722dc6e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/__init__.py
Neha1000000/userbot
3b88708da229f7d1e5163e64250b3cfde722dc6e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/__init__.py
Neha1000000/userbot
3b88708da229f7d1e5163e64250b3cfde722dc6e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # """ Userbot initialization. """ import os from sys import version_info from logging import basicConfig, getLogger, INFO, DEBUG from distutils.util import strtobool as sb from pylast import LastFMNetwork, md5 from pySmartDL import SmartDL from dotenv import load_dotenv from requests import get from telethon import TelegramClient from telethon.sessions import StringSession load_dotenv("config.env") # Bot Logs setup: CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False")) if CONSOLE_LOGGER_VERBOSE: basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=DEBUG, ) else: basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=INFO) LOGS = getLogger(__name__) if version_info[0] < 3 or version_info[1] < 8: LOGS.info("You MUST have a python version of at least 3.8." "Multiple features depend on this. Bot quitting.") quit(1) # Check if the config was edited by using the already used variable. # Basically, its the 'virginity check' for the config file ;) CONFIG_CHECK = os.environ.get( "", None) if CONFIG_CHECK: LOGS.info( "Please remove the line mentioned in the first hashtag from the config.env file" ) quit(1) # Telegram App KEY and HASH API_KEY = os.environ.get("API_KEY", "1344910") API_HASH = os.environ.get("API_HASH", "d5359102baee69634535553a48032e7f") # Userbot Session String STRING_SESSION = os.environ.get("STRING_SESSION", None) # Logging channel/group ID configuration. BOTLOG_CHATID = int(os.environ.get("BOTLOG_CHATID", None)) # Userbot logging feature switch. BOTLOG = sb(os.environ.get("BOTLOG", "False")) LOGSPAMMER = sb(os.environ.get("LOGSPAMMER", "False")) # Bleep Blop, this is a bot ;) PM_AUTO_BAN = sb(os.environ.get("PM_AUTO_BAN", "False")) # Heroku Credentials for updater. HEROKU_MEMEZ = sb(os.environ.get("HEROKU_MEMEZ", "False")) HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME", None) HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY", None) # Github Credentials for updater and Gitupload. GIT_REPO_NAME = os.environ.get("GIT_REPO_NAME", None) GITHUB_ACCESS_TOKEN = os.environ.get("GITHUB_ACCESS_TOKEN", None) # Custom (forked) repo URL and BRANCH for updater. UPSTREAM_REPO_URL = os.environ.get( "UPSTREAM_REPO_URL", "https://github.com/MoveAngel/One4uBot.git") UPSTREAM_REPO_BRANCH = os.environ.get( "UPSTREAM_REPO_BRANCH", "sql-extended") # Console verbose logging CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False")) # SQL Database URI DB_URI = os.environ.get("DATABASE_URL", None) # OCR API key OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY", None) # remove.bg API key REM_BG_API_KEY = os.environ.get("REM_BG_API_KEY", None) # Chrome Driver and Headless Google Chrome Binaries CHROME_DRIVER = os.environ.get("CHROME_DRIVER", None) GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN", None) # OpenWeatherMap API Key OPEN_WEATHER_MAP_APPID = os.environ.get("OPEN_WEATHER_MAP_APPID", None) WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY", None) # Genius lyrics API GENIUS = os.environ.get("GENIUS_ACCESS_TOKEN", None) # Lydia API LYDIA_API_KEY = os.environ.get("LYDIA_API_KEY", None) # Quotes API Token QUOTES_API_TOKEN = os.environ.get("QUOTES_API_TOKEN", None) # Anti Spambot Config ANTI_SPAMBOT = sb(os.environ.get("ANTI_SPAMBOT", "False")) ANTI_SPAMBOT_SHOUT = sb(os.environ.get("ANTI_SPAMBOT_SHOUT", "False")) # Youtube API key YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY", None) # Telegraph TELEGRAPH_SHORT_NAME = os.environ.get("TELEGRAPH_SHORT_NAME", None) # Default .alive name ALIVE_NAME = os.environ.get("ALIVE_NAME", None) # Time & Date - Country and Time Zone COUNTRY = str(os.environ.get("COUNTRY", "")) TZ_NUMBER = int(os.environ.get("TZ_NUMBER", 1)) # User Terminal alias USER_TERM_ALIAS = os.environ.get("USER_TERM_ALIAS", "One4uBot") # Clean Welcome CLEAN_WELCOME = sb(os.environ.get("CLEAN_WELCOME", "True")) # Last.fm Module BIO_PREFIX = os.environ.get("BIO_PREFIX", None) DEFAULT_BIO = os.environ.get("DEFAULT_BIO", None) LASTFM_API = os.environ.get("LASTFM_API", None) LASTFM_SECRET = os.environ.get("LASTFM_SECRET", None) LASTFM_USERNAME = os.environ.get("LASTFM_USERNAME", None) LASTFM_PASSWORD_PLAIN = os.environ.get("LASTFM_PASSWORD", None) LASTFM_PASS = md5(LASTFM_PASSWORD_PLAIN) if LASTFM_API and LASTFM_SECRET and LASTFM_USERNAME and LASTFM_PASS: lastfm = LastFMNetwork(api_key=LASTFM_API, api_secret=LASTFM_SECRET, username=LASTFM_USERNAME, password_hash=LASTFM_PASS) else: lastfm = None # Google Drive Module G_DRIVE_DATA = os.environ.get("G_DRIVE_DATA", None) G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID", None) G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None) G_DRIVE_AUTH_TOKEN_DATA = os.environ.get("G_DRIVE_AUTH_TOKEN_DATA", None) G_DRIVE_FOLDER_ID = os.environ.get("G_DRIVE_FOLDER_ID", None) TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TMP_DOWNLOAD_DIRECTORY", "./downloads") # Setting Up CloudMail.ru and MEGA.nz extractor binaries, # and giving them correct perms to work properly. if not os.path.exists('bin'): os.mkdir('bin') binaries = { "https://raw.githubusercontent.com/adekmaulana/megadown/master/megadown": "bin/megadown", "https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py": "bin/cmrudl" } for binary, path in binaries.items(): downloader = SmartDL(binary, path, progress_bar=False) downloader.start() os.chmod(path, 0o755) # 'bot' variable if STRING_SESSION: # pylint: disable=invalid-name bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH) else: # pylint: disable=invalid-name bot = TelegramClient("userbot", API_KEY, API_HASH) async def check_botlog_chatid(): if not BOTLOG_CHATID and LOGSPAMMER: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work." ) quit(1) elif not BOTLOG_CHATID and BOTLOG: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work." ) quit(1) elif not BOTLOG or not LOGSPAMMER: return entity = await bot.get_entity(BOTLOG_CHATID) if entity.default_banned_rights.send_messages: LOGS.info( "Your account doesn't have rights to send messages to BOTLOG_CHATID " "group. Check if you typed the Chat ID correctly.") quit(1) with bot: try: bot.loop.run_until_complete(check_botlog_chatid()) except: LOGS.info( "BOTLOG_CHATID environment variable isn't a " "valid entity. Check your environment variables/config.env file.") quit(1) # Global Variables COUNT_MSG = 0 USERS = {} COUNT_PM = {} LASTMSG = {} CMD_HELP = {} ZALG_LIST = {} ISAFK = False AFKREASON = None
31.719828
143
0.718712
import os from sys import version_info from logging import basicConfig, getLogger, INFO, DEBUG from distutils.util import strtobool as sb from pylast import LastFMNetwork, md5 from pySmartDL import SmartDL from dotenv import load_dotenv from requests import get from telethon import TelegramClient from telethon.sessions import StringSession load_dotenv("config.env") CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False")) if CONSOLE_LOGGER_VERBOSE: basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=DEBUG, ) else: basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=INFO) LOGS = getLogger(__name__) if version_info[0] < 3 or version_info[1] < 8: LOGS.info("You MUST have a python version of at least 3.8." "Multiple features depend on this. Bot quitting.") quit(1) CONFIG_CHECK = os.environ.get( "", None) if CONFIG_CHECK: LOGS.info( "Please remove the line mentioned in the first hashtag from the config.env file" ) quit(1) API_KEY = os.environ.get("API_KEY", "1344910") API_HASH = os.environ.get("API_HASH", "d5359102baee69634535553a48032e7f") STRING_SESSION = os.environ.get("STRING_SESSION", None) BOTLOG_CHATID = int(os.environ.get("BOTLOG_CHATID", None)) BOTLOG = sb(os.environ.get("BOTLOG", "False")) LOGSPAMMER = sb(os.environ.get("LOGSPAMMER", "False")) PM_AUTO_BAN = sb(os.environ.get("PM_AUTO_BAN", "False")) HEROKU_MEMEZ = sb(os.environ.get("HEROKU_MEMEZ", "False")) HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME", None) HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY", None) GIT_REPO_NAME = os.environ.get("GIT_REPO_NAME", None) GITHUB_ACCESS_TOKEN = os.environ.get("GITHUB_ACCESS_TOKEN", None) UPSTREAM_REPO_URL = os.environ.get( "UPSTREAM_REPO_URL", "https://github.com/MoveAngel/One4uBot.git") UPSTREAM_REPO_BRANCH = os.environ.get( "UPSTREAM_REPO_BRANCH", "sql-extended") CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False")) DB_URI = os.environ.get("DATABASE_URL", None) OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY", None) REM_BG_API_KEY = os.environ.get("REM_BG_API_KEY", None) CHROME_DRIVER = os.environ.get("CHROME_DRIVER", None) GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN", None) OPEN_WEATHER_MAP_APPID = os.environ.get("OPEN_WEATHER_MAP_APPID", None) WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY", None) GENIUS = os.environ.get("GENIUS_ACCESS_TOKEN", None) LYDIA_API_KEY = os.environ.get("LYDIA_API_KEY", None) QUOTES_API_TOKEN = os.environ.get("QUOTES_API_TOKEN", None) ANTI_SPAMBOT = sb(os.environ.get("ANTI_SPAMBOT", "False")) ANTI_SPAMBOT_SHOUT = sb(os.environ.get("ANTI_SPAMBOT_SHOUT", "False")) YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY", None) TELEGRAPH_SHORT_NAME = os.environ.get("TELEGRAPH_SHORT_NAME", None) ALIVE_NAME = os.environ.get("ALIVE_NAME", None) COUNTRY = str(os.environ.get("COUNTRY", "")) TZ_NUMBER = int(os.environ.get("TZ_NUMBER", 1)) USER_TERM_ALIAS = os.environ.get("USER_TERM_ALIAS", "One4uBot") CLEAN_WELCOME = sb(os.environ.get("CLEAN_WELCOME", "True")) BIO_PREFIX = os.environ.get("BIO_PREFIX", None) DEFAULT_BIO = os.environ.get("DEFAULT_BIO", None) LASTFM_API = os.environ.get("LASTFM_API", None) LASTFM_SECRET = os.environ.get("LASTFM_SECRET", None) LASTFM_USERNAME = os.environ.get("LASTFM_USERNAME", None) LASTFM_PASSWORD_PLAIN = os.environ.get("LASTFM_PASSWORD", None) LASTFM_PASS = md5(LASTFM_PASSWORD_PLAIN) if LASTFM_API and LASTFM_SECRET and LASTFM_USERNAME and LASTFM_PASS: lastfm = LastFMNetwork(api_key=LASTFM_API, api_secret=LASTFM_SECRET, username=LASTFM_USERNAME, password_hash=LASTFM_PASS) else: lastfm = None G_DRIVE_DATA = os.environ.get("G_DRIVE_DATA", None) G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID", None) G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None) G_DRIVE_AUTH_TOKEN_DATA = os.environ.get("G_DRIVE_AUTH_TOKEN_DATA", None) G_DRIVE_FOLDER_ID = os.environ.get("G_DRIVE_FOLDER_ID", None) TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TMP_DOWNLOAD_DIRECTORY", "./downloads") if not os.path.exists('bin'): os.mkdir('bin') binaries = { "https://raw.githubusercontent.com/adekmaulana/megadown/master/megadown": "bin/megadown", "https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py": "bin/cmrudl" } for binary, path in binaries.items(): downloader = SmartDL(binary, path, progress_bar=False) downloader.start() os.chmod(path, 0o755) if STRING_SESSION: bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH) else: bot = TelegramClient("userbot", API_KEY, API_HASH) async def check_botlog_chatid(): if not BOTLOG_CHATID and LOGSPAMMER: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work." ) quit(1) elif not BOTLOG_CHATID and BOTLOG: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work." ) quit(1) elif not BOTLOG or not LOGSPAMMER: return entity = await bot.get_entity(BOTLOG_CHATID) if entity.default_banned_rights.send_messages: LOGS.info( "Your account doesn't have rights to send messages to BOTLOG_CHATID " "group. Check if you typed the Chat ID correctly.") quit(1) with bot: try: bot.loop.run_until_complete(check_botlog_chatid()) except: LOGS.info( "BOTLOG_CHATID environment variable isn't a " "valid entity. Check your environment variables/config.env file.") quit(1) COUNT_MSG = 0 USERS = {} COUNT_PM = {} LASTMSG = {} CMD_HELP = {} ZALG_LIST = {} ISAFK = False AFKREASON = None
true
true
1c375058d2ec067e74c6eede661ad706c1802e75
21,143
py
Python
src/ralph/scan/data.py
quamilek/ralph
bf7231ea096924332b874718b33cd1f43f9c783b
[ "Apache-2.0" ]
null
null
null
src/ralph/scan/data.py
quamilek/ralph
bf7231ea096924332b874718b33cd1f43f9c783b
[ "Apache-2.0" ]
null
null
null
src/ralph/scan/data.py
quamilek/ralph
bf7231ea096924332b874718b33cd1f43f9c783b
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Translating between the device database model and the scan data. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.db import models as db from django.conf import settings from ralph.discovery.models_component import ( ComponentModel, ComponentType, DiskShare, DiskShareMount, Ethernet, FibreChannel, GenericComponent, Memory, OperatingSystem, Processor, Storage, Software, ) from ralph.discovery.models_network import ( IPAddress, ) from ralph.discovery.models_device import ( Device, DeviceType, DeviceModel, ) def _update_addresses(device, address_data, is_management=False): """ Update management or system ip addresses of a device based on data. :param device: Device to be updated :param address_data: list of strings with the ip addresses :param is_management: whether to update management or system addresses """ ipaddress_ids = [] for ip in address_data: try: ipaddress = IPAddress.objects.get(address=ip) except IPAddress.DoesNotExist: ipaddress = IPAddress(address=ip) ipaddress.device = device ipaddress.is_management = is_management ipaddress.save(update_last_seen=False) ipaddress_ids.append(ipaddress.id) # Disconnect the rest of addresses from this device for ipaddress in IPAddress.objects.filter( device=device, is_management=is_management, ).exclude(id__in=ipaddress_ids): ipaddress.device = None ipaddress.save(update_last_seen=False) def _update_component_data( device, component_data, Component, field_map, unique_fields, model_type=None, forbidden_model_fields=set(), ): """ Update components of a device based on the data from scan. This function is a little tricky, because we want to reuse the components as much as possible, instead of deleting everything and creating new ones every time. :param component_data: list of dicts describing the components :param Component: model to use to query and create components :param field_map: mapping from database fields to component_data keys :param unique_fields: list of tuples of fields that are unique together :param model_type: If provided, a 'model' field will be added :param forbidden_model_fields: If provided, model will be created without those fields """ component_ids = [] for index, data in enumerate(component_data): data['device'] = device data['index'] = index for group in unique_fields: # First try to find an existing component using unique fields fields = { field: data[field_map[field]] for field in group if data.get(field_map[field]) is not None } if len(group) != len(fields): continue try: component = Component.objects.get(**fields) except Component.DoesNotExist: continue break else: # No matching component found, create a new one if model_type is not None or 'type' in data: # If model_type is provided, create the model model = None if model_type is None: try: model_type = ComponentType.from_name(data['type']) except ValueError: model_type = None if model_type is not None: model_fields = { field: data[field_map[field]] for field in field_map if all(( data.get(field_map[field]), field != 'type', field not in forbidden_model_fields, )) } if all(( 'model_name' in data, 'name' not in forbidden_model_fields, )): model_fields['name'] = data['model_name'] model, created = ComponentModel.create( model_type, 0, **model_fields) if model is None: raise ValueError('Unknown model') component = Component(model=model) else: component = Component() # Fill the component with values from the data dict for field, key in field_map.iteritems(): if key in data: setattr(component, field, data[key]) component.save(priority=100) component_ids.append(component.id) # Delete the components that are no longer current for component in Component.objects.filter( device=device, ).exclude( id__in=component_ids, ): component.delete() def get_device_data(device): """ Generate a dict with all information that is stored in the database about this device, in a format compatible with that returned by the discovery plugins. """ data = { 'id': device.id, 'system_ip_addresses': [ ip.address for ip in device.ipaddress_set.filter(is_management=False) ], 'management_ip_addresses': [ ip.address for ip in device.ipaddress_set.filter(is_management=True) ], 'mac_addresses': [ eth.mac for eth in device.ethernet_set.all() ], } if device.name != 'unknown': data['hostname'] = device.name if device.model is not None: data['model_name'] = device.model.name if device.model.type != DeviceType.unknown: data['type'] = DeviceType.from_id(device.model.type).name if device.sn is not None: data['serial_number'] = device.sn if device.chassis_position: data['chassis_position'] = device.chassis_position if device.dc: data['data_center'] = device.dc if device.rack: data['rack'] = device.rack data['memory'] = [ { 'label': m.label, 'size': m.size, 'speed': m.speed, 'index': m.index, } for m in device.memory_set.order_by('index') ] data['processors'] = [ { 'model_name': p.model.name if p.model else '', 'speed': p.speed, 'cores': p.get_cores(), 'family': p.model.family if p.model else '', 'label': p.label, 'index': p.index, } for p in device.processor_set.order_by('index') ] disks = [] for disk in device.storage_set.order_by('sn', 'mount_point'): disk_data = { 'label': disk.label, 'size': disk.size, } if disk.sn: disk_data['serial_number'] = disk.sn if disk.mount_point: disk_data['mount_point'] = disk.mount_point if disk.model: disk_data.update({ 'model_name': disk.model.name, 'family': disk.model.family, }) disks.append(disk_data) data['disks'] = disks data['disk_exports'] = [ { 'serial_number': share.wwn, 'full': share.full, 'size': share.size, 'snapshot_size': share.snapshot_size, 'label': share.label, 'share_id': share.share_id, 'model_name': share.model.name if share.model else '', } for share in device.diskshare_set.order_by('wwn') ] disk_shares = [] for mount in device.disksharemount_set.order_by('volume', 'address'): mount_data = { 'serial_number': mount.share.wwn if mount.share else '', 'size': mount.size, 'address': mount.address.address if mount.address else '', 'is_virtual': mount.is_virtual, 'volume': mount.volume, } if mount.server: mount_data['server'] = { 'serial_number': mount.server.sn, } else: mount_data['server'] = None disk_shares.append(mount_data) data['disk_shares'] = disk_shares data['installed_software'] = [ { 'label': soft.label, 'version': soft.version, 'path': soft.path, 'serial_number': soft.sn, 'model_name': soft.model.name if soft.model else '', } for soft in device.software_set.order_by('label', 'version') ] data['fibrechannel_cards'] = [ { 'physical_id': fc.physical_id, 'label': fc.label, 'model_name': fc.model.name if fc.model else '', } for fc in device.fibrechannel_set.order_by('label') ] data['parts'] = [ { 'serial_number': part.sn, 'label': part.label, 'boot_firmware': part.boot_firmware, 'hard_firmware': part.hard_firmware, 'diag_firmware': part.diag_firmware, 'mgmt_firmware': part.mgmt_firmware, 'model_name': part.model.name if part.model else '', 'type': ComponentType.from_id( part.model.type, ).raw if part.model else '', } for part in device.genericcomponent_set.order_by('sn') ] data['subdevices'] = [ get_device_data(dev) for dev in device.child_set.order_by('id') ] if device.operatingsystem_set.exists(): system = device.operatingsystem_set.all()[0] data['system_label'] = system.label data['system_memory'] = system.memory data['system_storage'] = system.storage data['system_cores_count'] = system.cores_count if system.model: data['system_family'] = system.model.family if 'ralph_assets' in settings.INSTALLED_APPS: from ralph_assets.api_ralph import get_asset asset = get_asset(device.id) if asset: data['asset'] = '{}, sn: {}'.format(asset['model'], asset['sn']) else: data['asset'] = None return data def set_device_data(device, data): """ Go through the submitted data, and update the Device object in accordance with the meaning of the particular fields. """ keys = { 'sn': 'serial_number', 'name': 'hostname', 'dc': 'data_center', 'rack': 'rack', 'barcode': 'barcode', 'chassis_position': 'chassis_position', } for field_name, key_name in keys.iteritems(): if key_name in data: setattr(device, field_name, data[key_name]) if 'model_name' in data: try: model_type = DeviceType.from_name(data.get('type', 'unknown')) except ValueError: model_type = ComponentType.unknown try: # Don't use get_or_create, because we are in transaction device.model = DeviceModel.objects.get(name=data['model_name']) except DeviceModel.DoesNotExist: model = DeviceModel( type=model_type, name=data['model_name'], ) model.save() device.model = model else: if all(( device.model.type != model_type, model_type != ComponentType.unknown, )): device.model.type = model_type device.model.save() if 'disks' in data: _update_component_data( device, data['disks'], Storage, { 'sn': 'serial_number', 'device': 'device', 'size': 'size', 'speed': 'speed', 'mount_point': 'mount_point', 'label': 'label', 'family': 'family', 'model_name': 'model_name', }, [ ('sn',), ('device', 'mount_point'), ], ComponentType.disk, {'name'}, ) if 'processors' in data: for index, processor in enumerate(data['processors']): processor['index'] = index _update_component_data( device, data['processors'], Processor, { 'device': 'device', 'label': 'label', 'speed': 'speed', 'cores': 'cores', 'family': 'family', 'index': 'index', 'model_name': 'model_name', }, [ ('device', 'index'), ], ComponentType.processor, ) if 'memory' in data: for index, memory in enumerate(data['memory']): memory['index'] = index memory['speed'] = memory.get('speed', None) or None _update_component_data( device, data['memory'], Memory, { 'device': 'device', 'label': 'label', 'speed': 'speed', 'size': 'size', 'index': 'index', }, [ ('device', 'index'), ], ComponentType.memory, {'name'}, ) if 'mac_addresses' in data: _update_component_data( device, [{'mac': mac} for mac in data['mac_addresses']], Ethernet, { 'mac': 'mac', 'device': 'device', }, [ ('mac',), ], None, ) if 'management_ip_addresses' in data: _update_addresses(device, data['management_ip_addresses'], True) if 'system_ip_addresses' in data: _update_addresses(device, data['system_ip_addresses'], False) if 'fibrechannel_cards' in data: _update_component_data( device, data['fibrechannel_cards'], FibreChannel, { 'device': 'device', 'label': 'label', 'model_name': 'model_name', 'physical_id': 'physical_id', }, [ ('physical_id', 'device'), ], ComponentType.fibre, ) if 'parts' in data: _update_component_data( device, data['parts'], GenericComponent, { 'device': 'device', 'label': 'label', 'model_name': 'model_name', 'sn': 'serial_number', 'type': 'type', }, [ ('sn',), ], ) if 'disk_exports' in data: _update_component_data( device, data['disk_exports'], DiskShare, { 'device': 'device', 'label': 'label', 'wwn': 'serial_number', 'size': 'size', 'full': 'full', 'snapshot_size': 'snapshot_size', 'share_id': 'share_id', 'model_name': 'model_name', }, [ ('wwn',), ], ComponentType.share, ) if 'disk_shares' in data: for share in data['disk_shares']: if share.get('server'): servers = find_devices({ 'server': share['server'], }) if len(servers) > 1: raise ValueError( "Multiple servers found for share mount %r" % share, ) elif len(servers) <= 0: raise ValueError( "No server found for share mount %r" % share, ) share['server'] = servers[0] else: share['server'] = None share['share'] = DiskShare.objects.get(wwn=share['serial_number']) if share.get('address'): share['address'] = IPAddress.objects.get( address=share['address'], ) _update_component_data( device, data['disk_shares'], DiskShareMount, { 'share': 'share', 'size': 'size', 'address': 'address', 'is_virtual': 'is_virtual', 'volume': 'volume', 'server': 'server', 'device': 'device', }, [ ('device', 'share'), ], ) if 'installed_software' in data: _update_component_data( device, data['installed_software'], Software, { 'device': 'device', 'path': 'path', 'label': 'label', 'version': 'version', 'model_name': 'model_name', 'sn': 'serial_number', }, [ ('device', 'path'), ], ComponentType.software, ) if ( 'system_label' in data or 'system_memory' in data or 'system_storage' in data or 'system_cores_count' in data or 'system_family' in data or 'system_model_name' in data ): _update_component_data( device, [data], OperatingSystem, { 'device': 'device', 'memory': 'system_memory', 'storage': 'system_storage', 'cores_count': 'system_cores_count', 'family': 'system_family', 'label': 'system_label', 'model_name': 'system_model_name', }, [ ('device',), ], ComponentType.os, ) if 'subdevices' in data: subdevice_ids = [] for subdevice_data in data['subdevices']: subdevice = device_from_data(subdevice_data) subdevice.parent = device subdevice.save() subdevice_ids.append(subdevice.id) for subdevice in device.child_set.exclude(id__in=subdevice_ids): subdevice.parent = None subdevice.save() if 'asset' in data and 'ralph_assets' in settings.INSTALLED_APPS: from ralph_assets.api_ralph import assign_asset if data['asset']: assign_asset(device.id, data['asset'].id) def device_from_data(data): """ Create or find a device based on the provided scan data. """ sn = data.get('serial_number') ethernets = [('', mac, None) for mac in data.get('mac_addresses', [])] model_name = data.get('model_name') model_type = DeviceType.from_name(data.get('type', 'unknown').lower()) device = Device.create( sn=sn, ethernets=ethernets, model_name=model_name, model_type=model_type, ) set_device_data(device, data) device.save() return device def merge_data(*args, **kwargs): """ Merge several dicts with data from a scan into a single dict. :param *args: data to merge :param only_multiple: if True, only keys with multiple values are returned """ only_multiple = kwargs.get('only_multiple', False) merged = {} for result in args: for plugin_name, data in result.iteritems(): for key, value in data.get('device', {}).iteritems(): merged.setdefault(key, {})[plugin_name] = value # Now, make the values unique. unique = {} for key, values in merged.iteritems(): repeated = {} for source, value in values.iteritems(): repeated.setdefault(unicode(value), []).append(source) if only_multiple and len(repeated) <= 1: continue for value_str, sources in repeated.iteritems(): sources.sort() unique.setdefault( key, {}, )[tuple(sources)] = merged[key][sources[0]] return unique def find_devices(result): """ Find all devices that can be possibly matched to this scan data. """ ids = set( r['device']['id'] for r in result.itervalues() if 'id' in r.get('device', {}) ) serials = set( r['device']['serial_number'] for r in result.itervalues() if 'serial_number' in r.get('device', {}) ) macs = set() for r in result.itervalues(): macs |= set(r.get('device', {}).get('mac_addresses', [])) return Device.admin_objects.filter( db.Q(id__in=ids) | db.Q(sn__in=serials) | db.Q(ethernet__mac__in=macs) ).distinct()
32.328746
78
0.516814
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.db import models as db from django.conf import settings from ralph.discovery.models_component import ( ComponentModel, ComponentType, DiskShare, DiskShareMount, Ethernet, FibreChannel, GenericComponent, Memory, OperatingSystem, Processor, Storage, Software, ) from ralph.discovery.models_network import ( IPAddress, ) from ralph.discovery.models_device import ( Device, DeviceType, DeviceModel, ) def _update_addresses(device, address_data, is_management=False): ipaddress_ids = [] for ip in address_data: try: ipaddress = IPAddress.objects.get(address=ip) except IPAddress.DoesNotExist: ipaddress = IPAddress(address=ip) ipaddress.device = device ipaddress.is_management = is_management ipaddress.save(update_last_seen=False) ipaddress_ids.append(ipaddress.id) for ipaddress in IPAddress.objects.filter( device=device, is_management=is_management, ).exclude(id__in=ipaddress_ids): ipaddress.device = None ipaddress.save(update_last_seen=False) def _update_component_data( device, component_data, Component, field_map, unique_fields, model_type=None, forbidden_model_fields=set(), ): component_ids = [] for index, data in enumerate(component_data): data['device'] = device data['index'] = index for group in unique_fields: fields = { field: data[field_map[field]] for field in group if data.get(field_map[field]) is not None } if len(group) != len(fields): continue try: component = Component.objects.get(**fields) except Component.DoesNotExist: continue break else: if model_type is not None or 'type' in data: model = None if model_type is None: try: model_type = ComponentType.from_name(data['type']) except ValueError: model_type = None if model_type is not None: model_fields = { field: data[field_map[field]] for field in field_map if all(( data.get(field_map[field]), field != 'type', field not in forbidden_model_fields, )) } if all(( 'model_name' in data, 'name' not in forbidden_model_fields, )): model_fields['name'] = data['model_name'] model, created = ComponentModel.create( model_type, 0, **model_fields) if model is None: raise ValueError('Unknown model') component = Component(model=model) else: component = Component() for field, key in field_map.iteritems(): if key in data: setattr(component, field, data[key]) component.save(priority=100) component_ids.append(component.id) for component in Component.objects.filter( device=device, ).exclude( id__in=component_ids, ): component.delete() def get_device_data(device): data = { 'id': device.id, 'system_ip_addresses': [ ip.address for ip in device.ipaddress_set.filter(is_management=False) ], 'management_ip_addresses': [ ip.address for ip in device.ipaddress_set.filter(is_management=True) ], 'mac_addresses': [ eth.mac for eth in device.ethernet_set.all() ], } if device.name != 'unknown': data['hostname'] = device.name if device.model is not None: data['model_name'] = device.model.name if device.model.type != DeviceType.unknown: data['type'] = DeviceType.from_id(device.model.type).name if device.sn is not None: data['serial_number'] = device.sn if device.chassis_position: data['chassis_position'] = device.chassis_position if device.dc: data['data_center'] = device.dc if device.rack: data['rack'] = device.rack data['memory'] = [ { 'label': m.label, 'size': m.size, 'speed': m.speed, 'index': m.index, } for m in device.memory_set.order_by('index') ] data['processors'] = [ { 'model_name': p.model.name if p.model else '', 'speed': p.speed, 'cores': p.get_cores(), 'family': p.model.family if p.model else '', 'label': p.label, 'index': p.index, } for p in device.processor_set.order_by('index') ] disks = [] for disk in device.storage_set.order_by('sn', 'mount_point'): disk_data = { 'label': disk.label, 'size': disk.size, } if disk.sn: disk_data['serial_number'] = disk.sn if disk.mount_point: disk_data['mount_point'] = disk.mount_point if disk.model: disk_data.update({ 'model_name': disk.model.name, 'family': disk.model.family, }) disks.append(disk_data) data['disks'] = disks data['disk_exports'] = [ { 'serial_number': share.wwn, 'full': share.full, 'size': share.size, 'snapshot_size': share.snapshot_size, 'label': share.label, 'share_id': share.share_id, 'model_name': share.model.name if share.model else '', } for share in device.diskshare_set.order_by('wwn') ] disk_shares = [] for mount in device.disksharemount_set.order_by('volume', 'address'): mount_data = { 'serial_number': mount.share.wwn if mount.share else '', 'size': mount.size, 'address': mount.address.address if mount.address else '', 'is_virtual': mount.is_virtual, 'volume': mount.volume, } if mount.server: mount_data['server'] = { 'serial_number': mount.server.sn, } else: mount_data['server'] = None disk_shares.append(mount_data) data['disk_shares'] = disk_shares data['installed_software'] = [ { 'label': soft.label, 'version': soft.version, 'path': soft.path, 'serial_number': soft.sn, 'model_name': soft.model.name if soft.model else '', } for soft in device.software_set.order_by('label', 'version') ] data['fibrechannel_cards'] = [ { 'physical_id': fc.physical_id, 'label': fc.label, 'model_name': fc.model.name if fc.model else '', } for fc in device.fibrechannel_set.order_by('label') ] data['parts'] = [ { 'serial_number': part.sn, 'label': part.label, 'boot_firmware': part.boot_firmware, 'hard_firmware': part.hard_firmware, 'diag_firmware': part.diag_firmware, 'mgmt_firmware': part.mgmt_firmware, 'model_name': part.model.name if part.model else '', 'type': ComponentType.from_id( part.model.type, ).raw if part.model else '', } for part in device.genericcomponent_set.order_by('sn') ] data['subdevices'] = [ get_device_data(dev) for dev in device.child_set.order_by('id') ] if device.operatingsystem_set.exists(): system = device.operatingsystem_set.all()[0] data['system_label'] = system.label data['system_memory'] = system.memory data['system_storage'] = system.storage data['system_cores_count'] = system.cores_count if system.model: data['system_family'] = system.model.family if 'ralph_assets' in settings.INSTALLED_APPS: from ralph_assets.api_ralph import get_asset asset = get_asset(device.id) if asset: data['asset'] = '{}, sn: {}'.format(asset['model'], asset['sn']) else: data['asset'] = None return data def set_device_data(device, data): keys = { 'sn': 'serial_number', 'name': 'hostname', 'dc': 'data_center', 'rack': 'rack', 'barcode': 'barcode', 'chassis_position': 'chassis_position', } for field_name, key_name in keys.iteritems(): if key_name in data: setattr(device, field_name, data[key_name]) if 'model_name' in data: try: model_type = DeviceType.from_name(data.get('type', 'unknown')) except ValueError: model_type = ComponentType.unknown try: device.model = DeviceModel.objects.get(name=data['model_name']) except DeviceModel.DoesNotExist: model = DeviceModel( type=model_type, name=data['model_name'], ) model.save() device.model = model else: if all(( device.model.type != model_type, model_type != ComponentType.unknown, )): device.model.type = model_type device.model.save() if 'disks' in data: _update_component_data( device, data['disks'], Storage, { 'sn': 'serial_number', 'device': 'device', 'size': 'size', 'speed': 'speed', 'mount_point': 'mount_point', 'label': 'label', 'family': 'family', 'model_name': 'model_name', }, [ ('sn',), ('device', 'mount_point'), ], ComponentType.disk, {'name'}, ) if 'processors' in data: for index, processor in enumerate(data['processors']): processor['index'] = index _update_component_data( device, data['processors'], Processor, { 'device': 'device', 'label': 'label', 'speed': 'speed', 'cores': 'cores', 'family': 'family', 'index': 'index', 'model_name': 'model_name', }, [ ('device', 'index'), ], ComponentType.processor, ) if 'memory' in data: for index, memory in enumerate(data['memory']): memory['index'] = index memory['speed'] = memory.get('speed', None) or None _update_component_data( device, data['memory'], Memory, { 'device': 'device', 'label': 'label', 'speed': 'speed', 'size': 'size', 'index': 'index', }, [ ('device', 'index'), ], ComponentType.memory, {'name'}, ) if 'mac_addresses' in data: _update_component_data( device, [{'mac': mac} for mac in data['mac_addresses']], Ethernet, { 'mac': 'mac', 'device': 'device', }, [ ('mac',), ], None, ) if 'management_ip_addresses' in data: _update_addresses(device, data['management_ip_addresses'], True) if 'system_ip_addresses' in data: _update_addresses(device, data['system_ip_addresses'], False) if 'fibrechannel_cards' in data: _update_component_data( device, data['fibrechannel_cards'], FibreChannel, { 'device': 'device', 'label': 'label', 'model_name': 'model_name', 'physical_id': 'physical_id', }, [ ('physical_id', 'device'), ], ComponentType.fibre, ) if 'parts' in data: _update_component_data( device, data['parts'], GenericComponent, { 'device': 'device', 'label': 'label', 'model_name': 'model_name', 'sn': 'serial_number', 'type': 'type', }, [ ('sn',), ], ) if 'disk_exports' in data: _update_component_data( device, data['disk_exports'], DiskShare, { 'device': 'device', 'label': 'label', 'wwn': 'serial_number', 'size': 'size', 'full': 'full', 'snapshot_size': 'snapshot_size', 'share_id': 'share_id', 'model_name': 'model_name', }, [ ('wwn',), ], ComponentType.share, ) if 'disk_shares' in data: for share in data['disk_shares']: if share.get('server'): servers = find_devices({ 'server': share['server'], }) if len(servers) > 1: raise ValueError( "Multiple servers found for share mount %r" % share, ) elif len(servers) <= 0: raise ValueError( "No server found for share mount %r" % share, ) share['server'] = servers[0] else: share['server'] = None share['share'] = DiskShare.objects.get(wwn=share['serial_number']) if share.get('address'): share['address'] = IPAddress.objects.get( address=share['address'], ) _update_component_data( device, data['disk_shares'], DiskShareMount, { 'share': 'share', 'size': 'size', 'address': 'address', 'is_virtual': 'is_virtual', 'volume': 'volume', 'server': 'server', 'device': 'device', }, [ ('device', 'share'), ], ) if 'installed_software' in data: _update_component_data( device, data['installed_software'], Software, { 'device': 'device', 'path': 'path', 'label': 'label', 'version': 'version', 'model_name': 'model_name', 'sn': 'serial_number', }, [ ('device', 'path'), ], ComponentType.software, ) if ( 'system_label' in data or 'system_memory' in data or 'system_storage' in data or 'system_cores_count' in data or 'system_family' in data or 'system_model_name' in data ): _update_component_data( device, [data], OperatingSystem, { 'device': 'device', 'memory': 'system_memory', 'storage': 'system_storage', 'cores_count': 'system_cores_count', 'family': 'system_family', 'label': 'system_label', 'model_name': 'system_model_name', }, [ ('device',), ], ComponentType.os, ) if 'subdevices' in data: subdevice_ids = [] for subdevice_data in data['subdevices']: subdevice = device_from_data(subdevice_data) subdevice.parent = device subdevice.save() subdevice_ids.append(subdevice.id) for subdevice in device.child_set.exclude(id__in=subdevice_ids): subdevice.parent = None subdevice.save() if 'asset' in data and 'ralph_assets' in settings.INSTALLED_APPS: from ralph_assets.api_ralph import assign_asset if data['asset']: assign_asset(device.id, data['asset'].id) def device_from_data(data): sn = data.get('serial_number') ethernets = [('', mac, None) for mac in data.get('mac_addresses', [])] model_name = data.get('model_name') model_type = DeviceType.from_name(data.get('type', 'unknown').lower()) device = Device.create( sn=sn, ethernets=ethernets, model_name=model_name, model_type=model_type, ) set_device_data(device, data) device.save() return device def merge_data(*args, **kwargs): only_multiple = kwargs.get('only_multiple', False) merged = {} for result in args: for plugin_name, data in result.iteritems(): for key, value in data.get('device', {}).iteritems(): merged.setdefault(key, {})[plugin_name] = value # Now, make the values unique. unique = {} for key, values in merged.iteritems(): repeated = {} for source, value in values.iteritems(): repeated.setdefault(unicode(value), []).append(source) if only_multiple and len(repeated) <= 1: continue for value_str, sources in repeated.iteritems(): sources.sort() unique.setdefault( key, {}, )[tuple(sources)] = merged[key][sources[0]] return unique def find_devices(result): ids = set( r['device']['id'] for r in result.itervalues() if 'id' in r.get('device', {}) ) serials = set( r['device']['serial_number'] for r in result.itervalues() if 'serial_number' in r.get('device', {}) ) macs = set() for r in result.itervalues(): macs |= set(r.get('device', {}).get('mac_addresses', [])) return Device.admin_objects.filter( db.Q(id__in=ids) | db.Q(sn__in=serials) | db.Q(ethernet__mac__in=macs) ).distinct()
true
true
1c37509f13e11d36b9a9ac8d0e304095fd1cba3c
232
py
Python
python_modules/dagster/dagster/core/engine/engine_base.py
bambielli-flex/dagster
30b75ba7c62fc536bc827f177c1dc6ba20f5ae20
[ "Apache-2.0" ]
1
2019-07-15T17:34:04.000Z
2019-07-15T17:34:04.000Z
python_modules/dagster/dagster/core/engine/engine_base.py
bambielli-flex/dagster
30b75ba7c62fc536bc827f177c1dc6ba20f5ae20
[ "Apache-2.0" ]
null
null
null
python_modules/dagster/dagster/core/engine/engine_base.py
bambielli-flex/dagster
30b75ba7c62fc536bc827f177c1dc6ba20f5ae20
[ "Apache-2.0" ]
null
null
null
import abc import six class IEngine(six.with_metaclass(abc.ABCMeta)): # pylint: disable=no-init @staticmethod @abc.abstractmethod def execute(pipeline_context, execution_plan, step_keys_to_execute=None): pass
23.2
77
0.74569
import abc import six class IEngine(six.with_metaclass(abc.ABCMeta)): @staticmethod @abc.abstractmethod def execute(pipeline_context, execution_plan, step_keys_to_execute=None): pass
true
true
1c375280df1eca68f1c9b7ef13d8563c43f619fd
13,872
py
Python
projects/vdk-control-cli/src/vdk/internal/control/command_groups/job/deploy_cli_impl.py
vmware/versatile-data-kit
c4e10324a4f3203c58079cb18203880f68053f15
[ "Apache-2.0" ]
100
2021-10-04T09:32:04.000Z
2022-03-30T11:23:53.000Z
projects/vdk-control-cli/src/vdk/internal/control/command_groups/job/deploy_cli_impl.py
vmware/versatile-data-kit
c4e10324a4f3203c58079cb18203880f68053f15
[ "Apache-2.0" ]
208
2021-10-04T16:56:40.000Z
2022-03-31T10:41:44.000Z
projects/vdk-control-cli/src/vdk/internal/control/command_groups/job/deploy_cli_impl.py
vmware/versatile-data-kit
c4e10324a4f3203c58079cb18203880f68053f15
[ "Apache-2.0" ]
14
2021-10-11T14:15:13.000Z
2022-03-11T13:39:17.000Z
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 import glob import json import logging import os from typing import Optional import click import click_spinner from tabulate import tabulate from taurus_datajob_api import ApiException from taurus_datajob_api import DataJob from taurus_datajob_api import DataJobConfig from taurus_datajob_api import DataJobContacts from taurus_datajob_api import DataJobDeployment from taurus_datajob_api import DataJobSchedule from vdk.internal.control.configuration.defaults_config import load_default_team_name from vdk.internal.control.exception.vdk_exception import VDKException from vdk.internal.control.job.job_archive import JobArchive from vdk.internal.control.job.job_config import JobConfig from vdk.internal.control.rest_lib.factory import ApiClientFactory from vdk.internal.control.rest_lib.rest_client_errors import ApiClientErrorDecorator from vdk.internal.control.utils.cli_utils import get_or_prompt from vdk.internal.control.utils.cli_utils import OutputFormat log = logging.getLogger(__name__) class JobDeploy: ZIP_ARCHIVE_TYPE = "zip" ARCHIVE_SUFFIX = "-archive" def __init__(self, rest_api_url: str, output): self.deploy_api = ApiClientFactory(rest_api_url).get_deploy_api() self.jobs_api = ApiClientFactory(rest_api_url).get_jobs_api() self.job_sources_api = ApiClientFactory(rest_api_url).get_jobs_sources_api() # support for multiple deployments is not implemented yet so we can put anything here. # Ultimately this will be user facing parameter (possibly fetched from config.ini) self.__deployment_id = "production" self.__job_archive = JobArchive() @staticmethod def __detect_keytab_files_in_job_directory(job_path: str) -> None: keytab_glob = os.path.join(job_path, "**/*.keytab") keytab_files = glob.glob(keytab_glob, recursive=True) if keytab_files: raise VDKException( what=f"Detected keytab file inside data job directory.: {keytab_files}", why="Keytab files are secret and must be kept separate - usually at the same level as data job directory but not inside.", consequence="In order to prevent security issues, data job code will not be uploaded and deploy operation is aborted.", countermeasure="Move the keytab file outside data job directory and try to deploy again.", ) @staticmethod def __validate_datajob(job_path: str, job_config: JobConfig, team: str) -> None: log.debug( "Validate data job does not have credentials in its directory (keytab file)" ) JobDeploy.__detect_keytab_files_in_job_directory(job_path) log.debug("Validate data job team is consistent.") job_config_team = job_config.get_team() if team is not None and job_config_team is not None and team != job_config_team: raise VDKException( what="Cannot create new deployment of the data job.", why=f"Team param ({team}) and team value in config.ini ({job_config_team}) do not match.", consequence="The latest change is not deployed, job will continue to run with previous version.", countermeasure=f"1. Fix config.ini to set correct team (if it is {team}) OR\n" f"2. Do not pass team param (team {job_config_team} will be automatically used from config.ini) OR\n" f"3. Pass param team={job_config_team} OR\n" f"4. Create a new job with team={team} and try to deploy it\n", ) # TODO: we may use https://github.com/Yelp/detect-secrets to make sure users do not accidentally pass secrets @staticmethod def __check_value(key: str, value: str) -> str: if not value: raise VDKException( what="Cannot extract job configuration.", why=f"Configuration property {key} in file config.ini is missing.", consequence="Cannot deploy the Data Job.", countermeasure="Update config.ini.", ) return value def __read_data_job(self, name: str, team: str) -> DataJob: try: return self.jobs_api.data_job_read(team_name=team, job_name=name) except ApiException as e: raise VDKException( what=f"Cannot find data job {name}", why="Data job does not exist on CLOUD.", consequence="Cannot deploy the Data Job.", countermeasure="Use VDK CLI create command to create the job first.", ) from e @staticmethod def __archive_binary(job_archive_path: str) -> bytes: log.debug(f"Read archive binary: {job_archive_path}") with open(job_archive_path, "rb") as job_archive_file: # Read the whole file at once job_archive_binary = job_archive_file.read() return job_archive_binary @staticmethod def __cleanup_archive(archive_path: str) -> None: try: log.debug(f"Remove temp archive {archive_path}") os.remove(archive_path) except OSError as e: log.warning( VDKException( what=f"Cannot cleanup archive: {archive_path} as part of deployment.", why=f"VDK CLI did not clean up after deploying: {e}", consequence="There is a leftover archive file next to the folder containing the data job", countermeasure="Clean up the archive file manually or leave it", ).message ) def __update_data_job_deploy_configuration( self, job_path: str, name: str, team: str ) -> None: job: DataJob = self.__read_data_job(name, team) local_config = JobConfig(job_path) schedule = local_config.get_schedule_cron() if len(schedule) == 0: log.warning( "You have provided no schedule for your Data Job. " "Note that your deployed job will not be scheduled and will only run when manually executed." ) contacts = DataJobContacts( local_config.get_contacts_notified_on_job_failure_user_error(), local_config.get_contacts_notified_on_job_failure_platform_error(), local_config.get_contacts_notified_on_job_success(), local_config.get_contacts_notified_on_job_deploy(), ) job.config = DataJobConfig( enable_execution_notifications=local_config.get_enable_execution_notifications(), notification_delay_period_minutes=local_config.get_notification_delay_period_minutes(), contacts=contacts, schedule=DataJobSchedule(schedule_cron=schedule), ) log.debug(f"Update data job deploy configuration: {job}") self.jobs_api.data_job_update(team_name=team, job_name=name, data_job=job) @ApiClientErrorDecorator() def update( self, name: str, team: str, enabled: Optional[bool], # true, false or None job_version: Optional[str], vdk_version: Optional[str], output: str, ) -> None: deployment = DataJobDeployment(enabled=None) if job_version: deployment.job_version = job_version if vdk_version: deployment.vdk_version = vdk_version deployment.enabled = enabled if job_version: self.__update_job_version(name, team, deployment, output) elif vdk_version or enabled is not None: self.__update_deployment(name, team, deployment) msg = f"Deployment of Data Job {name} updated; " if vdk_version: msg = msg + f"vdk version: {vdk_version}; " if enabled is not None: msg = msg + "status: " + ("enabled" if enabled else "disabled") + "; " log.info(msg) else: log.warning(f"Nothing to update for deployment of job {name}.") def __update_deployment( self, name: str, team: str, deployment: DataJobDeployment ) -> None: log.debug(f"Update Deployment of a job {name} of team {team} : {deployment}") self.deploy_api.deployment_patch( team_name=team, job_name=name, deployment_id=self.__deployment_id, data_job_deployment=deployment, ) def __update_job_version( self, name: str, team: str, deployment: DataJobDeployment, output: str ): log.debug( f"Update Deployment version of a job {name} of team {team} : {deployment}" ) self.deploy_api.deployment_update( team_name=team, job_name=name, data_job_deployment=deployment ) if output == OutputFormat.TEXT.value: log.info( f"Request to deploy Data Job {name} using version {deployment.job_version} finished successfully.\n" f"It would take a few minutes for the Data Job to be deployed in the server.\n" f"If notified_on_job_deploy option in config.ini is configured then " f"notification will be sent on successful deploy or in case of an error.\n\n" f"You can also execute `vdk deploy --show -t '{team}' -n '{name}'` and compare the printed version " f"to the one of the newly deployed job - {deployment.job_version} - to verify that the deployment " f"was successful." ) else: result = { "job_name": name, "job_version": deployment.job_version, } click.echo(json.dumps(result)) @ApiClientErrorDecorator() def remove(self, name: str, team: str) -> None: log.debug(f"Remove Deployment of a job {name} of team {team}") self.deploy_api.deployment_delete( team_name=team, job_name=name, deployment_id=self.__deployment_id ) log.info(f"Deployment of Data Job {name} removed.") @ApiClientErrorDecorator() def show(self, name: str, team: str, output: str) -> None: log.debug(f"Get list of deployments for job {name} of team {team} ") deployments = self.deploy_api.deployment_list(team_name=team, job_name=name) log.debug( f"Found following deployments for job {name} of team {team} : {deployments}" ) if deployments: # d.to_dict() brings unnecessary parts of data deployments = map( lambda d: dict( job_name=name, job_version=d.job_version, last_deployed_by=d.last_deployed_by, last_deployed_date=d.last_deployed_date, enabled=d.enabled, ), deployments, ) if output == OutputFormat.TEXT.value: click.echo( "You can compare the version seen here to the one seen when " "deploying to verify your deployment was successful." ) click.echo("") click.echo(tabulate(deployments, headers="keys")) else: click.echo(json.dumps(list(deployments))) else: if output == OutputFormat.TEXT.value: click.echo("No deployments.") else: click.echo(json.dumps([])) @ApiClientErrorDecorator() def create( self, name: str, team: str, job_path: str, reason: str, output: str, vdk_version: Optional[str], enabled: Optional[bool], ) -> None: log.debug( f"Create Deployment of a job {name} of team {team} with local path {job_path} and reason {reason}" ) job_path = os.path.abspath(job_path) if not os.path.isdir(job_path): raise VDKException( what="Cannot create new deployment of the data job.", why=f"Directory {job_path} does not exists.", consequence="The latest change is not deployed, job will continue to run with previous version", countermeasure="Provide correct path to the Data Job.", ) log.debug( "We verify that config.ini exists. This is to avoid uploading accidentally some random directory" ) job_config = JobConfig(job_path) self.__validate_datajob(job_path=job_path, job_config=job_config, team=team) team = get_or_prompt( "Team Name", team or job_config.get_team() or load_default_team_name() ) if output == OutputFormat.TEXT.value: log.info( f"Deploy Data Job with name {name} from directory {job_path} ... \n" ) archive_path = self.__job_archive.archive_data_job( job_name=name, job_archive_path=job_path ) try: job_archive_binary = self.__archive_binary(archive_path) if output == OutputFormat.TEXT.value: log.info("Uploading the data job might take some time ...") with click_spinner.spinner(disable=(output == OutputFormat.JSON.value)): data_job_version = self.job_sources_api.sources_upload( team_name=team, job_name=name, body=job_archive_binary, reason=reason, ) self.__update_data_job_deploy_configuration(job_path, name, team) self.update( name, team, enabled, data_job_version.version_sha, vdk_version, output ) finally: self.__cleanup_archive(archive_path=archive_path)
43.760252
138
0.626081
import glob import json import logging import os from typing import Optional import click import click_spinner from tabulate import tabulate from taurus_datajob_api import ApiException from taurus_datajob_api import DataJob from taurus_datajob_api import DataJobConfig from taurus_datajob_api import DataJobContacts from taurus_datajob_api import DataJobDeployment from taurus_datajob_api import DataJobSchedule from vdk.internal.control.configuration.defaults_config import load_default_team_name from vdk.internal.control.exception.vdk_exception import VDKException from vdk.internal.control.job.job_archive import JobArchive from vdk.internal.control.job.job_config import JobConfig from vdk.internal.control.rest_lib.factory import ApiClientFactory from vdk.internal.control.rest_lib.rest_client_errors import ApiClientErrorDecorator from vdk.internal.control.utils.cli_utils import get_or_prompt from vdk.internal.control.utils.cli_utils import OutputFormat log = logging.getLogger(__name__) class JobDeploy: ZIP_ARCHIVE_TYPE = "zip" ARCHIVE_SUFFIX = "-archive" def __init__(self, rest_api_url: str, output): self.deploy_api = ApiClientFactory(rest_api_url).get_deploy_api() self.jobs_api = ApiClientFactory(rest_api_url).get_jobs_api() self.job_sources_api = ApiClientFactory(rest_api_url).get_jobs_sources_api() self.__deployment_id = "production" self.__job_archive = JobArchive() @staticmethod def __detect_keytab_files_in_job_directory(job_path: str) -> None: keytab_glob = os.path.join(job_path, "**/*.keytab") keytab_files = glob.glob(keytab_glob, recursive=True) if keytab_files: raise VDKException( what=f"Detected keytab file inside data job directory.: {keytab_files}", why="Keytab files are secret and must be kept separate - usually at the same level as data job directory but not inside.", consequence="In order to prevent security issues, data job code will not be uploaded and deploy operation is aborted.", countermeasure="Move the keytab file outside data job directory and try to deploy again.", ) @staticmethod def __validate_datajob(job_path: str, job_config: JobConfig, team: str) -> None: log.debug( "Validate data job does not have credentials in its directory (keytab file)" ) JobDeploy.__detect_keytab_files_in_job_directory(job_path) log.debug("Validate data job team is consistent.") job_config_team = job_config.get_team() if team is not None and job_config_team is not None and team != job_config_team: raise VDKException( what="Cannot create new deployment of the data job.", why=f"Team param ({team}) and team value in config.ini ({job_config_team}) do not match.", consequence="The latest change is not deployed, job will continue to run with previous version.", countermeasure=f"1. Fix config.ini to set correct team (if it is {team}) OR\n" f"2. Do not pass team param (team {job_config_team} will be automatically used from config.ini) OR\n" f"3. Pass param team={job_config_team} OR\n" f"4. Create a new job with team={team} and try to deploy it\n", ) @staticmethod def __check_value(key: str, value: str) -> str: if not value: raise VDKException( what="Cannot extract job configuration.", why=f"Configuration property {key} in file config.ini is missing.", consequence="Cannot deploy the Data Job.", countermeasure="Update config.ini.", ) return value def __read_data_job(self, name: str, team: str) -> DataJob: try: return self.jobs_api.data_job_read(team_name=team, job_name=name) except ApiException as e: raise VDKException( what=f"Cannot find data job {name}", why="Data job does not exist on CLOUD.", consequence="Cannot deploy the Data Job.", countermeasure="Use VDK CLI create command to create the job first.", ) from e @staticmethod def __archive_binary(job_archive_path: str) -> bytes: log.debug(f"Read archive binary: {job_archive_path}") with open(job_archive_path, "rb") as job_archive_file: job_archive_binary = job_archive_file.read() return job_archive_binary @staticmethod def __cleanup_archive(archive_path: str) -> None: try: log.debug(f"Remove temp archive {archive_path}") os.remove(archive_path) except OSError as e: log.warning( VDKException( what=f"Cannot cleanup archive: {archive_path} as part of deployment.", why=f"VDK CLI did not clean up after deploying: {e}", consequence="There is a leftover archive file next to the folder containing the data job", countermeasure="Clean up the archive file manually or leave it", ).message ) def __update_data_job_deploy_configuration( self, job_path: str, name: str, team: str ) -> None: job: DataJob = self.__read_data_job(name, team) local_config = JobConfig(job_path) schedule = local_config.get_schedule_cron() if len(schedule) == 0: log.warning( "You have provided no schedule for your Data Job. " "Note that your deployed job will not be scheduled and will only run when manually executed." ) contacts = DataJobContacts( local_config.get_contacts_notified_on_job_failure_user_error(), local_config.get_contacts_notified_on_job_failure_platform_error(), local_config.get_contacts_notified_on_job_success(), local_config.get_contacts_notified_on_job_deploy(), ) job.config = DataJobConfig( enable_execution_notifications=local_config.get_enable_execution_notifications(), notification_delay_period_minutes=local_config.get_notification_delay_period_minutes(), contacts=contacts, schedule=DataJobSchedule(schedule_cron=schedule), ) log.debug(f"Update data job deploy configuration: {job}") self.jobs_api.data_job_update(team_name=team, job_name=name, data_job=job) @ApiClientErrorDecorator() def update( self, name: str, team: str, enabled: Optional[bool], job_version: Optional[str], vdk_version: Optional[str], output: str, ) -> None: deployment = DataJobDeployment(enabled=None) if job_version: deployment.job_version = job_version if vdk_version: deployment.vdk_version = vdk_version deployment.enabled = enabled if job_version: self.__update_job_version(name, team, deployment, output) elif vdk_version or enabled is not None: self.__update_deployment(name, team, deployment) msg = f"Deployment of Data Job {name} updated; " if vdk_version: msg = msg + f"vdk version: {vdk_version}; " if enabled is not None: msg = msg + "status: " + ("enabled" if enabled else "disabled") + "; " log.info(msg) else: log.warning(f"Nothing to update for deployment of job {name}.") def __update_deployment( self, name: str, team: str, deployment: DataJobDeployment ) -> None: log.debug(f"Update Deployment of a job {name} of team {team} : {deployment}") self.deploy_api.deployment_patch( team_name=team, job_name=name, deployment_id=self.__deployment_id, data_job_deployment=deployment, ) def __update_job_version( self, name: str, team: str, deployment: DataJobDeployment, output: str ): log.debug( f"Update Deployment version of a job {name} of team {team} : {deployment}" ) self.deploy_api.deployment_update( team_name=team, job_name=name, data_job_deployment=deployment ) if output == OutputFormat.TEXT.value: log.info( f"Request to deploy Data Job {name} using version {deployment.job_version} finished successfully.\n" f"It would take a few minutes for the Data Job to be deployed in the server.\n" f"If notified_on_job_deploy option in config.ini is configured then " f"notification will be sent on successful deploy or in case of an error.\n\n" f"You can also execute `vdk deploy --show -t '{team}' -n '{name}'` and compare the printed version " f"to the one of the newly deployed job - {deployment.job_version} - to verify that the deployment " f"was successful." ) else: result = { "job_name": name, "job_version": deployment.job_version, } click.echo(json.dumps(result)) @ApiClientErrorDecorator() def remove(self, name: str, team: str) -> None: log.debug(f"Remove Deployment of a job {name} of team {team}") self.deploy_api.deployment_delete( team_name=team, job_name=name, deployment_id=self.__deployment_id ) log.info(f"Deployment of Data Job {name} removed.") @ApiClientErrorDecorator() def show(self, name: str, team: str, output: str) -> None: log.debug(f"Get list of deployments for job {name} of team {team} ") deployments = self.deploy_api.deployment_list(team_name=team, job_name=name) log.debug( f"Found following deployments for job {name} of team {team} : {deployments}" ) if deployments: deployments = map( lambda d: dict( job_name=name, job_version=d.job_version, last_deployed_by=d.last_deployed_by, last_deployed_date=d.last_deployed_date, enabled=d.enabled, ), deployments, ) if output == OutputFormat.TEXT.value: click.echo( "You can compare the version seen here to the one seen when " "deploying to verify your deployment was successful." ) click.echo("") click.echo(tabulate(deployments, headers="keys")) else: click.echo(json.dumps(list(deployments))) else: if output == OutputFormat.TEXT.value: click.echo("No deployments.") else: click.echo(json.dumps([])) @ApiClientErrorDecorator() def create( self, name: str, team: str, job_path: str, reason: str, output: str, vdk_version: Optional[str], enabled: Optional[bool], ) -> None: log.debug( f"Create Deployment of a job {name} of team {team} with local path {job_path} and reason {reason}" ) job_path = os.path.abspath(job_path) if not os.path.isdir(job_path): raise VDKException( what="Cannot create new deployment of the data job.", why=f"Directory {job_path} does not exists.", consequence="The latest change is not deployed, job will continue to run with previous version", countermeasure="Provide correct path to the Data Job.", ) log.debug( "We verify that config.ini exists. This is to avoid uploading accidentally some random directory" ) job_config = JobConfig(job_path) self.__validate_datajob(job_path=job_path, job_config=job_config, team=team) team = get_or_prompt( "Team Name", team or job_config.get_team() or load_default_team_name() ) if output == OutputFormat.TEXT.value: log.info( f"Deploy Data Job with name {name} from directory {job_path} ... \n" ) archive_path = self.__job_archive.archive_data_job( job_name=name, job_archive_path=job_path ) try: job_archive_binary = self.__archive_binary(archive_path) if output == OutputFormat.TEXT.value: log.info("Uploading the data job might take some time ...") with click_spinner.spinner(disable=(output == OutputFormat.JSON.value)): data_job_version = self.job_sources_api.sources_upload( team_name=team, job_name=name, body=job_archive_binary, reason=reason, ) self.__update_data_job_deploy_configuration(job_path, name, team) self.update( name, team, enabled, data_job_version.version_sha, vdk_version, output ) finally: self.__cleanup_archive(archive_path=archive_path)
true
true
1c3752a76d771bdb174957f32118bdb4672da833
6,471
py
Python
dapper/_core.py
markrwilliams/dapper
e18bc91d7b494437ef5946584b4d842dc03cb5d8
[ "MIT" ]
3
2016-12-14T08:55:47.000Z
2016-12-23T22:31:46.000Z
dapper/_core.py
markrwilliams/dapper
e18bc91d7b494437ef5946584b4d842dc03cb5d8
[ "MIT" ]
null
null
null
dapper/_core.py
markrwilliams/dapper
e18bc91d7b494437ef5946584b4d842dc03cb5d8
[ "MIT" ]
null
null
null
import attr import io import itertools import functools import struct _gen_id = functools.partial(next, itertools.count()) class Incomplete(Exception): """ Not enough data. """ @attr.s class ClaimableByteBuffer(object): _bio = attr.ib(default=attr.Factory(io.BytesIO)) _total = attr.ib(init=False, default=0) _claimed = attr.ib(init=False, default=0) def write(self, value): position = self._bio.tell() self._bio.seek(0, 2) self._bio.write(value) self._bio.seek(position) self._total += len(value) def unclaimed(self): return self._total - self._claimed def claim(self, amount): self._claimed = max(self._total, self._claimed + amount) return self._bio.read(amount) class Container(object): def __init__(self, **kwargs): self._fields = [] for name, value in kwargs.iteritems(): self._fields.append(name) setattr(self, name, value) def __eq__(self, other): if not isinstance(other, Container): return False if other._fields != self._fields: return False return all(getattr(other, field) == getattr(self, field) for field in self._fields) @attr.s(frozen=True) class _NullContext(object): """ An empty context. """ _the_null_context = _NullContext() @attr.s class FormatField(object): _packer = attr.ib(convert=struct.Struct) _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _the_null_context def _feed(self, context, byte_buffer): if byte_buffer.unclaimed() < self._packer.size: raise Incomplete return self._packer.unpack(byte_buffer.claim(self._packer.size)) def _emit(self, byte_buffer, *values): byte_buffer.write(self._packer.pack(*values)) @attr.s class UBInt8(object): _field = attr.ib(init=False, default=FormatField('>b')) _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _the_null_context def _feed(self, context, byte_buffer): return self._field._feed(context, byte_buffer)[0] def _emit(self, byte_buffer, value): self._field._emit(byte_buffer, value) @attr.s class UBInt16(object): _field = attr.ib(init=False, default=FormatField('>h')) _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _the_null_context def _feed(self, context, byte_buffer): return self._field._feed(context, byte_buffer)[0] def _emit(self, byte_buffer, value): self._field._emit(byte_buffer, value) @attr.s class UBInt24(object): _field = attr.ib(init=False, default=FormatField('>bbb')) _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _the_null_context def _feed(self, context, byte_buffer): high, medium, low = self._field._feed(context, byte_buffer) return high << 16 | medium << 8 | low def _emit(self, byte_buffer, value): high = (value & 0xFF0000) >> 16 medium = (value & 0x00FF00) >> 8 low = value & 0x0000FF self._field._emit(byte_buffer, high, medium, low) @attr.s class _StructContext(object): position = attr.ib(default=0) parsed = attr.ib(default=attr.Factory(list)) children = attr.ib(default=attr.Factory(dict)) @attr.s class Struct(object): members = attr.ib() _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _StructContext() def _feed(self, context, byte_buffer): for idx in range(context.position, len(self.members)): name, dap = self.members[idx] parsed = _feed(dap, context.children, byte_buffer) context.parsed.append(parsed) context.position += 1 return Container( **{name: parsed for name, parsed in zip((name for name, _ in self.members), context.parsed)}) def _emit(self, byte_buffer, container): for name, dap in self.members: dap._emit(byte_buffer, getattr(container, name)) @attr.s class _SequenceContext(object): position = attr.ib(default=0) parsed = attr.ib(default=attr.Factory(list)) children = attr.ib(default=attr.Factory(dict)) @attr.s class Sequence(object): _MISSING = "MISSING" members = attr.ib() _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _SequenceContext() def _feed(self, context, byte_buffer): for idx in range(context.position, len(self.members)): dap = self.members[idx] parsed = _feed(dap, context.children, byte_buffer) context.parsed.append(parsed) context.position += 1 return context.parsed def _emit(self, byte_buffer, values): members_iterator = iter(self.members) values_iterator = iter(values) for dap, value in zip(members_iterator, values_iterator): dap._emit(byte_buffer, value) @attr.s class _LayerContext(object): parsed = attr.ib(default=0) children = attr.ib(default=attr.Factory(dict)) @attr.s class Layer(object): _upper = attr.ib() _lower = attr.ib() _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _LayerContext() def _feed(self, context, byte_buffer): if not context.parsed: context.parsed = _feed(self._lower, context.children, byte_buffer) return _feed(self._upper, context.children, byte_buffer) def _emit(self, byte_buffer, values): self._lower(byte_buffer, self._upper.emit(byte_buffer, values)) @attr.s class Translate(object): _inward = attr.ib() _outward = attr.ib() def _feed(dap, pending, byte_buffer): context = pending.get(dap._id) if context is None: pending[dap._id] = context = dap._prepare_context() return dap._feed(context, byte_buffer) @attr.s class FeedContext(object): byte_buffer = attr.ib(default=attr.Factory(ClaimableByteBuffer)) children = attr.ib(default=attr.Factory(dict)) def feed(dap, data, context): context.byte_buffer.write(data) return _feed(dap, context.children, context.byte_buffer) def emit(dap, value): byte_buffer = io.BytesIO() dap._emit(byte_buffer, value) return byte_buffer.getvalue()
26.412245
78
0.65214
import attr import io import itertools import functools import struct _gen_id = functools.partial(next, itertools.count()) class Incomplete(Exception): @attr.s class ClaimableByteBuffer(object): _bio = attr.ib(default=attr.Factory(io.BytesIO)) _total = attr.ib(init=False, default=0) _claimed = attr.ib(init=False, default=0) def write(self, value): position = self._bio.tell() self._bio.seek(0, 2) self._bio.write(value) self._bio.seek(position) self._total += len(value) def unclaimed(self): return self._total - self._claimed def claim(self, amount): self._claimed = max(self._total, self._claimed + amount) return self._bio.read(amount) class Container(object): def __init__(self, **kwargs): self._fields = [] for name, value in kwargs.iteritems(): self._fields.append(name) setattr(self, name, value) def __eq__(self, other): if not isinstance(other, Container): return False if other._fields != self._fields: return False return all(getattr(other, field) == getattr(self, field) for field in self._fields) @attr.s(frozen=True) class _NullContext(object): _the_null_context = _NullContext() @attr.s class FormatField(object): _packer = attr.ib(convert=struct.Struct) _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _the_null_context def _feed(self, context, byte_buffer): if byte_buffer.unclaimed() < self._packer.size: raise Incomplete return self._packer.unpack(byte_buffer.claim(self._packer.size)) def _emit(self, byte_buffer, *values): byte_buffer.write(self._packer.pack(*values)) @attr.s class UBInt8(object): _field = attr.ib(init=False, default=FormatField('>b')) _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _the_null_context def _feed(self, context, byte_buffer): return self._field._feed(context, byte_buffer)[0] def _emit(self, byte_buffer, value): self._field._emit(byte_buffer, value) @attr.s class UBInt16(object): _field = attr.ib(init=False, default=FormatField('>h')) _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _the_null_context def _feed(self, context, byte_buffer): return self._field._feed(context, byte_buffer)[0] def _emit(self, byte_buffer, value): self._field._emit(byte_buffer, value) @attr.s class UBInt24(object): _field = attr.ib(init=False, default=FormatField('>bbb')) _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _the_null_context def _feed(self, context, byte_buffer): high, medium, low = self._field._feed(context, byte_buffer) return high << 16 | medium << 8 | low def _emit(self, byte_buffer, value): high = (value & 0xFF0000) >> 16 medium = (value & 0x00FF00) >> 8 low = value & 0x0000FF self._field._emit(byte_buffer, high, medium, low) @attr.s class _StructContext(object): position = attr.ib(default=0) parsed = attr.ib(default=attr.Factory(list)) children = attr.ib(default=attr.Factory(dict)) @attr.s class Struct(object): members = attr.ib() _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _StructContext() def _feed(self, context, byte_buffer): for idx in range(context.position, len(self.members)): name, dap = self.members[idx] parsed = _feed(dap, context.children, byte_buffer) context.parsed.append(parsed) context.position += 1 return Container( **{name: parsed for name, parsed in zip((name for name, _ in self.members), context.parsed)}) def _emit(self, byte_buffer, container): for name, dap in self.members: dap._emit(byte_buffer, getattr(container, name)) @attr.s class _SequenceContext(object): position = attr.ib(default=0) parsed = attr.ib(default=attr.Factory(list)) children = attr.ib(default=attr.Factory(dict)) @attr.s class Sequence(object): _MISSING = "MISSING" members = attr.ib() _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _SequenceContext() def _feed(self, context, byte_buffer): for idx in range(context.position, len(self.members)): dap = self.members[idx] parsed = _feed(dap, context.children, byte_buffer) context.parsed.append(parsed) context.position += 1 return context.parsed def _emit(self, byte_buffer, values): members_iterator = iter(self.members) values_iterator = iter(values) for dap, value in zip(members_iterator, values_iterator): dap._emit(byte_buffer, value) @attr.s class _LayerContext(object): parsed = attr.ib(default=0) children = attr.ib(default=attr.Factory(dict)) @attr.s class Layer(object): _upper = attr.ib() _lower = attr.ib() _id = attr.ib(default=attr.Factory(_gen_id)) def _prepare_context(self): return _LayerContext() def _feed(self, context, byte_buffer): if not context.parsed: context.parsed = _feed(self._lower, context.children, byte_buffer) return _feed(self._upper, context.children, byte_buffer) def _emit(self, byte_buffer, values): self._lower(byte_buffer, self._upper.emit(byte_buffer, values)) @attr.s class Translate(object): _inward = attr.ib() _outward = attr.ib() def _feed(dap, pending, byte_buffer): context = pending.get(dap._id) if context is None: pending[dap._id] = context = dap._prepare_context() return dap._feed(context, byte_buffer) @attr.s class FeedContext(object): byte_buffer = attr.ib(default=attr.Factory(ClaimableByteBuffer)) children = attr.ib(default=attr.Factory(dict)) def feed(dap, data, context): context.byte_buffer.write(data) return _feed(dap, context.children, context.byte_buffer) def emit(dap, value): byte_buffer = io.BytesIO() dap._emit(byte_buffer, value) return byte_buffer.getvalue()
true
true
1c3752c54c8dbbbee88f6d6a4aca79f6a3d3600f
18,042
py
Python
homeassistant/components/xiaomi_miio/switch.py
alindeman/home-assistant
b274b10f3874c196f0db8f9cfa5f47eb756d1f8e
[ "Apache-2.0" ]
4
2019-07-03T22:36:57.000Z
2019-08-10T15:33:25.000Z
homeassistant/components/xiaomi_miio/switch.py
alindeman/home-assistant
b274b10f3874c196f0db8f9cfa5f47eb756d1f8e
[ "Apache-2.0" ]
7
2019-08-23T05:26:02.000Z
2022-03-11T23:57:18.000Z
homeassistant/components/xiaomi_miio/switch.py
alindeman/home-assistant
b274b10f3874c196f0db8f9cfa5f47eb756d1f8e
[ "Apache-2.0" ]
2
2018-08-15T03:59:35.000Z
2018-10-18T12:20:05.000Z
"""Support for Xiaomi Smart WiFi Socket and Smart Power Strip.""" import asyncio from functools import partial import logging import voluptuous as vol from homeassistant.components.switch import ( DOMAIN, PLATFORM_SCHEMA, SwitchDevice) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, CONF_NAME, CONF_TOKEN) from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Xiaomi Miio Switch' DATA_KEY = 'switch.xiaomi_miio' CONF_MODEL = 'model' MODEL_POWER_STRIP_V2 = 'zimi.powerstrip.v2' MODEL_PLUG_V3 = 'chuangmi.plug.v3' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_MODEL): vol.In( ['chuangmi.plug.v1', 'qmi.powerstrip.v1', 'zimi.powerstrip.v2', 'chuangmi.plug.m1', 'chuangmi.plug.m3', 'chuangmi.plug.v2', 'chuangmi.plug.v3', 'chuangmi.plug.hmi205', 'lumi.acpartner.v3', ]), }) ATTR_POWER = 'power' ATTR_TEMPERATURE = 'temperature' ATTR_LOAD_POWER = 'load_power' ATTR_MODEL = 'model' ATTR_MODE = 'mode' ATTR_POWER_MODE = 'power_mode' ATTR_WIFI_LED = 'wifi_led' ATTR_POWER_PRICE = 'power_price' ATTR_PRICE = 'price' SUCCESS = ['ok'] FEATURE_SET_POWER_MODE = 1 FEATURE_SET_WIFI_LED = 2 FEATURE_SET_POWER_PRICE = 4 FEATURE_FLAGS_GENERIC = 0 FEATURE_FLAGS_POWER_STRIP_V1 = (FEATURE_SET_POWER_MODE | FEATURE_SET_WIFI_LED | FEATURE_SET_POWER_PRICE) FEATURE_FLAGS_POWER_STRIP_V2 = (FEATURE_SET_WIFI_LED | FEATURE_SET_POWER_PRICE) FEATURE_FLAGS_PLUG_V3 = (FEATURE_SET_WIFI_LED) SERVICE_SET_WIFI_LED_ON = 'xiaomi_miio_set_wifi_led_on' SERVICE_SET_WIFI_LED_OFF = 'xiaomi_miio_set_wifi_led_off' SERVICE_SET_POWER_MODE = 'xiaomi_miio_set_power_mode' SERVICE_SET_POWER_PRICE = 'xiaomi_miio_set_power_price' SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, }) SERVICE_SCHEMA_POWER_MODE = SERVICE_SCHEMA.extend({ vol.Required(ATTR_MODE): vol.All(vol.In(['green', 'normal'])), }) SERVICE_SCHEMA_POWER_PRICE = SERVICE_SCHEMA.extend({ vol.Required(ATTR_PRICE): vol.All(vol.Coerce(float), vol.Range(min=0)) }) SERVICE_TO_METHOD = { SERVICE_SET_WIFI_LED_ON: {'method': 'async_set_wifi_led_on'}, SERVICE_SET_WIFI_LED_OFF: {'method': 'async_set_wifi_led_off'}, SERVICE_SET_POWER_MODE: { 'method': 'async_set_power_mode', 'schema': SERVICE_SCHEMA_POWER_MODE}, SERVICE_SET_POWER_PRICE: { 'method': 'async_set_power_price', 'schema': SERVICE_SCHEMA_POWER_PRICE}, } async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the switch from config.""" from miio import Device, DeviceException if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} host = config.get(CONF_HOST) name = config.get(CONF_NAME) token = config.get(CONF_TOKEN) model = config.get(CONF_MODEL) _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) devices = [] unique_id = None if model is None: try: miio_device = Device(host, token) device_info = miio_device.info() model = device_info.model unique_id = "{}-{}".format(model, device_info.mac_address) _LOGGER.info("%s %s %s detected", model, device_info.firmware_version, device_info.hardware_version) except DeviceException: raise PlatformNotReady if model in ['chuangmi.plug.v1', 'chuangmi.plug.v3']: from miio import ChuangmiPlug plug = ChuangmiPlug(host, token, model=model) # The device has two switchable channels (mains and a USB port). # A switch device per channel will be created. for channel_usb in [True, False]: device = ChuangMiPlugSwitch( name, plug, model, unique_id, channel_usb) devices.append(device) hass.data[DATA_KEY][host] = device elif model in ['qmi.powerstrip.v1', 'zimi.powerstrip.v2']: from miio import PowerStrip plug = PowerStrip(host, token, model=model) device = XiaomiPowerStripSwitch(name, plug, model, unique_id) devices.append(device) hass.data[DATA_KEY][host] = device elif model in ['chuangmi.plug.m1', 'chuangmi.plug.m3', 'chuangmi.plug.v2', 'chuangmi.plug.hmi205']: from miio import ChuangmiPlug plug = ChuangmiPlug(host, token, model=model) device = XiaomiPlugGenericSwitch(name, plug, model, unique_id) devices.append(device) hass.data[DATA_KEY][host] = device elif model in ['lumi.acpartner.v3']: from miio import AirConditioningCompanionV3 plug = AirConditioningCompanionV3(host, token) device = XiaomiAirConditioningCompanionSwitch(name, plug, model, unique_id) devices.append(device) hass.data[DATA_KEY][host] = device else: _LOGGER.error( 'Unsupported device found! Please create an issue at ' 'https://github.com/rytilahti/python-miio/issues ' 'and provide the following data: %s', model) return False async_add_entities(devices, update_before_add=True) async def async_service_handler(service): """Map services to methods on XiaomiPlugGenericSwitch.""" method = SERVICE_TO_METHOD.get(service.service) params = {key: value for key, value in service.data.items() if key != ATTR_ENTITY_ID} entity_ids = service.data.get(ATTR_ENTITY_ID) if entity_ids: devices = [device for device in hass.data[DATA_KEY].values() if device.entity_id in entity_ids] else: devices = hass.data[DATA_KEY].values() update_tasks = [] for device in devices: if not hasattr(device, method['method']): continue await getattr(device, method['method'])(**params) update_tasks.append(device.async_update_ha_state(True)) if update_tasks: await asyncio.wait(update_tasks) for plug_service in SERVICE_TO_METHOD: schema = SERVICE_TO_METHOD[plug_service].get('schema', SERVICE_SCHEMA) hass.services.async_register( DOMAIN, plug_service, async_service_handler, schema=schema) class XiaomiPlugGenericSwitch(SwitchDevice): """Representation of a Xiaomi Plug Generic.""" def __init__(self, name, plug, model, unique_id): """Initialize the plug switch.""" self._name = name self._plug = plug self._model = model self._unique_id = unique_id self._icon = 'mdi:power-socket' self._available = False self._state = None self._state_attrs = { ATTR_TEMPERATURE: None, ATTR_MODEL: self._model, } self._device_features = FEATURE_FLAGS_GENERIC self._skip_update = False @property def should_poll(self): """Poll the plug.""" return True @property def unique_id(self): """Return an unique ID.""" return self._unique_id @property def name(self): """Return the name of the device if any.""" return self._name @property def icon(self): """Return the icon to use for device if any.""" return self._icon @property def available(self): """Return true when state is known.""" return self._available @property def device_state_attributes(self): """Return the state attributes of the device.""" return self._state_attrs @property def is_on(self): """Return true if switch is on.""" return self._state async def _try_command(self, mask_error, func, *args, **kwargs): """Call a plug command handling error messages.""" from miio import DeviceException try: result = await self.hass.async_add_executor_job( partial(func, *args, **kwargs)) _LOGGER.debug("Response received from plug: %s", result) # The Chuangmi Plug V3 returns 0 on success on usb_on/usb_off. if func in ['usb_on', 'usb_off'] and result == 0: return True return result == SUCCESS except DeviceException as exc: _LOGGER.error(mask_error, exc) self._available = False return False async def async_turn_on(self, **kwargs): """Turn the plug on.""" result = await self._try_command( "Turning the plug on failed.", self._plug.on) if result: self._state = True self._skip_update = True async def async_turn_off(self, **kwargs): """Turn the plug off.""" result = await self._try_command( "Turning the plug off failed.", self._plug.off) if result: self._state = False self._skip_update = True async def async_update(self): """Fetch state from the device.""" from miio import DeviceException # On state change the device doesn't provide the new state immediately. if self._skip_update: self._skip_update = False return try: state = await self.hass.async_add_executor_job(self._plug.status) _LOGGER.debug("Got new state: %s", state) self._available = True self._state = state.is_on self._state_attrs[ATTR_TEMPERATURE] = state.temperature except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) async def async_set_wifi_led_on(self): """Turn the wifi led on.""" if self._device_features & FEATURE_SET_WIFI_LED == 0: return await self._try_command( "Turning the wifi led on failed.", self._plug.set_wifi_led, True) async def async_set_wifi_led_off(self): """Turn the wifi led on.""" if self._device_features & FEATURE_SET_WIFI_LED == 0: return await self._try_command( "Turning the wifi led off failed.", self._plug.set_wifi_led, False) async def async_set_power_price(self, price: int): """Set the power price.""" if self._device_features & FEATURE_SET_POWER_PRICE == 0: return await self._try_command( "Setting the power price of the power strip failed.", self._plug.set_power_price, price) class XiaomiPowerStripSwitch(XiaomiPlugGenericSwitch): """Representation of a Xiaomi Power Strip.""" def __init__(self, name, plug, model, unique_id): """Initialize the plug switch.""" super().__init__(name, plug, model, unique_id) if self._model == MODEL_POWER_STRIP_V2: self._device_features = FEATURE_FLAGS_POWER_STRIP_V2 else: self._device_features = FEATURE_FLAGS_POWER_STRIP_V1 self._state_attrs[ATTR_LOAD_POWER] = None if self._device_features & FEATURE_SET_POWER_MODE == 1: self._state_attrs[ATTR_POWER_MODE] = None if self._device_features & FEATURE_SET_WIFI_LED == 1: self._state_attrs[ATTR_WIFI_LED] = None if self._device_features & FEATURE_SET_POWER_PRICE == 1: self._state_attrs[ATTR_POWER_PRICE] = None async def async_update(self): """Fetch state from the device.""" from miio import DeviceException # On state change the device doesn't provide the new state immediately. if self._skip_update: self._skip_update = False return try: state = await self.hass.async_add_executor_job(self._plug.status) _LOGGER.debug("Got new state: %s", state) self._available = True self._state = state.is_on self._state_attrs.update({ ATTR_TEMPERATURE: state.temperature, ATTR_LOAD_POWER: state.load_power, }) if self._device_features & FEATURE_SET_POWER_MODE == 1 and \ state.mode: self._state_attrs[ATTR_POWER_MODE] = state.mode.value if self._device_features & FEATURE_SET_WIFI_LED == 1 and \ state.wifi_led: self._state_attrs[ATTR_WIFI_LED] = state.wifi_led if self._device_features & FEATURE_SET_POWER_PRICE == 1 and \ state.power_price: self._state_attrs[ATTR_POWER_PRICE] = state.power_price except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) async def async_set_power_mode(self, mode: str): """Set the power mode.""" if self._device_features & FEATURE_SET_POWER_MODE == 0: return from miio.powerstrip import PowerMode await self._try_command( "Setting the power mode of the power strip failed.", self._plug.set_power_mode, PowerMode(mode)) class ChuangMiPlugSwitch(XiaomiPlugGenericSwitch): """Representation of a Chuang Mi Plug V1 and V3.""" def __init__(self, name, plug, model, unique_id, channel_usb): """Initialize the plug switch.""" name = '{} USB'.format(name) if channel_usb else name if unique_id is not None and channel_usb: unique_id = "{}-{}".format(unique_id, 'usb') super().__init__(name, plug, model, unique_id) self._channel_usb = channel_usb if self._model == MODEL_PLUG_V3: self._device_features = FEATURE_FLAGS_PLUG_V3 self._state_attrs[ATTR_WIFI_LED] = None if self._channel_usb is False: self._state_attrs[ATTR_LOAD_POWER] = None async def async_turn_on(self, **kwargs): """Turn a channel on.""" if self._channel_usb: result = await self._try_command( "Turning the plug on failed.", self._plug.usb_on) else: result = await self._try_command( "Turning the plug on failed.", self._plug.on) if result: self._state = True self._skip_update = True async def async_turn_off(self, **kwargs): """Turn a channel off.""" if self._channel_usb: result = await self._try_command( "Turning the plug on failed.", self._plug.usb_off) else: result = await self._try_command( "Turning the plug on failed.", self._plug.off) if result: self._state = False self._skip_update = True async def async_update(self): """Fetch state from the device.""" from miio import DeviceException # On state change the device doesn't provide the new state immediately. if self._skip_update: self._skip_update = False return try: state = await self.hass.async_add_executor_job(self._plug.status) _LOGGER.debug("Got new state: %s", state) self._available = True if self._channel_usb: self._state = state.usb_power else: self._state = state.is_on self._state_attrs[ATTR_TEMPERATURE] = state.temperature if state.wifi_led: self._state_attrs[ATTR_WIFI_LED] = state.wifi_led if self._channel_usb is False and state.load_power: self._state_attrs[ATTR_LOAD_POWER] = state.load_power except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) class XiaomiAirConditioningCompanionSwitch(XiaomiPlugGenericSwitch): """Representation of a Xiaomi AirConditioning Companion.""" def __init__(self, name, plug, model, unique_id): """Initialize the acpartner switch.""" super().__init__(name, plug, model, unique_id) self._state_attrs.update({ ATTR_TEMPERATURE: None, ATTR_LOAD_POWER: None, }) async def async_turn_on(self, **kwargs): """Turn the socket on.""" result = await self._try_command( "Turning the socket on failed.", self._plug.socket_on) if result: self._state = True self._skip_update = True async def async_turn_off(self, **kwargs): """Turn the socket off.""" result = await self._try_command( "Turning the socket off failed.", self._plug.socket_off) if result: self._state = False self._skip_update = True async def async_update(self): """Fetch state from the device.""" from miio import DeviceException # On state change the device doesn't provide the new state immediately. if self._skip_update: self._skip_update = False return try: state = await self.hass.async_add_executor_job(self._plug.status) _LOGGER.debug("Got new state: %s", state) self._available = True self._state = state.power_socket == 'on' self._state_attrs[ATTR_LOAD_POWER] = state.load_power except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex)
33.723364
79
0.623046
import asyncio from functools import partial import logging import voluptuous as vol from homeassistant.components.switch import ( DOMAIN, PLATFORM_SCHEMA, SwitchDevice) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, CONF_NAME, CONF_TOKEN) from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Xiaomi Miio Switch' DATA_KEY = 'switch.xiaomi_miio' CONF_MODEL = 'model' MODEL_POWER_STRIP_V2 = 'zimi.powerstrip.v2' MODEL_PLUG_V3 = 'chuangmi.plug.v3' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_MODEL): vol.In( ['chuangmi.plug.v1', 'qmi.powerstrip.v1', 'zimi.powerstrip.v2', 'chuangmi.plug.m1', 'chuangmi.plug.m3', 'chuangmi.plug.v2', 'chuangmi.plug.v3', 'chuangmi.plug.hmi205', 'lumi.acpartner.v3', ]), }) ATTR_POWER = 'power' ATTR_TEMPERATURE = 'temperature' ATTR_LOAD_POWER = 'load_power' ATTR_MODEL = 'model' ATTR_MODE = 'mode' ATTR_POWER_MODE = 'power_mode' ATTR_WIFI_LED = 'wifi_led' ATTR_POWER_PRICE = 'power_price' ATTR_PRICE = 'price' SUCCESS = ['ok'] FEATURE_SET_POWER_MODE = 1 FEATURE_SET_WIFI_LED = 2 FEATURE_SET_POWER_PRICE = 4 FEATURE_FLAGS_GENERIC = 0 FEATURE_FLAGS_POWER_STRIP_V1 = (FEATURE_SET_POWER_MODE | FEATURE_SET_WIFI_LED | FEATURE_SET_POWER_PRICE) FEATURE_FLAGS_POWER_STRIP_V2 = (FEATURE_SET_WIFI_LED | FEATURE_SET_POWER_PRICE) FEATURE_FLAGS_PLUG_V3 = (FEATURE_SET_WIFI_LED) SERVICE_SET_WIFI_LED_ON = 'xiaomi_miio_set_wifi_led_on' SERVICE_SET_WIFI_LED_OFF = 'xiaomi_miio_set_wifi_led_off' SERVICE_SET_POWER_MODE = 'xiaomi_miio_set_power_mode' SERVICE_SET_POWER_PRICE = 'xiaomi_miio_set_power_price' SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, }) SERVICE_SCHEMA_POWER_MODE = SERVICE_SCHEMA.extend({ vol.Required(ATTR_MODE): vol.All(vol.In(['green', 'normal'])), }) SERVICE_SCHEMA_POWER_PRICE = SERVICE_SCHEMA.extend({ vol.Required(ATTR_PRICE): vol.All(vol.Coerce(float), vol.Range(min=0)) }) SERVICE_TO_METHOD = { SERVICE_SET_WIFI_LED_ON: {'method': 'async_set_wifi_led_on'}, SERVICE_SET_WIFI_LED_OFF: {'method': 'async_set_wifi_led_off'}, SERVICE_SET_POWER_MODE: { 'method': 'async_set_power_mode', 'schema': SERVICE_SCHEMA_POWER_MODE}, SERVICE_SET_POWER_PRICE: { 'method': 'async_set_power_price', 'schema': SERVICE_SCHEMA_POWER_PRICE}, } async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): from miio import Device, DeviceException if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} host = config.get(CONF_HOST) name = config.get(CONF_NAME) token = config.get(CONF_TOKEN) model = config.get(CONF_MODEL) _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) devices = [] unique_id = None if model is None: try: miio_device = Device(host, token) device_info = miio_device.info() model = device_info.model unique_id = "{}-{}".format(model, device_info.mac_address) _LOGGER.info("%s %s %s detected", model, device_info.firmware_version, device_info.hardware_version) except DeviceException: raise PlatformNotReady if model in ['chuangmi.plug.v1', 'chuangmi.plug.v3']: from miio import ChuangmiPlug plug = ChuangmiPlug(host, token, model=model) for channel_usb in [True, False]: device = ChuangMiPlugSwitch( name, plug, model, unique_id, channel_usb) devices.append(device) hass.data[DATA_KEY][host] = device elif model in ['qmi.powerstrip.v1', 'zimi.powerstrip.v2']: from miio import PowerStrip plug = PowerStrip(host, token, model=model) device = XiaomiPowerStripSwitch(name, plug, model, unique_id) devices.append(device) hass.data[DATA_KEY][host] = device elif model in ['chuangmi.plug.m1', 'chuangmi.plug.m3', 'chuangmi.plug.v2', 'chuangmi.plug.hmi205']: from miio import ChuangmiPlug plug = ChuangmiPlug(host, token, model=model) device = XiaomiPlugGenericSwitch(name, plug, model, unique_id) devices.append(device) hass.data[DATA_KEY][host] = device elif model in ['lumi.acpartner.v3']: from miio import AirConditioningCompanionV3 plug = AirConditioningCompanionV3(host, token) device = XiaomiAirConditioningCompanionSwitch(name, plug, model, unique_id) devices.append(device) hass.data[DATA_KEY][host] = device else: _LOGGER.error( 'Unsupported device found! Please create an issue at ' 'https://github.com/rytilahti/python-miio/issues ' 'and provide the following data: %s', model) return False async_add_entities(devices, update_before_add=True) async def async_service_handler(service): method = SERVICE_TO_METHOD.get(service.service) params = {key: value for key, value in service.data.items() if key != ATTR_ENTITY_ID} entity_ids = service.data.get(ATTR_ENTITY_ID) if entity_ids: devices = [device for device in hass.data[DATA_KEY].values() if device.entity_id in entity_ids] else: devices = hass.data[DATA_KEY].values() update_tasks = [] for device in devices: if not hasattr(device, method['method']): continue await getattr(device, method['method'])(**params) update_tasks.append(device.async_update_ha_state(True)) if update_tasks: await asyncio.wait(update_tasks) for plug_service in SERVICE_TO_METHOD: schema = SERVICE_TO_METHOD[plug_service].get('schema', SERVICE_SCHEMA) hass.services.async_register( DOMAIN, plug_service, async_service_handler, schema=schema) class XiaomiPlugGenericSwitch(SwitchDevice): def __init__(self, name, plug, model, unique_id): self._name = name self._plug = plug self._model = model self._unique_id = unique_id self._icon = 'mdi:power-socket' self._available = False self._state = None self._state_attrs = { ATTR_TEMPERATURE: None, ATTR_MODEL: self._model, } self._device_features = FEATURE_FLAGS_GENERIC self._skip_update = False @property def should_poll(self): return True @property def unique_id(self): return self._unique_id @property def name(self): return self._name @property def icon(self): return self._icon @property def available(self): return self._available @property def device_state_attributes(self): return self._state_attrs @property def is_on(self): return self._state async def _try_command(self, mask_error, func, *args, **kwargs): from miio import DeviceException try: result = await self.hass.async_add_executor_job( partial(func, *args, **kwargs)) _LOGGER.debug("Response received from plug: %s", result) if func in ['usb_on', 'usb_off'] and result == 0: return True return result == SUCCESS except DeviceException as exc: _LOGGER.error(mask_error, exc) self._available = False return False async def async_turn_on(self, **kwargs): result = await self._try_command( "Turning the plug on failed.", self._plug.on) if result: self._state = True self._skip_update = True async def async_turn_off(self, **kwargs): result = await self._try_command( "Turning the plug off failed.", self._plug.off) if result: self._state = False self._skip_update = True async def async_update(self): from miio import DeviceException if self._skip_update: self._skip_update = False return try: state = await self.hass.async_add_executor_job(self._plug.status) _LOGGER.debug("Got new state: %s", state) self._available = True self._state = state.is_on self._state_attrs[ATTR_TEMPERATURE] = state.temperature except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) async def async_set_wifi_led_on(self): if self._device_features & FEATURE_SET_WIFI_LED == 0: return await self._try_command( "Turning the wifi led on failed.", self._plug.set_wifi_led, True) async def async_set_wifi_led_off(self): if self._device_features & FEATURE_SET_WIFI_LED == 0: return await self._try_command( "Turning the wifi led off failed.", self._plug.set_wifi_led, False) async def async_set_power_price(self, price: int): if self._device_features & FEATURE_SET_POWER_PRICE == 0: return await self._try_command( "Setting the power price of the power strip failed.", self._plug.set_power_price, price) class XiaomiPowerStripSwitch(XiaomiPlugGenericSwitch): def __init__(self, name, plug, model, unique_id): super().__init__(name, plug, model, unique_id) if self._model == MODEL_POWER_STRIP_V2: self._device_features = FEATURE_FLAGS_POWER_STRIP_V2 else: self._device_features = FEATURE_FLAGS_POWER_STRIP_V1 self._state_attrs[ATTR_LOAD_POWER] = None if self._device_features & FEATURE_SET_POWER_MODE == 1: self._state_attrs[ATTR_POWER_MODE] = None if self._device_features & FEATURE_SET_WIFI_LED == 1: self._state_attrs[ATTR_WIFI_LED] = None if self._device_features & FEATURE_SET_POWER_PRICE == 1: self._state_attrs[ATTR_POWER_PRICE] = None async def async_update(self): from miio import DeviceException # On state change the device doesn't provide the new state immediately. if self._skip_update: self._skip_update = False return try: state = await self.hass.async_add_executor_job(self._plug.status) _LOGGER.debug("Got new state: %s", state) self._available = True self._state = state.is_on self._state_attrs.update({ ATTR_TEMPERATURE: state.temperature, ATTR_LOAD_POWER: state.load_power, }) if self._device_features & FEATURE_SET_POWER_MODE == 1 and \ state.mode: self._state_attrs[ATTR_POWER_MODE] = state.mode.value if self._device_features & FEATURE_SET_WIFI_LED == 1 and \ state.wifi_led: self._state_attrs[ATTR_WIFI_LED] = state.wifi_led if self._device_features & FEATURE_SET_POWER_PRICE == 1 and \ state.power_price: self._state_attrs[ATTR_POWER_PRICE] = state.power_price except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) async def async_set_power_mode(self, mode: str): if self._device_features & FEATURE_SET_POWER_MODE == 0: return from miio.powerstrip import PowerMode await self._try_command( "Setting the power mode of the power strip failed.", self._plug.set_power_mode, PowerMode(mode)) class ChuangMiPlugSwitch(XiaomiPlugGenericSwitch): def __init__(self, name, plug, model, unique_id, channel_usb): name = '{} USB'.format(name) if channel_usb else name if unique_id is not None and channel_usb: unique_id = "{}-{}".format(unique_id, 'usb') super().__init__(name, plug, model, unique_id) self._channel_usb = channel_usb if self._model == MODEL_PLUG_V3: self._device_features = FEATURE_FLAGS_PLUG_V3 self._state_attrs[ATTR_WIFI_LED] = None if self._channel_usb is False: self._state_attrs[ATTR_LOAD_POWER] = None async def async_turn_on(self, **kwargs): if self._channel_usb: result = await self._try_command( "Turning the plug on failed.", self._plug.usb_on) else: result = await self._try_command( "Turning the plug on failed.", self._plug.on) if result: self._state = True self._skip_update = True async def async_turn_off(self, **kwargs): if self._channel_usb: result = await self._try_command( "Turning the plug on failed.", self._plug.usb_off) else: result = await self._try_command( "Turning the plug on failed.", self._plug.off) if result: self._state = False self._skip_update = True async def async_update(self): from miio import DeviceException if self._skip_update: self._skip_update = False return try: state = await self.hass.async_add_executor_job(self._plug.status) _LOGGER.debug("Got new state: %s", state) self._available = True if self._channel_usb: self._state = state.usb_power else: self._state = state.is_on self._state_attrs[ATTR_TEMPERATURE] = state.temperature if state.wifi_led: self._state_attrs[ATTR_WIFI_LED] = state.wifi_led if self._channel_usb is False and state.load_power: self._state_attrs[ATTR_LOAD_POWER] = state.load_power except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex) class XiaomiAirConditioningCompanionSwitch(XiaomiPlugGenericSwitch): def __init__(self, name, plug, model, unique_id): super().__init__(name, plug, model, unique_id) self._state_attrs.update({ ATTR_TEMPERATURE: None, ATTR_LOAD_POWER: None, }) async def async_turn_on(self, **kwargs): result = await self._try_command( "Turning the socket on failed.", self._plug.socket_on) if result: self._state = True self._skip_update = True async def async_turn_off(self, **kwargs): result = await self._try_command( "Turning the socket off failed.", self._plug.socket_off) if result: self._state = False self._skip_update = True async def async_update(self): from miio import DeviceException # On state change the device doesn't provide the new state immediately. if self._skip_update: self._skip_update = False return try: state = await self.hass.async_add_executor_job(self._plug.status) _LOGGER.debug("Got new state: %s", state) self._available = True self._state = state.power_socket == 'on' self._state_attrs[ATTR_LOAD_POWER] = state.load_power except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex)
true
true
1c37540cc5870935640dc46567573fec3ea1c1e1
438
py
Python
anees/migrations/0032_auto_20200927_0511.py
ashish2020kashyap/cessini
9713fd76d2e31a95266ec69da2abc98424a46e52
[ "MIT" ]
null
null
null
anees/migrations/0032_auto_20200927_0511.py
ashish2020kashyap/cessini
9713fd76d2e31a95266ec69da2abc98424a46e52
[ "MIT" ]
null
null
null
anees/migrations/0032_auto_20200927_0511.py
ashish2020kashyap/cessini
9713fd76d2e31a95266ec69da2abc98424a46e52
[ "MIT" ]
null
null
null
# Generated by Django 3.1.1 on 2020-09-27 05:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('anees', '0031_auto_20200927_0401'), ] operations = [ migrations.RemoveField( model_name='campaign', name='mycustomer', ), migrations.RemoveField( model_name='email', name='mycampaign', ), ]
19.909091
47
0.56621
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('anees', '0031_auto_20200927_0401'), ] operations = [ migrations.RemoveField( model_name='campaign', name='mycustomer', ), migrations.RemoveField( model_name='email', name='mycampaign', ), ]
true
true
1c375696cd1d7fb1b8bc7e457af4d5fbd97e1a97
1,474
py
Python
.history/classes/Menu_20171107130940.py
reecebenson/DADSA-Tennis-PartA
d0763f819b300fcd0ce27041f5bc4ef0519c00bf
[ "MIT" ]
null
null
null
.history/classes/Menu_20171107130940.py
reecebenson/DADSA-Tennis-PartA
d0763f819b300fcd0ce27041f5bc4ef0519c00bf
[ "MIT" ]
null
null
null
.history/classes/Menu_20171107130940.py
reecebenson/DADSA-Tennis-PartA
d0763f819b300fcd0ce27041f5bc4ef0519c00bf
[ "MIT" ]
null
null
null
# DADSA - Assignment 1 # Reece Benson class Menu(): # Define the variables we will be using _app = None _menu = None _current_menu = [ 0 ] def __init__(self, app): # Set our Application self._app = app def load(self): # Define our Menu self.menu = { 'Item 1': { 'Sub Item 1': self.load_action, 'Sub Item 2': self.load_action }, 'Item 2': { 'Sub Item 1': self.load_action, 'Sub Item 2': self.load_action, 'Sub Item 3': self.load_action, 'Sub Item 4': self.load_action }, 'Item 3': self.load_action, 'Item 4': { 'Sub Item 1': { 'Sub Sub Item 1': self.load_action, 'Sub Sub Item 2': self.load_action } } } # Display our Menu self.display() def display(self): #TODO: Display the current Menu self.get_current_menu() def get_current_menu(self): # Retrieve our current index [x, y, z] index = self._current_menu # ITS FUCKEEEEEEEEEEEEEED print(self.menu[index]) def get_input(self): #TODO: Get user's input from defined menu print("Get Input") def load_action(self, menu_id): #TODO: Load Action from Menu_ID print("Load Action")
24.983051
55
0.495251
class Menu(): _app = None _menu = None _current_menu = [ 0 ] def __init__(self, app): self._app = app def load(self): self.menu = { 'Item 1': { 'Sub Item 1': self.load_action, 'Sub Item 2': self.load_action }, 'Item 2': { 'Sub Item 1': self.load_action, 'Sub Item 2': self.load_action, 'Sub Item 3': self.load_action, 'Sub Item 4': self.load_action }, 'Item 3': self.load_action, 'Item 4': { 'Sub Item 1': { 'Sub Sub Item 1': self.load_action, 'Sub Sub Item 2': self.load_action } } } self.display() def display(self): self.get_current_menu() def get_current_menu(self): index = self._current_menu print(self.menu[index]) def get_input(self): print("Get Input") def load_action(self, menu_id): #TODO: Load Action from Menu_ID print("Load Action")
true
true