code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
import functools from .abi import ( # noqa: F401 abi_middleware, ) from .attrdict import ( # noqa: F401 attrdict_middleware, ) from .cache import ( # noqa: F401 construct_simple_cache_middleware, construct_time_based_cache_middleware, construct_latest_block_based_cache_middleware, _simple_cache_middleware as simple_cache_middleware, _time_based_cache_middleware as time_based_cache_middleware, _latest_block_based_cache_middleware as latest_block_based_cache_middleware, ) from .exception_handling import ( # noqa: F401 construct_exception_handler_middleware, ) from .filter import ( # noqa: F401 local_filter_middleware, ) from .fixture import ( # noqa: F401 construct_fixture_middleware, construct_result_generator_middleware, construct_error_generator_middleware, ) from .formatting import ( # noqa: F401 construct_formatting_middleware, ) from .gas_price_strategy import ( # noqa: F401 gas_price_strategy_middleware, ) from .names import ( # noqa: F401 name_to_address_middleware, ) from .normalize_errors import ( # noqa: F401 normalize_errors_middleware, ) from .normalize_request_parameters import ( # noqa: F401 request_parameter_normalizer, ) from .pythonic import ( # noqa: F401 pythonic_middleware, ) from .stalecheck import ( # noqa: F401 make_stalecheck_middleware, ) from .exception_retry_request import ( # noqa: F401 http_retry_request_middleware ) from .geth_poa import ( # noqa: F401 geth_poa_middleware, ) from .validation import ( # noqa: F401 validation_middleware, ) from .signing import ( # noqa: F401 construct_sign_and_send_raw_middleware, ) def combine_middlewares(middlewares, web3, provider_request_fn): """ Returns a callable function which will call the provider.provider_request function wrapped with all of the middlewares. """ return functools.reduce( lambda request_fn, middleware: middleware(request_fn, web3), reversed(middlewares), provider_request_fn, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/__init__.py
__init__.py
from web3._utils.toolz import ( assoc, ) def gas_price_strategy_middleware(make_request, web3): """ Includes a gas price using the gas price strategy """ def middleware(method, params): if method == 'eth_sendTransaction': transaction = params[0] if 'gasPrice' not in transaction: generated_gas_price = web3.eth.generateGasPrice(transaction) if generated_gas_price is not None: transaction = assoc(transaction, 'gasPrice', generated_gas_price) return make_request(method, [transaction]) return make_request(method, params) return middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/gas_price_strategy.py
gas_price_strategy.py
from requests.exceptions import ( ConnectionError, HTTPError, Timeout, TooManyRedirects, ) whitelist = [ 'admin', 'shh', 'miner', 'net', 'txpool' 'testing', 'evm', 'eth_protocolVersion', 'eth_syncing', 'eth_coinbase', 'eth_mining', 'eth_hashrate', 'eth_gasPrice', 'eth_accounts', 'eth_blockNumber', 'eth_getBalance', 'eth_getStorageAt', 'eth_getCode', 'eth_getBlockByNumber', 'eth_getBlockByHash', 'eth_getBlockTransactionCountByNumber', 'eth_getBlockTransactionCountByHash', 'eth_getUncleCountByBlockNumber', 'eth_getUncleCountByBlockHash', 'eth_getTransactionByHash', 'eth_getTransactionByBlockHashAndIndex', 'eth_getTransactionByBlockNumberAndIndex', 'eth_getTransactionReceipt', 'eth_getTransactionCount', 'eth_call', 'eth_estimateGas', 'eth_newBlockFilter', 'eth_newPendingTransactionFilter', 'eth_newFilter', 'eth_getFilterChanges', 'eth_getFilterLogs', 'eth_getLogs', 'eth_uninstallFilter', 'eth_getCompilers', 'eth_getWork', 'eth_sign', 'eth_sendRawTransaction', 'personal_importRawKey', 'personal_newAccount', 'personal_listAccounts', 'personal_lockAccount', 'personal_unlockAccount', 'personal_ecRecover', 'personal_sign' ] def check_if_retry_on_failure(method): root = method.split('_')[0] if root in whitelist: return True elif method in whitelist: return True else: return False def exception_retry_middleware(make_request, web3, errors, retries=5): """ Creates middleware that retries failed HTTP requests. Is a default middleware for HTTPProvider. """ def middleware(method, params): if check_if_retry_on_failure(method): for i in range(retries): try: return make_request(method, params) except errors: if i < retries - 1: continue else: raise else: return make_request(method, params) return middleware def http_retry_request_middleware(make_request, web3): return exception_retry_middleware( make_request, web3, (ConnectionError, HTTPError, Timeout, TooManyRedirects) )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/exception_retry_request.py
exception_retry_request.py
from functools import ( singledispatch, ) import operator from eth_account import ( Account, ) from eth_account.local import ( LocalAccount, ) from eth_keys.datatypes import ( PrivateKey, ) from eth_utils import ( to_dict, ) from web3._utils.formatters import ( apply_formatter_if, ) from web3._utils.rpc_abi import ( TRANSACTION_PARAMS_ABIS, apply_abi_formatters_to_dict, ) from web3._utils.toolz import ( compose, ) from web3._utils.transactions import ( fill_nonce, fill_transaction_defaults, ) from .abi import ( STANDARD_NORMALIZERS, ) to_hexstr_from_eth_key = operator.methodcaller('to_hex') def is_eth_key(value): return isinstance(value, PrivateKey) key_normalizer = compose( apply_formatter_if(is_eth_key, to_hexstr_from_eth_key), ) @to_dict def gen_normalized_accounts(val): if isinstance(val, (list, tuple, set,)): for i in val: account = to_account(i) yield account.address, account else: account = to_account(val) yield account.address, account return @singledispatch def to_account(val): raise TypeError( "key must be one of the types: " "eth_keys.datatype.PrivateKey, eth_account.local.LocalAccount, " "or raw private key as a hex string or byte string. " "Was of type {0}".format(type(val))) @to_account.register(LocalAccount) def _(val): return val def private_key_to_account(val): normalized_key = key_normalizer(val) return Account.privateKeyToAccount(normalized_key) to_account.register(PrivateKey, private_key_to_account) to_account.register(str, private_key_to_account) to_account.register(bytes, private_key_to_account) def format_transaction(transaction): """Format transaction so that it can be used correctly in the signing middleware. Converts bytes to hex strings and other types that can be passed to the underlying layers. Also has the effect of normalizing 'from' for easier comparisons. """ return apply_abi_formatters_to_dict(STANDARD_NORMALIZERS, TRANSACTION_PARAMS_ABIS, transaction) def construct_sign_and_send_raw_middleware(private_key_or_account): """Capture transactions sign and send as raw transactions Keyword arguments: private_key_or_account -- A single private key or a tuple, list or set of private keys. Keys can be any of the following formats: - An eth_account.LocalAccount object - An eth_keys.PrivateKey object - A raw private key as a hex string or byte string """ accounts = gen_normalized_accounts(private_key_or_account) def sign_and_send_raw_middleware(make_request, w3): format_and_fill_tx = compose( format_transaction, fill_transaction_defaults(w3), fill_nonce(w3)) def middleware(method, params): if method != "eth_sendTransaction": return make_request(method, params) else: transaction = format_and_fill_tx(params[0]) if 'from' not in transaction: return make_request(method, params) elif transaction.get('from') not in accounts: return make_request(method, params) account = accounts[transaction['from']] raw_tx = account.signTransaction(transaction).rawTransaction return make_request( "eth_sendRawTransaction", [raw_tx]) return middleware return sign_and_send_raw_middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/middleware/signing.py
signing.py
import logging import os from eth_utils import ( to_dict, ) from web3._utils.http import ( construct_user_agent, ) from web3._utils.request import ( make_post_request, ) from web3.datastructures import ( NamedElementOnion, ) from web3.middleware import ( http_retry_request_middleware, ) from .base import ( JSONBaseProvider, ) def get_default_endpoint(): return os.environ.get('WEB3_HTTP_PROVIDER_URI', 'http://localhost:8545') class HTTPProvider(JSONBaseProvider): logger = logging.getLogger("web3.providers.HTTPProvider") endpoint_uri = None _request_args = None _request_kwargs = None _middlewares = NamedElementOnion([(http_retry_request_middleware, 'http_retry_request')]) def __init__(self, endpoint_uri=None, request_kwargs=None): if endpoint_uri is None: self.endpoint_uri = get_default_endpoint() else: self.endpoint_uri = endpoint_uri self._request_kwargs = request_kwargs or {} super().__init__() def __str__(self): return "RPC connection {0}".format(self.endpoint_uri) @to_dict def get_request_kwargs(self): if 'headers' not in self._request_kwargs: yield 'headers', self.get_request_headers() for key, value in self._request_kwargs.items(): yield key, value def get_request_headers(self): return { 'Content-Type': 'application/json', 'User-Agent': construct_user_agent(str(type(self))), } def make_request(self, method, params): self.logger.debug("Making request HTTP. URI: %s, Method: %s", self.endpoint_uri, method) request_data = self.encode_rpc_request(method, params) raw_response = make_post_request( self.endpoint_uri, request_data, **self.get_request_kwargs() ) response = self.decode_rpc_response(raw_response) self.logger.debug("Getting response HTTP. URI: %s, " "Method: %s, Response: %s", self.endpoint_uri, method, response) return response
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/rpc.py
rpc.py
import itertools from eth_utils import ( to_bytes, to_text, ) from web3._utils.encoding import ( FriendlyJsonSerde, ) from web3.middleware import ( combine_middlewares, ) class BaseProvider: _middlewares = () _request_func_cache = (None, None) # a tuple of (all_middlewares, request_func) @property def middlewares(self): return self._middlewares @middlewares.setter def middlewares(self, values): self._middlewares = tuple(values) def request_func(self, web3, outer_middlewares): """ @param outer_middlewares is an iterable of middlewares, ordered by first to execute @returns a function that calls all the middleware and eventually self.make_request() """ all_middlewares = tuple(outer_middlewares) + tuple(self.middlewares) cache_key = self._request_func_cache[0] if cache_key is None or cache_key != all_middlewares: self._request_func_cache = ( all_middlewares, self._generate_request_func(web3, all_middlewares) ) return self._request_func_cache[-1] def _generate_request_func(self, web3, middlewares): return combine_middlewares( middlewares=middlewares, web3=web3, provider_request_fn=self.make_request, ) def make_request(self, method, params): raise NotImplementedError("Providers must implement this method") def isConnected(self): raise NotImplementedError("Providers must implement this method") class JSONBaseProvider(BaseProvider): def __init__(self): self.request_counter = itertools.count() def decode_rpc_response(self, response): text_response = to_text(response) return FriendlyJsonSerde().json_decode(text_response) def encode_rpc_request(self, method, params): rpc_dict = { "jsonrpc": "2.0", "method": method, "params": params or [], "id": next(self.request_counter), } encoded = FriendlyJsonSerde().json_encode(rpc_dict) return to_bytes(text=encoded) def isConnected(self): try: response = self.make_request('web3_clientVersion', []) except IOError: return False assert response['jsonrpc'] == '2.0' assert 'error' not in response return True
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/base.py
base.py
import asyncio import json import logging import os from threading import ( Thread, ) import websockets from web3.exceptions import ( ValidationError, ) from web3.providers.base import ( JSONBaseProvider, ) RESTRICTED_WEBSOCKET_KWARGS = {'uri', 'loop'} DEFAULT_WEBSOCKET_TIMEOUT = 10 def _start_event_loop(loop): asyncio.set_event_loop(loop) loop.run_forever() loop.close() def _get_threaded_loop(): new_loop = asyncio.new_event_loop() thread_loop = Thread(target=_start_event_loop, args=(new_loop,), daemon=True) thread_loop.start() return new_loop def get_default_endpoint(): return os.environ.get('WEB3_WS_PROVIDER_URI', 'ws://127.0.0.1:8546') class PersistentWebSocket: def __init__(self, endpoint_uri, loop, websocket_kwargs): self.ws = None self.endpoint_uri = endpoint_uri self.loop = loop self.websocket_kwargs = websocket_kwargs async def __aenter__(self): if self.ws is None: self.ws = await websockets.connect( uri=self.endpoint_uri, loop=self.loop, **self.websocket_kwargs ) return self.ws async def __aexit__(self, exc_type, exc_val, exc_tb): if exc_val is not None: try: await self.ws.close() except Exception: pass self.ws = None class WebsocketProvider(JSONBaseProvider): logger = logging.getLogger("web3.providers.WebsocketProvider") _loop = None def __init__( self, endpoint_uri=None, websocket_kwargs=None, websocket_timeout=DEFAULT_WEBSOCKET_TIMEOUT ): self.endpoint_uri = endpoint_uri self.websocket_timeout = websocket_timeout if self.endpoint_uri is None: self.endpoint_uri = get_default_endpoint() if WebsocketProvider._loop is None: WebsocketProvider._loop = _get_threaded_loop() if websocket_kwargs is None: websocket_kwargs = {} else: found_restricted_keys = set(websocket_kwargs.keys()).intersection( RESTRICTED_WEBSOCKET_KWARGS ) if found_restricted_keys: raise ValidationError( '{0} are not allowed in websocket_kwargs, ' 'found: {1}'.format(RESTRICTED_WEBSOCKET_KWARGS, found_restricted_keys) ) self.conn = PersistentWebSocket( self.endpoint_uri, WebsocketProvider._loop, websocket_kwargs ) super().__init__() def __str__(self): return "WS connection {0}".format(self.endpoint_uri) async def coro_make_request(self, request_data): async with self.conn as conn: await asyncio.wait_for( conn.send(request_data), timeout=self.websocket_timeout ) return json.loads( await asyncio.wait_for( conn.recv(), timeout=self.websocket_timeout ) ) def make_request(self, method, params): self.logger.debug("Making request WebSocket. URI: %s, " "Method: %s", self.endpoint_uri, method) request_data = self.encode_rpc_request(method, params) future = asyncio.run_coroutine_threadsafe( self.coro_make_request(request_data), WebsocketProvider._loop ) return future.result()
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/websocket.py
websocket.py
import os from urllib.parse import ( urlparse, ) from web3.exceptions import ( CannotHandleRequest, ) from web3.providers import ( BaseProvider, HTTPProvider, IPCProvider, WebsocketProvider, ) HTTP_SCHEMES = {'http', 'https'} WS_SCHEMES = {'ws', 'wss'} def load_provider_from_environment(): uri_string = os.environ.get('WEB3_PROVIDER_URI', '') if not uri_string: return None return load_provider_from_uri(uri_string) def load_provider_from_uri(uri_string): uri = urlparse(uri_string) if uri.scheme == 'file': return IPCProvider(uri.path) elif uri.scheme in HTTP_SCHEMES: return HTTPProvider(uri_string) elif uri.scheme in WS_SCHEMES: return WebsocketProvider(uri_string) else: raise NotImplementedError( 'Web3 does not know how to connect to scheme %r in %r' % ( uri.scheme, uri_string, ) ) class AutoProvider(BaseProvider): default_providers = ( load_provider_from_environment, IPCProvider, HTTPProvider, WebsocketProvider, ) _active_provider = None def __init__(self, potential_providers=None): """ :param iterable potential_providers: ordered series of provider classes to attempt with AutoProvider will initialize each potential provider (without arguments), in an attempt to find an active node. The list will default to :attribute:`default_providers`. """ if potential_providers: self._potential_providers = potential_providers else: self._potential_providers = self.default_providers def make_request(self, method, params): try: return self._proxy_request(method, params) except IOError as exc: return self._proxy_request(method, params, use_cache=False) def isConnected(self): provider = self._get_active_provider(use_cache=True) return provider is not None and provider.isConnected() def _proxy_request(self, method, params, use_cache=True): provider = self._get_active_provider(use_cache) if provider is None: raise CannotHandleRequest( "Could not discover provider while making request: " "method:{0}\n" "params:{1}\n".format( method, params)) return provider.make_request(method, params) def _get_active_provider(self, use_cache): if use_cache and self._active_provider is not None: return self._active_provider for Provider in self._potential_providers: provider = Provider() if provider is not None and provider.isConnected(): self._active_provider = provider return provider return None
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/auto.py
auto.py
from .base import ( # noqa: F401 BaseProvider, JSONBaseProvider, ) from .rpc import HTTPProvider # noqa: F401 from .ipc import IPCProvider # noqa: F401 from .websocket import WebsocketProvider # noqa: F401 from .auto import AutoProvider # noqa: F401
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/__init__.py
__init__.py
import logging import os from pathlib import ( Path, ) import socket import sys import threading from web3._utils.threads import ( Timeout, ) from .base import ( JSONBaseProvider, ) try: from json import JSONDecodeError except ImportError: JSONDecodeError = ValueError def get_ipc_socket(ipc_path, timeout=0.1): if sys.platform == 'win32': # On Windows named pipe is used. Simulate socket with it. from web3._utils.windows import NamedPipe return NamedPipe(ipc_path) else: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(ipc_path) sock.settimeout(timeout) return sock class PersistantSocket: sock = None def __init__(self, ipc_path): self.ipc_path = ipc_path def __enter__(self): if not self.ipc_path: raise FileNotFoundError("cannot connect to IPC socket at path: %r" % self.ipc_path) if not self.sock: self.sock = self._open() return self.sock def __exit__(self, exc_type, exc_value, traceback): # only close the socket if there was an error if exc_value is not None: try: self.sock.close() except Exception: pass self.sock = None def _open(self): return get_ipc_socket(self.ipc_path) def reset(self): self.sock.close() self.sock = self._open() return self.sock def get_default_ipc_path(): if sys.platform == 'darwin': ipc_path = os.path.expanduser(os.path.join( "~", "Library", "Ethereum", "geth.ipc" )) if os.path.exists(ipc_path): return ipc_path ipc_path = os.path.expanduser(os.path.join( "~", "Library", "Application Support", "io.parity.ethereum", "jsonrpc.ipc" )) if os.path.exists(ipc_path): return ipc_path base_trinity_path = Path('~').expanduser() / '.local' / 'share' / 'trinity' ipc_path = base_trinity_path / 'mainnet' / 'jsonrpc.ipc' if ipc_path.exists(): return str(ipc_path) elif sys.platform.startswith('linux') or sys.platform.startswith('freebsd'): ipc_path = os.path.expanduser(os.path.join( "~", ".ethereum", "geth.ipc" )) if os.path.exists(ipc_path): return ipc_path ipc_path = os.path.expanduser(os.path.join( "~", ".local", "share", "io.parity.ethereum", "jsonrpc.ipc" )) if os.path.exists(ipc_path): return ipc_path base_trinity_path = Path('~').expanduser() / '.local' / 'share' / 'trinity' ipc_path = base_trinity_path / 'mainnet' / 'jsonrpc.ipc' if ipc_path.exists(): return str(ipc_path) elif sys.platform == 'win32': ipc_path = os.path.join( "\\\\", ".", "pipe", "geth.ipc" ) if os.path.exists(ipc_path): return ipc_path ipc_path = os.path.join( "\\\\", ".", "pipe", "jsonrpc.ipc" ) if os.path.exists(ipc_path): return ipc_path else: raise ValueError( "Unsupported platform '{0}'. Only darwin/linux/win32/freebsd are " "supported. You must specify the ipc_path".format(sys.platform) ) def get_dev_ipc_path(): if sys.platform == 'darwin': tmpdir = os.environ.get('TMPDIR', '') ipc_path = os.path.expanduser(os.path.join( tmpdir, "geth.ipc" )) if os.path.exists(ipc_path): return ipc_path elif sys.platform.startswith('linux') or sys.platform.startswith('freebsd'): ipc_path = os.path.expanduser(os.path.join( "/tmp", "geth.ipc" )) if os.path.exists(ipc_path): return ipc_path elif sys.platform == 'win32': ipc_path = os.path.join( "\\\\", ".", "pipe", "geth.ipc" ) if os.path.exists(ipc_path): return ipc_path ipc_path = os.path.join( "\\\\", ".", "pipe", "jsonrpc.ipc" ) if os.path.exists(ipc_path): return ipc_path else: raise ValueError( "Unsupported platform '{0}'. Only darwin/linux/win32/freebsd are " "supported. You must specify the ipc_path".format(sys.platform) ) class IPCProvider(JSONBaseProvider): logger = logging.getLogger("web3.providers.IPCProvider") _socket = None def __init__(self, ipc_path=None, timeout=10, *args, **kwargs): if ipc_path is None: self.ipc_path = get_default_ipc_path() else: if isinstance(ipc_path, Path): ipc_path = str(ipc_path.resolve()) self.ipc_path = ipc_path self.timeout = timeout self._lock = threading.Lock() self._socket = PersistantSocket(self.ipc_path) super().__init__(*args, **kwargs) def make_request(self, method, params): self.logger.debug("Making request IPC. Path: %s, Method: %s", self.ipc_path, method) request = self.encode_rpc_request(method, params) with self._lock, self._socket as sock: try: sock.sendall(request) except BrokenPipeError: # one extra attempt, then give up sock = self._socket.reset() sock.sendall(request) raw_response = b"" with Timeout(self.timeout) as timeout: while True: try: raw_response += sock.recv(4096) except socket.timeout: timeout.sleep(0) continue if raw_response == b"": timeout.sleep(0) elif has_valid_json_rpc_ending(raw_response): try: response = self.decode_rpc_response(raw_response) except JSONDecodeError: timeout.sleep(0) continue else: return response else: timeout.sleep(0) continue # A valid JSON RPC response can only end in } or ] http://www.jsonrpc.org/specification def has_valid_json_rpc_ending(raw_response): stripped_raw_response = raw_response.rstrip() for valid_ending in [b"}", b"]"]: if stripped_raw_response.endswith(valid_ending): return True else: return False
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/ipc.py
ipc.py
import operator from eth_utils import ( is_dict, is_hex, is_string, ) from web3._utils.formatters import ( apply_formatter_if, apply_formatter_to_array, apply_formatters_to_args, apply_formatters_to_dict, apply_key_map, hex_to_integer, integer_to_hex, is_array_of_dicts, remove_key_if, static_return, ) from web3._utils.toolz import ( assoc, complement, compose, curry, identity, partial, pipe, ) from web3.middleware import ( construct_formatting_middleware, ) def is_named_block(value): return value in {"latest", "earliest", "pending"} def is_hexstr(value): return is_string(value) and is_hex(value) to_integer_if_hex = apply_formatter_if(is_hexstr, hex_to_integer) is_not_named_block = complement(is_named_block) TRANSACTION_KEY_MAPPINGS = { 'block_hash': 'blockHash', 'block_number': 'blockNumber', 'gas_price': 'gasPrice', 'transaction_hash': 'transactionHash', 'transaction_index': 'transactionIndex', } transaction_key_remapper = apply_key_map(TRANSACTION_KEY_MAPPINGS) LOG_KEY_MAPPINGS = { 'log_index': 'logIndex', 'transaction_index': 'transactionIndex', 'transaction_hash': 'transactionHash', 'block_hash': 'blockHash', 'block_number': 'blockNumber', } log_key_remapper = apply_key_map(LOG_KEY_MAPPINGS) RECEIPT_KEY_MAPPINGS = { 'block_hash': 'blockHash', 'block_number': 'blockNumber', 'contract_address': 'contractAddress', 'gas_used': 'gasUsed', 'cumulative_gas_used': 'cumulativeGasUsed', 'transaction_hash': 'transactionHash', 'transaction_index': 'transactionIndex', } receipt_key_remapper = apply_key_map(RECEIPT_KEY_MAPPINGS) BLOCK_KEY_MAPPINGS = { 'gas_limit': 'gasLimit', 'sha3_uncles': 'sha3Uncles', 'transactions_root': 'transactionsRoot', 'parent_hash': 'parentHash', 'bloom': 'logsBloom', 'state_root': 'stateRoot', 'receipt_root': 'receiptsRoot', 'total_difficulty': 'totalDifficulty', 'extra_data': 'extraData', 'gas_used': 'gasUsed', } block_key_remapper = apply_key_map(BLOCK_KEY_MAPPINGS) TRANSACTION_PARAMS_MAPPING = { 'gasPrice': 'gas_price', } transaction_params_remapper = apply_key_map(TRANSACTION_PARAMS_MAPPING) TRANSACTION_PARAMS_FORMATTERS = { 'gas': to_integer_if_hex, 'gasPrice': to_integer_if_hex, 'value': to_integer_if_hex, 'nonce': to_integer_if_hex, } transaction_params_formatter = compose( # remove nonce for now due to issue https://github.com/ethereum/eth-tester/issues/80 remove_key_if('nonce', lambda _: True), apply_formatters_to_dict(TRANSACTION_PARAMS_FORMATTERS), ) FILTER_PARAMS_MAPPINGS = { 'fromBlock': 'from_block', 'toBlock': 'to_block', } filter_params_remapper = apply_key_map(FILTER_PARAMS_MAPPINGS) FILTER_PARAMS_FORMATTERS = { 'fromBlock': to_integer_if_hex, 'toBlock': to_integer_if_hex, } filter_params_formatter = apply_formatters_to_dict(FILTER_PARAMS_FORMATTERS) filter_params_transformer = compose(filter_params_remapper, filter_params_formatter) TRANSACTION_FORMATTERS = { 'to': apply_formatter_if(partial(operator.eq, ''), static_return(None)), } transaction_formatter = apply_formatters_to_dict(TRANSACTION_FORMATTERS) RECEIPT_FORMATTERS = { 'logs': apply_formatter_to_array(log_key_remapper), } receipt_formatter = apply_formatters_to_dict(RECEIPT_FORMATTERS) transaction_params_transformer = compose(transaction_params_remapper, transaction_params_formatter) ethereum_tester_middleware = construct_formatting_middleware( request_formatters={ # Eth 'eth_getBlockByNumber': apply_formatters_to_args( apply_formatter_if(is_not_named_block, to_integer_if_hex), ), 'eth_getFilterChanges': apply_formatters_to_args(hex_to_integer), 'eth_getFilterLogs': apply_formatters_to_args(hex_to_integer), 'eth_getBlockTransactionCountByNumber': apply_formatters_to_args( apply_formatter_if(is_not_named_block, to_integer_if_hex), ), 'eth_getUncleCountByBlockNumber': apply_formatters_to_args( apply_formatter_if(is_not_named_block, to_integer_if_hex), ), 'eth_getTransactionByBlockHashAndIndex': apply_formatters_to_args( identity, to_integer_if_hex, ), 'eth_getTransactionByBlockNumberAndIndex': apply_formatters_to_args( apply_formatter_if(is_not_named_block, to_integer_if_hex), to_integer_if_hex, ), 'eth_getUncleByBlockNumberAndIndex': apply_formatters_to_args( apply_formatter_if(is_not_named_block, to_integer_if_hex), to_integer_if_hex, ), 'eth_newFilter': apply_formatters_to_args( filter_params_transformer, ), 'eth_getLogs': apply_formatters_to_args( filter_params_transformer, ), 'eth_sendTransaction': apply_formatters_to_args( transaction_params_transformer, ), 'eth_estimateGas': apply_formatters_to_args( transaction_params_transformer, ), 'eth_call': apply_formatters_to_args( transaction_params_transformer, apply_formatter_if(is_not_named_block, to_integer_if_hex), ), 'eth_uninstallFilter': apply_formatters_to_args(hex_to_integer), 'eth_getCode': apply_formatters_to_args( identity, apply_formatter_if(is_not_named_block, to_integer_if_hex), ), # EVM 'evm_revert': apply_formatters_to_args(hex_to_integer), # Personal 'personal_sendTransaction': apply_formatters_to_args( transaction_params_transformer, identity, ), }, result_formatters={ 'eth_getBlockByHash': apply_formatter_if( is_dict, block_key_remapper, ), 'eth_getBlockByNumber': apply_formatter_if( is_dict, block_key_remapper, ), 'eth_getBlockTransactionCountByHash': apply_formatter_if( is_dict, transaction_key_remapper, ), 'eth_getBlockTransactionCountByNumber': apply_formatter_if( is_dict, transaction_key_remapper, ), 'eth_getTransactionByHash': apply_formatter_if( is_dict, compose(transaction_key_remapper, transaction_formatter), ), 'eth_getTransactionReceipt': apply_formatter_if( is_dict, compose(receipt_key_remapper, receipt_formatter), ), 'eth_newFilter': integer_to_hex, 'eth_newBlockFilter': integer_to_hex, 'eth_newPendingTransactionFilter': integer_to_hex, 'eth_getLogs': apply_formatter_if( is_array_of_dicts, apply_formatter_to_array(log_key_remapper), ), 'eth_getFilterChanges': apply_formatter_if( is_array_of_dicts, apply_formatter_to_array(log_key_remapper), ), 'eth_getFilterLogs': apply_formatter_if( is_array_of_dicts, apply_formatter_to_array(log_key_remapper), ), # EVM 'evm_snapshot': integer_to_hex, }, ) def guess_from(web3, transaction): coinbase = web3.eth.coinbase if coinbase is not None: return coinbase try: return web3.eth.accounts[0] except KeyError as e: # no accounts available to pre-fill, carry on pass return None def guess_gas(web3, transaction): return web3.eth.estimateGas(transaction) * 2 @curry def fill_default(field, guess_func, web3, transaction): if field in transaction and transaction[field] is not None: return transaction else: guess_val = guess_func(web3, transaction) return assoc(transaction, field, guess_val) def default_transaction_fields_middleware(make_request, web3): fill_default_from = fill_default('from', guess_from, web3) fill_default_gas = fill_default('gas', guess_gas, web3) def middleware(method, params): # TODO send call to eth-tester without gas, and remove guess_gas entirely if method == 'eth_call': filled_transaction = pipe( params[0], fill_default_from, fill_default_gas, ) return make_request(method, [filled_transaction] + params[1:]) elif method in ( 'eth_estimateGas', 'eth_sendTransaction', ): filled_transaction = pipe( params[0], fill_default_from, ) return make_request(method, [filled_transaction] + params[1:]) else: return make_request(method, params) return middleware
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/eth_tester/middleware.py
middleware.py
import operator import random import sys from eth_tester.exceptions import ( BlockNotFound, FilterNotFound, TransactionNotFound, ValidationError, ) from eth_utils import ( decode_hex, encode_hex, is_null, keccak, ) from web3._utils.formatters import ( apply_formatter_if, ) from web3._utils.toolz import ( compose, curry, excepts, ) def not_implemented(*args, **kwargs): raise NotImplementedError("RPC method not implemented") @curry def call_eth_tester(fn_name, eth_tester, fn_args, fn_kwargs=None): if fn_kwargs is None: fn_kwargs = {} return getattr(eth_tester, fn_name)(*fn_args, **fn_kwargs) def without_eth_tester(fn): # workaround for: https://github.com/pytoolz/cytoolz/issues/103 # @functools.wraps(fn) def inner(eth_tester, params): return fn(params) return inner def without_params(fn): # workaround for: https://github.com/pytoolz/cytoolz/issues/103 # @functools.wraps(fn) def inner(eth_tester, params): return fn(eth_tester) return inner @curry def preprocess_params(eth_tester, params, preprocessor_fn): return eth_tester, preprocessor_fn(params) def static_return(value): def inner(*args, **kwargs): return value return inner def client_version(eth_tester, params): # TODO: account for the backend that is in use. from eth_tester import __version__ return "EthereumTester/{version}/{platform}/python{v.major}.{v.minor}.{v.micro}".format( version=__version__, v=sys.version_info, platform=sys.platform, ) @curry def null_if_excepts(exc_type, fn): return excepts( exc_type, fn, static_return(None), ) null_if_block_not_found = null_if_excepts(BlockNotFound) null_if_transaction_not_found = null_if_excepts(TransactionNotFound) null_if_filter_not_found = null_if_excepts(FilterNotFound) null_if_indexerror = null_if_excepts(IndexError) @null_if_indexerror @null_if_block_not_found def get_transaction_by_block_hash_and_index(eth_tester, params): block_hash, transaction_index = params block = eth_tester.get_block_by_hash(block_hash, full_transactions=True) transaction = block['transactions'][transaction_index] return transaction @null_if_indexerror @null_if_block_not_found def get_transaction_by_block_number_and_index(eth_tester, params): block_number, transaction_index = params block = eth_tester.get_block_by_number(block_number, full_transactions=True) transaction = block['transactions'][transaction_index] return transaction def create_log_filter(eth_tester, params): filter_params = params[0] filter_id = eth_tester.create_log_filter(**filter_params) return filter_id def get_logs(eth_tester, params): filter_params = params[0] logs = eth_tester.get_logs(**filter_params) return logs def _generate_random_private_key(): """ WARNING: This is not a secure way to generate private keys and should only be used for testing purposes. """ return encode_hex(bytes(bytearray(( random.randint(0, 255) for _ in range(32) )))) @without_params def create_new_account(eth_tester): return eth_tester.add_account(_generate_random_private_key()) def personal_send_transaction(eth_tester, params): transaction, password = params try: eth_tester.unlock_account(transaction['from'], password) transaction_hash = eth_tester.send_transaction(transaction) finally: eth_tester.lock_account(transaction['from']) return transaction_hash API_ENDPOINTS = { 'web3': { 'clientVersion': client_version, 'sha3': compose( encode_hex, keccak, decode_hex, without_eth_tester(operator.itemgetter(0)), ), }, 'net': { 'version': static_return('1'), 'peerCount': static_return(0), 'listening': static_return(False), }, 'eth': { 'protocolVersion': static_return('63'), 'syncing': static_return(False), 'coinbase': compose( operator.itemgetter(0), call_eth_tester('get_accounts'), ), 'mining': static_return(False), 'hashrate': static_return(0), 'gasPrice': static_return(1), 'accounts': call_eth_tester('get_accounts'), 'blockNumber': compose( operator.itemgetter('number'), call_eth_tester('get_block_by_number', fn_kwargs={'block_number': 'latest'}), ), 'getBalance': call_eth_tester('get_balance'), 'getStorageAt': not_implemented, 'getTransactionCount': call_eth_tester('get_nonce'), 'getBlockTransactionCountByHash': null_if_block_not_found(compose( len, operator.itemgetter('transactions'), call_eth_tester('get_block_by_hash'), )), 'getBlockTransactionCountByNumber': null_if_block_not_found(compose( len, operator.itemgetter('transactions'), call_eth_tester('get_block_by_number'), )), 'getUncleCountByBlockHash': null_if_block_not_found(compose( len, operator.itemgetter('uncles'), call_eth_tester('get_block_by_hash'), )), 'getUncleCountByBlockNumber': null_if_block_not_found(compose( len, operator.itemgetter('uncles'), call_eth_tester('get_block_by_number'), )), 'getCode': call_eth_tester('get_code'), 'sign': not_implemented, 'sendTransaction': call_eth_tester('send_transaction'), 'sendRawTransaction': call_eth_tester('send_raw_transaction'), 'call': call_eth_tester('call'), # TODO: untested 'estimateGas': call_eth_tester('estimate_gas'), # TODO: untested 'getBlockByHash': null_if_block_not_found(call_eth_tester('get_block_by_hash')), 'getBlockByNumber': null_if_block_not_found(call_eth_tester('get_block_by_number')), 'getTransactionByHash': null_if_transaction_not_found( call_eth_tester('get_transaction_by_hash') ), 'getTransactionByBlockHashAndIndex': get_transaction_by_block_hash_and_index, 'getTransactionByBlockNumberAndIndex': get_transaction_by_block_number_and_index, 'getTransactionReceipt': null_if_transaction_not_found(compose( apply_formatter_if( compose(is_null, operator.itemgetter('block_number')), static_return(None), ), call_eth_tester('get_transaction_receipt'), )), 'getUncleByBlockHashAndIndex': not_implemented, 'getUncleByBlockNumberAndIndex': not_implemented, 'getCompilers': not_implemented, 'compileLLL': not_implemented, 'compileSolidity': not_implemented, 'compileSerpent': not_implemented, 'newFilter': create_log_filter, 'newBlockFilter': call_eth_tester('create_block_filter'), 'newPendingTransactionFilter': call_eth_tester('create_pending_transaction_filter'), 'uninstallFilter': excepts( FilterNotFound, compose( is_null, call_eth_tester('delete_filter'), ), static_return(False), ), 'getFilterChanges': null_if_filter_not_found(call_eth_tester('get_only_filter_changes')), 'getFilterLogs': null_if_filter_not_found(call_eth_tester('get_all_filter_logs')), 'getLogs': get_logs, 'getWork': not_implemented, 'submitWork': not_implemented, 'submitHashrate': not_implemented, }, 'db': { 'putString': not_implemented, 'getString': not_implemented, 'putHex': not_implemented, 'getHex': not_implemented, }, 'shh': { 'post': not_implemented, 'version': not_implemented, 'newIdentity': not_implemented, 'hasIdentity': not_implemented, 'newGroup': not_implemented, 'addToGroup': not_implemented, 'newFilter': not_implemented, 'uninstallFilter': not_implemented, 'getFilterChanges': not_implemented, 'getMessages': not_implemented, }, 'admin': { 'addPeer': not_implemented, 'datadir': not_implemented, 'nodeInfo': not_implemented, 'peers': not_implemented, 'setSolc': not_implemented, 'startRPC': not_implemented, 'startWS': not_implemented, 'stopRPC': not_implemented, 'stopWS': not_implemented, }, 'debug': { 'backtraceAt': not_implemented, 'blockProfile': not_implemented, 'cpuProfile': not_implemented, 'dumpBlock': not_implemented, 'gtStats': not_implemented, 'getBlockRLP': not_implemented, 'goTrace': not_implemented, 'memStats': not_implemented, 'seedHashSign': not_implemented, 'setBlockProfileRate': not_implemented, 'setHead': not_implemented, 'stacks': not_implemented, 'startCPUProfile': not_implemented, 'startGoTrace': not_implemented, 'stopCPUProfile': not_implemented, 'stopGoTrace': not_implemented, 'traceBlock': not_implemented, 'traceBlockByNumber': not_implemented, 'traceBlockByHash': not_implemented, 'traceBlockFromFile': not_implemented, 'traceTransaction': not_implemented, 'verbosity': not_implemented, 'vmodule': not_implemented, 'writeBlockProfile': not_implemented, 'writeMemProfile': not_implemented, }, 'miner': { 'makeDAG': not_implemented, 'setExtra': not_implemented, 'setGasPrice': not_implemented, 'start': not_implemented, 'startAutoDAG': not_implemented, 'stop': not_implemented, 'stopAutoDAG': not_implemented, }, 'personal': { 'ecRecover': not_implemented, 'importRawKey': call_eth_tester('add_account'), 'listAccounts': call_eth_tester('get_accounts'), 'lockAccount': excepts( ValidationError, compose(static_return(True), call_eth_tester('lock_account')), static_return(False), ), 'newAccount': create_new_account, 'unlockAccount': excepts( ValidationError, compose(static_return(True), call_eth_tester('unlock_account')), static_return(False), ), 'sendTransaction': personal_send_transaction, 'sign': not_implemented, }, 'testing': { 'timeTravel': call_eth_tester('time_travel'), }, 'txpool': { 'content': not_implemented, 'inspect': not_implemented, 'status': not_implemented, }, 'evm': { 'mine': call_eth_tester('mine_blocks'), 'revert': call_eth_tester('revert_to_snapshot'), 'snapshot': call_eth_tester('take_snapshot'), }, }
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/eth_tester/defaults.py
defaults.py
from web3.providers import ( BaseProvider, ) from .middleware import ( default_transaction_fields_middleware, ethereum_tester_middleware, ) class AsyncEthereumTesterProvider(BaseProvider): """This is a placeholder. For now its purpose is to provide an awaitable request function for testing the async api execution. """ def __init__(self): self.eth_tester = EthereumTesterProvider() async def make_request(self, method, params): return self.eth_tester.make_request(method, params) class EthereumTesterProvider(BaseProvider): middlewares = [ default_transaction_fields_middleware, ethereum_tester_middleware, ] ethereum_tester = None api_endpoints = None def __init__(self, ethereum_tester=None, api_endpoints=None): # do not import eth_tester until runtime, it is not a default dependency from eth_tester import EthereumTester from eth_tester.backends.base import BaseChainBackend if ethereum_tester is None: self.ethereum_tester = EthereumTester() elif isinstance(ethereum_tester, EthereumTester): self.ethereum_tester = ethereum_tester elif isinstance(ethereum_tester, BaseChainBackend): self.ethereum_tester = EthereumTester(ethereum_tester) else: raise TypeError( "Expected ethereum_tester to be of type `eth_tester.EthereumTester` or " "a subclass of `eth_tester.backends.base.BaseChainBackend`, " f"instead received {type(ethereum_tester)}. " "If you would like a custom eth-tester instance to test with, see the " "eth-tester documentation. https://github.com/ethereum/eth-tester." ) if api_endpoints is None: # do not import eth_tester derivatives until runtime, it is not a default dependency from .defaults import API_ENDPOINTS self.api_endpoints = API_ENDPOINTS else: self.api_endpoints = api_endpoints def make_request(self, method, params): namespace, _, endpoint = method.partition('_') try: delegator = self.api_endpoints[namespace][endpoint] except KeyError: return { "error": "Unknown RPC Endpoint: {0}".format(method), } try: response = delegator(self.ethereum_tester, params) except NotImplementedError: return { "error": "RPC Endpoint has not been implemented: {0}".format(method), } else: return { 'result': response, } def isConnected(self): return True
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/eth_tester/main.py
main.py
from .main import ( # noqa: F401 EthereumTesterProvider, )
0x-web3
/0x-web3-5.0.0a5.tar.gz/0x-web3-5.0.0a5/web3/providers/eth_tester/__init__.py
__init__.py
from setuptools import setup import sys setup(name='0x', version=0.1)
0x
/0x-0.1.tar.gz/0x-0.1/setup.py
setup.py
### Здесь есть функции: - `upload_file_url(url, expires, secret)`: Загрузка файла через ссылку, url=ссылка, expires=время хранения файла в часах(можно оставить пустым), secret=удлинняет ссылку(можно оставить пустым). - `upload_file_path(path, expires, secret)`: Тоже самое что и upload_file_url, только нужно указывать путь к файлу. - `delete_file(token, url)`: Удаляет файл, token=токен, url=ссылкана файл в 0x0. - `change_expires(url, expires, token)`: Изменяет время хранения файла, token=токен, url=ссылка на файл в 0x0, expires=новое время хранение файла в часах.
0x0-python
/0x0-python-0.5.tar.gz/0x0-python-0.5/README.md
README.md
from setuptools import setup from markdown import markdown with open('README.md', 'r', encoding='utf-8') as f: long_description_md = f.read() long_description_html = markdown(long_description_md, extensions=['markdown.extensions.fenced_code']) setup(name='0x0-python', version='0.5', description='Библиотека для взаимодействия с 0x0.st через Python', long_description=long_description_html, long_description_content_type='text/markdown', author_email='neso_hoshi_official@mail.ru', zip_safe=False, author='Neso Hiroshi', classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ])
0x0-python
/0x0-python-0.5.tar.gz/0x0-python-0.5/setup.py
setup.py
# Aliyun DNS plugin for autocert project This plugin provides an automated `perform_dns01()` for [autocert](https://github.com/Smart-Hypercube/autocert/tree/master/letsencrypt#apply-for-some-certificates). ```python3 # other kinds of credential, e.g. StsTokenCredential, can be used as well credential = AccessKeyCredential(ACCESS_KEY_ID, ACCESS_KEY_SECRET) with AliyunDNS(credential) as aliyun: result = le.order(k2, domains, aliyun.perform_dns01) # added DNS records will be removed automatically ```
0x01-autocert-dns-aliyun
/0x01-autocert-dns-aliyun-0.1.tar.gz/0x01-autocert-dns-aliyun-0.1/README.md
README.md
from setuptools import setup setup( name='0x01-autocert-dns-aliyun', version='0.1', description='Aliyun DNS plugin for autocert project', url='https://github.com/Smart-Hypercube/autocert', author='Hypercube', author_email='hypercube@0x01.me', license='MIT', py_modules=['autocert_dns_aliyun'], python_requires='>=3.6', install_requires=['aliyun-python-sdk-alidns>=2.0.7'], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
0x01-autocert-dns-aliyun
/0x01-autocert-dns-aliyun-0.1.tar.gz/0x01-autocert-dns-aliyun-0.1/setup.py
setup.py
"""Aliyun DNS plugin for autocert project""" __all__ = [ 'AccessKeyCredential', 'StsTokenCredential', 'RamRoleArnCredential', 'EcsRamRoleCredential', 'RsaKeyPairCredential', 'AliyunDNS', ] import json import aliyunsdkcore.client from aliyunsdkalidns.request.v20150109.GetMainDomainNameRequest import \ GetMainDomainNameRequest from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import \ AddDomainRecordRequest from aliyunsdkalidns.request.v20150109.DeleteDomainRecordRequest import \ DeleteDomainRecordRequest from aliyunsdkcore.auth.credentials import ( AccessKeyCredential, StsTokenCredential, RamRoleArnCredential, EcsRamRoleCredential, RsaKeyPairCredential, ) class AliyunDNS: def __init__(self, credential): self.aliyun = aliyunsdkcore.client.AcsClient(credential=credential) self.records = [] def __enter__(self): return self def __exit__(self, *args): self.clean() def perform_dns01(self, domain, validation): domain_info = self._call(GetMainDomainNameRequest, InputString=domain) domain = domain_info['DomainName'] rr = domain_info['RR'] self.records.append(self._call( AddDomainRecordRequest, DomainName=domain, RR=rr, Type='TXT', Value=validation, )['RecordId']) def clean(self): for record_id in self.records: self._call(DeleteDomainRecordRequest, RecordId=record_id) def _call(self, request, **kwargs): if isinstance(request, type): request = request() for key, value in kwargs.items(): getattr(request, f'set_{key}')(value) return json.loads(self.aliyun.do_action_with_exception(request))
0x01-autocert-dns-aliyun
/0x01-autocert-dns-aliyun-0.1.tar.gz/0x01-autocert-dns-aliyun-0.1/autocert_dns_aliyun.py
autocert_dns_aliyun.py
# Cubic SDK `pip install 0x01-cubic-sdk`
0x01-cubic-sdk
/0x01-cubic-sdk-3.0.0.tar.gz/0x01-cubic-sdk-3.0.0/README.md
README.md
from setuptools import setup setup( name='0x01-cubic-sdk', version='3.0.0', author='Hypercube', author_email='hypercube@0x01.me', url='https://github.com/Smart-Hypercube/cubic-sdk', license='MIT', description='Cubic SDK', long_description='', long_description_content_type='text/markdown', packages=['cubic'], python_requires='>=3.7', install_requires=[ 'msgpack>=1.0', 'requests>=2.21', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.7', ], )
0x01-cubic-sdk
/0x01-cubic-sdk-3.0.0.tar.gz/0x01-cubic-sdk-3.0.0/setup.py
setup.py
"""Cubic SDK""" __all__ = ['Change', 'Cubic', 'Hash', 'Item', 'RemovedItem', 'Version', 'VersionData'] from dataclasses import dataclass from itertools import islice from hashlib import sha3_256 import struct from typing import Dict, Iterable, List, Mapping, Optional, Set, Tuple, Union import msgpack import requests Hash = bytes @dataclass(frozen=True) class Item: meta: bytes blocks: List[Hash] @dataclass(frozen=True) class RemovedItem: def __bool__(self): return False Change = Union[Item, RemovedItem] @dataclass(frozen=True) class Version: checksum: bytes timestamp: int timestamp_ns: int @dataclass(frozen=True) class VersionData: checksum: bytes timestamp: int timestamp_ns: int items: Dict[bytes, Item] def _validate(version: VersionData) -> None: hash = sha3_256(struct.pack('>qII', version.timestamp, version.timestamp_ns, len(version.items))) for path in sorted(version.items): item = version.items[path] hash.update(struct.pack('>III', len(path), len(item.meta), len(item.blocks))) hash.update(path) hash.update(item.meta) for h in item.blocks: hash.update(h) if hash.digest() != version.checksum: raise ValueError('VersionData validation failed') ENDPOINT = 'https://api.cubic.0x01.me' class Cubic: class Error(Exception): pass def __init__(self, tree, token, endpoint=ENDPOINT, session=None, timeout=60): self._tree = tree self._endpoint = endpoint self._session = session or requests.Session() self._session.auth = tree, token self._timeout = timeout self._limits = self._call('/v3/limits') def _call(self, api, payload=None): r = self._session.post(self._endpoint + api, data=msgpack.packb(payload), timeout=self._timeout) if not r.ok: raise self.Error(r) return msgpack.unpackb(r.content) def dedup_blocks(self, hashes: Iterable[Hash]) -> Set[Hash]: """Filter blocks that need to be uploaded.""" hashes = list(hashes) result = set() limit = self._limits['dedupBlocks/count'] for i in range(0, len(hashes), limit): result.update(self._call('/v3/dedupBlocks', hashes[i:i+limit])) return result def put_blocks(self, blocks: Iterable[bytes]) -> None: """Upload all blocks. You may want to use dedup_put_blocks instead. """ buffer = [] size = 0 limit_count = self._limits['putBlocks/count'] limit_size = self._limits['putBlocks/size'] for i in blocks: if len(buffer) + 1 > limit_count or size + len(i) > limit_size: if buffer: self._call('/v3/putBlocks', buffer) buffer = [] size = 0 buffer.append(i) size += len(i) self._call('/v3/putBlocks', buffer) def dedup_put_blocks(self, blocks: Mapping[Hash, bytes]) -> None: """Only upload necessary blocks.""" self.put_blocks(blocks[i] for i in self.dedup_blocks(blocks)) def put_block(self, block: bytes) -> None: """Upload one block.""" self._call('/v3/putBlocks', [block]) def get_blocks(self, hashes: Iterable[Hash]) -> Dict[Hash, bytes]: """Download all blocks.""" hashes = set(hashes) result = {} limit = self._limits['getBlocks/count'] while hashes: buffer = list(islice(hashes, limit)) for k, v in self._call('/v3/getBlocks', buffer).items(): hashes.discard(k) result[k] = v return result def get_block(self, hash: Hash) -> bytes: """Download one block.""" return self._call('/v3/getBlocks', [hash])[hash] def list_versions(self) -> List[Version]: """List all versions (most recent version last).""" return [Version(*i) for i in self._call('/v3/listVersions')] def diff_versions(self, from_: Union[None, Version, VersionData], to: Version) -> Dict[bytes, Change]: """Get changes between two versions.""" def f(x: Optional[Iterable]) -> Change: return Item(*x) if x else RemovedItem() payload = (from_.checksum if from_ else None), to.checksum return {k: f(v) for k, v in self._call('/v3/diffVersions', payload).items()} def get_version(self, version: Version, base: Optional[VersionData] = None) -> VersionData: """Get items of a version. If base is provided, only download changes between two versions.""" items = base.items.copy() if base else {} for k, v in self.diff_versions(base, version).items(): if v: items[k] = v else: del items[k] result = VersionData(version.checksum, version.timestamp, version.timestamp_ns, items) _validate(result) return result def update_version(self, changes: Mapping[bytes, Change], base: Optional[VersionData] = None) -> VersionData: """Create a new version using an old version and changes.""" def f(x: Change) -> Optional[Tuple]: return (x.meta, x.blocks) if x else None payload = (base.checksum if base else None), {k: f(v) for k, v in changes.items()} result = self._call('/v3/updateVersion', payload) _validate(result) return result
0x01-cubic-sdk
/0x01-cubic-sdk-3.0.0.tar.gz/0x01-cubic-sdk-3.0.0/cubic/__init__.py
__init__.py
"""Let's Encrypt library for human beings""" __all__ = ['LetsEncrypt', 'LetsEncryptStaging'] import acme.challenges import acme.client import acme.crypto_util import acme.errors import acme.messages import josepy import OpenSSL class LetsEncrypt: DIRECTORY_URL = 'https://acme-v02.api.letsencrypt.org/directory' def __init__(self, key: str, uri=None, *, phone=None, email=None): self.uri = uri if uri is None: self.account = None else: self.account = acme.messages.RegistrationResource(body={}, uri=uri) # noinspection PyTypeChecker self.key = josepy.JWK.load(key.encode('ascii')) self.session = acme.client.ClientNetwork(self.key, self.account) directory_json = self.session.get(self.DIRECTORY_URL).json() directory = acme.messages.Directory.from_json(directory_json) self.acme = acme.client.ClientV2(directory, self.session) if self.account is None: message = acme.messages.NewRegistration.from_data( phone=phone, email=email, terms_of_service_agreed=True, ) self.account = self.acme.new_account(message) self.uri = self.account.uri def order(self, key: str, domains, perform_dns01): def select_dns01(challenges): for i in challenges: if isinstance(i.chall, acme.challenges.DNS01): return i raise ValueError('DNS-01 not offered') csr = acme.crypto_util.make_csr(key, domains) order = self.acme.new_order(csr) for auth in order.authorizations: challenge = select_dns01(auth.body.challenges) response, validation = challenge.response_and_validation(self.key) name = auth.body.identifier.value domain = challenge.validation_domain_name(name) perform_dns01(domain, validation) self.acme.answer_challenge(challenge, response) return self.acme.poll_and_finalize(order).fullchain_pem def revoke(self, fullchain: str): # noinspection PyTypeChecker certificate = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fullchain) certificate = josepy.ComparableX509(certificate) try: return self.acme.revoke(certificate, 0) except acme.errors.ConflictError: pass class LetsEncryptStaging(LetsEncrypt): DIRECTORY_URL = 'https://acme-staging-v02.api.letsencrypt.org/directory'
0x01-letsencrypt
/0x01-letsencrypt-0.1.tar.gz/0x01-letsencrypt-0.1/letsencrypt.py
letsencrypt.py
# Let's Encrypt library for human beings Note: The example below used the Let's Encrypt [staging environment](https://letsencrypt.org/docs/staging-environment/). Replace `letsencrypt.LetsEncryptStaging` with `letsencrypt.LetsEncrypt` for production. ## Create account key ```bash openssl genrsa -out account.key 4096 ``` **WARNING: Keep the key safe!** ## Register on Let's Encrypt ```python3 with open('account.key') as f: account_key = f.read() # phone, email, or both can be omitted le = letsencrypt.LetsEncryptStaging(account_key, phone='...', email='...') uri = le.uri print('Please save your accound ID:') print(uri) ``` ## After you have an account ```python3 le = letsencrypt.LetsEncryptStaging(account_key, uri) ``` ## Apply for some certificates! ```bash openssl genrsa -out example.com.key 4096 ``` **WARNING: Keep the key safe!** ```python3 # just an example, please use an automated function instead def perform_dns01(domain, validation): print('Please add a TXT record:') print('domain:', domain) print('value:', validation) input('Press Enter after finished...') with open('example.com.key') as f: cert_key = f.read() with open('1.crt', 'w') as f: f.write(le.order(cert_key, ['example.com'], perform_dns01)) with open('2.crt', 'w') as f: f.write(le.order(cert_key, ['example.com', 'a.example.com'], perform_dns01)) with open('3.crt', 'w') as f: f.write(le.order(cert_key, ['a.b.example.com', '*.c.example.com'], perform_dns01)) ```
0x01-letsencrypt
/0x01-letsencrypt-0.1.tar.gz/0x01-letsencrypt-0.1/README.md
README.md
from setuptools import setup setup( name='0x01-letsencrypt', version='0.1', description="Let's Encrypt library for human beings", url='https://github.com/Smart-Hypercube/autocert', author='Hypercube', author_email='hypercube@0x01.me', license='MIT', py_modules=['letsencrypt'], python_requires='>=3.6', install_requires=['acme>=0.32'], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Security', ], )
0x01-letsencrypt
/0x01-letsencrypt-0.1.tar.gz/0x01-letsencrypt-0.1/setup.py
setup.py
``0x10c-asm`` assembly compiler for Notch's DCPU-16 --------------------------------------------------- Install from PyPI: ================== pip install 0x10c-asm Usage: ====== $ 0x10c-asm.py -h usage: ``0x10-asm.py [-h] IN [OUT]`` A simple Python-based DCPU assembly compiler positional arguments: ``IN`` file path of the file containing the assembly code ``OUT`` file path where to store the binary code optional arguments: -h, --help show this help message and exit
0x10c-asm
/0x10c-asm-0.0.2.tar.gz/0x10c-asm-0.0.2/README.rst
README.rst
#!/usr/bin/env python import re import argparse import sys import struct opcodes = [ 'SET', 'ADD', 'SUB', 'MUL', 'DIV', 'MOD', 'SHL', 'SHR', 'AND', 'BOR', 'XOR', 'IFE', 'IFN', 'IFG', 'IFB', ] nonbasic_opcodes = [ 'JSR' ] pointers = [ 'A', 'B', 'C', 'X', 'Y', 'Z', 'I', 'J', 'POP', 'PEEK', 'PUSH', 'SP', 'PC', 'O', ] oc = '|'.join(opcodes) # (SET|ADD|SUB|...) noc = '|'.join(nonbasic_opcodes) deref_pattern = '\[\s*%s\s*\]' # [ ? ] hexa = '0x[0-9a-d]{1,4}' # 0xbaba1 hexa_deref = deref_pattern % hexa # [ 0xbaba1 ] reg_pointers = '|'.join(pointers) # A|B|C reg_deref = '|'.join(deref_pattern % reg for reg in pointers[:8]) # [A]|[B] hexa_plus_reg = '(%s)\s*\+\s*(%s)' % (hexa, '|'.join(pointers[:8])) # 0xb1 + I offset = deref_pattern % hexa_plus_reg # [ 0xb1 + I ] label = '\w+' dec = '\d+' op = '|'.join( '(%s)' % x for x in [hexa, hexa_deref, reg_pointers, reg_deref, offset, dec, label] ) l_def = ':\w+' row_pattern = '^\s*(%s)?\s*(((%s)\s+(%s)\s*,\s*(%s))|((%s)\s+(%s)))?\s*(;.*)?$' re_row = re.compile(row_pattern % (l_def, oc, op, op, noc, op)) def emit_from_str(code): for line in code.split('\n'): parsed_line = re_row.match(line) if parsed_line is None: print 'error found on line: %s' % line exit(1) for token in emit_from_line(parsed_line.groups()): yield token def emit_from_line(line): if line[0]: yield ('LABEL_DEF', line[0][1:]) if line[3]: yield ('OPCODE', line[3]) for token in emit_from_op(line[4:14]): yield token for token in emit_from_op(line[14:24]): yield token if line[24]: yield ('OPCODE_NB', line[25]) for token in emit_from_op(line[26:36]): yield token if line[36]: yield ('COMMENT', line[36][1:]) def emit_from_op(op): if op[1]: yield ('CONST', int(op[1], 0)) elif op[2]: yield ('CONST_DEREF', int(op[2][1:-1], 0)) elif op[3]: yield ('REGISTRY', op[3]) elif op[4]: yield ('REGISTRY_DEREF', op[4][1:-1]) elif op[5]: yield ('OFFSET', (int(op[6], 0), op[7])) elif op[8]: yield ('CONST', int(op[8])) elif op[9]: yield ('LABEL_USE', op[9]) def compile(source): result = [] emitter = emit_from_str(source) labels = {} labels_to_update = {} to_append = [] def get_i(o_ttype, o_token): if o_ttype == 'CONST': i = o_token + 0x20 if o_token > 0x1f: i = 0x1f to_append.append(o_token) elif o_ttype == 'CONST_DEREF': i = 0x1e to_append.append(o_token) elif o_ttype == 'REGISTRY': i = pointers.index(o_token) if i >= 8: i += 0x10 elif o_ttype == 'REGISTRY_DEREF': i = pointers.index(o_token) + 0x08 elif o_ttype == 'OFFSET': offset, reg = o_token i = pointers.index(reg) + 0x10 to_append.append(offset) elif o_ttype == 'LABEL_USE': i = 0x1f addr = labels.get(o_token) if addr is None: pos = len(result) + 1 labels_to_update.setdefault(o_token, []).append(pos) to_append.append(addr) return i for ttype, token in emitter: to_append[:] = [] if ttype == 'LABEL_DEF': addr = labels[token] = len(result) for pos in labels_to_update.get(token, []): result[pos] = addr elif ttype == 'OPCODE': current_word = opcodes.index(token) + 1 shift = 0 for o_ttype, o_token in [emitter.next(), emitter.next()]: i = get_i(o_ttype, o_token) current_word += i << (4 + 6 * shift) shift += 1 result.append(current_word) result.extend(to_append) elif ttype == 'OPCODE_NB': index = nonbasic_opcodes.index(token) + 1 current_word = index << 4 o_ttype, o_token = emitter.next() i = get_i(o_ttype, o_token) current_word += i << 10 result.append(current_word) result.extend(to_append) return result def pprint(words): f = '%0.4x' wrds = words if len(words) % 8: wrds = words + [0] * (8 - len(words) % 8) for x in range(0, len(wrds), 8): print f % x + ':', ' '.join(f % w for w in wrds[x:x + 8]) def main(): parser = argparse.ArgumentParser( description='A simple Python-based DCPU assembly compiler' ) parser.add_argument( 'source', metavar='IN', type=str, nargs=1, help='file path of the file containing the assembly code' ) parser.add_argument( 'destination', metavar='OUT', type=str, nargs='?', help='file path where to store the binary code' ) args = parser.parse_args() c = compile(open(args.source[0]).read()) if args.destination is None: return pprint(c) assert sys.byteorder == 'little' out = open(args.destination, 'wb') c = [struct.pack('>H', b) for b in c] out.write(''.join(c)) out.close() if __name__ == '__main__': main()
0x10c-asm
/0x10c-asm-0.0.2.tar.gz/0x10c-asm-0.0.2/0x10c-asm.py
0x10c-asm.py
#!/usr/bin/env python from setuptools import setup setup( name='0x10c-asm', version='0.0.2', description="A simple Python-based DCPU assembly compiler", long_description=open('README.rst').read(), keywords='notch asm dcpu-16 dcpu assembly asm', author='Sever Banesiu', author_email='banesiu.sever@gmail.com', url='https://github.com/severb/0x10c-asm', license='BSD License', scripts=['0x10c-asm.py'], zip_safe=False, )
0x10c-asm
/0x10c-asm-0.0.2.tar.gz/0x10c-asm-0.0.2/setup.py
setup.py
# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['0x20bf'] package_data = \ {'': ['*']} install_requires = \ ['PyYAML==5.4.1', 'aiohttp==3.7.4.post0', 'gnupg>=2.3.1,<3.0.0', 'pre_commit>=2.1.0,<3.0.0'] setup_kwargs = { 'name': '0x20bf', 'version': '0.0.1', 'description': '0x20bf: This document proposes an Internet standards track protocol for transporting, broadcasting and syndication of messages over common internet communications channels. The distribution of all documents related to this proposal are unlimited and unencumbered by any LICENSE, but some are included anyway.', 'long_description': None, 'author': 'randymcmillan', 'author_email': 'randy.lee.mcmillan@gmail.com', 'maintainer': None, 'maintainer_email': None, 'url': None, 'packages': packages, 'package_data': package_data, 'install_requires': install_requires, 'python_requires': '>=3.8,<4.0', } setup(**setup_kwargs)
0x20bf
/0x20bf-0.0.1.tar.gz/0x20bf-0.0.1/setup.py
setup.py
from serpapi import GoogleSearch import requests from termcolor import colored def scrape(): print (colored('0x2nac0nda', 'green')) q = input('Enter the text to search : ') api_key = input('Enter your api_key : ') params = { "q": {q}, "google_domain": "google.com", "api_key": {api_key} } search = GoogleSearch(params) results = search.get_dict() knowledge_graph = results['knowledge_graph'] print(f"Serching....") print(knowledge_graph) scrape()
0x2nac0nda
/0x2nac0nda-0.1-py3-none-any.whl/abdallaabdelrhman/__init__.py
__init__.py
### Contents - [What is this?](#what-is-this) - [How do I install it?](#how-do-i-install-it) - [How do I use it?](#how-do-i-use-it) - [Extensions](#extensions) - [Reference](#reference) ### What is this?<a id="what-is-this"></a> The goal of this module is to help write code that generates code. Focus is placed on enabling the user to easily describe, build and reason about code structures rapidly. ### How do I install it?<a id="how-do-i-install-it"></a> ### From PyPI: `pip install 0xf0f-codenode` #### From GitHub: `pip install git+https://github.com/0xf0f/codenode` ### How do I use it?<a id="how-do-i-use-it"></a> Like the `json` and `pickle` modules, `dump` and `dumps` are used to generate output. Code can be built using any tree of iterables containing strings, indentation nodes and newline nodes. For example, the built-in `line` function returns a tuple: ```python from codenode import indentation, newline def line(content): return indentation, content, newline ``` Which we can combine with `indent` and `dedent` nodes: ```python from codenode import line, indent, dedent, dumps def counting_function(count_from, count_to): return [ line(f'def count_from_{count_from}_to_{count_to}():'), indent, [ line(f'print({i})') for i in range(count_from, count_to) ], dedent, ] print(dumps(counting_function(0, 5))) ``` Which outputs: ``` def count_from_0_to_5(): print(0) print(1) print(2) print(3) print(4) ``` But what if we want to count to a really big number, like 1,000,000,000,000,000? It would be inefficient to store all those lines in memory at once. We can use a generator to break them down into individual parts instead: ```python from codenode import indent, dedent, newline, indentation, dump def counting_function_generator(count_from, count_to): yield indentation yield 'def count_from_', str(count_from), '_to_', str(count_to), '():' yield newline yield indent for i in range(count_from, count_to): yield indentation, 'print(', str(i), ')', newline yield dedent with open('code.py', 'w') as file: dump(counting_function_generator(0, 1_000_000_000_000_000), file) ``` We can also build a class with an `__iter__` method: ```python from codenode import line, indent, dedent, dump class CountingFunction: def __init__(self, count_from, count_to): self.count_from = count_from self.count_to = count_to def __iter__(self): yield line( f'def count_from_{self.count_from}_to_{self.count_to}():' ) yield indent for i in range(self.count_from, self.count_to): yield line(f'print({i})') yield dedent with open('code.py', 'w') as file: dump(CountingFunction(0, 1_000_000), file) ``` Or a more generalized function class: ```python class Function: def __init__(self, name, *args): self.name = name self.args = args self.children = [] def __iter__(self): arg_string = ', '.join(self.args) yield line(f'def {self.name}({arg_string}):') yield indent yield self.children yield dedent class CountingFunction(Function): def __init__(self, count_from, count_to): super().__init__(f'count_from_{count_from}_to_{count_to}') for i in range(count_from, count_to): self.children.append(line(f'print({i})')) ``` Leveraging python's iteration protocol like this allows: - Mixing and matching whatever fits the use case to maximize tradeoffs, such as using generators for their memory efficiency, custom iterable classes for their semantics, or plain old lists and tuples for their simplicity. - Taking advantage of existing modules that offer tooling for iterables, such as itertools. - Building higher level structures from as many iterable building blocks as desired. ### Extensions Module behaviour can be extended by overriding methods of the `codenode.writer.Writer` and `codenode.writer.WriterStack` classes. An example of this can be seen in the `codenode.debug.debug_patch` function. The variable `codenode.default_writer_type` can be used to replace the `Writer` type used in `dump` and `dumps` with a custom one. Some modules with helper classes and functions are also provided: - [codenode_utilities](codenode_utilities/README.md) - contains general language agnostic helper functions and classes [comment]: <> ( - codenode_python) [comment]: <> ( - contains helper classes and functions for generating python code) [comment]: <> ( - codenode_cpp) [comment]: <> ( - contains helper classes and functions for generating c++ code) [comment]: <> ( - codenode_legacy) [comment]: <> ( - helpers for code that relies on the old codenode API &#40;below version 1.0&#41;) [comment]: <> ( - uses a previous, entirely different approach to nodes) ### Reference<a id="reference"></a> > **Note** > This section of the readme was generated using codenode itself. > > See docs/generate_readme.py #### Contents - [codenode.dump](#codenodedump) - [codenode.dumps](#codenodedumps) - [codenode.line](#codenodeline) - [codenode.indent](#codenodeindent) - [codenode.dedent](#codenodededent) - [codenode.newline](#codenodenewline) - [codenode.indentation](#codenodeindentation) - [codenode.lines](#codenodelines) - [codenode.empty_lines](#codenodeempty_lines) - [codenode.indented](#codenodeindented) - [codenode.default_writer_type](#codenodedefault_writer_type) - [codenode.writer.Writer](#codenodewriterwriter) - [codenode.writer.WriterStack](#codenodewriterwriterstack) - [codenode.nodes.newline.Newline](#codenodenodesnewlinenewline) - [codenode.nodes.depth_change.DepthChange](#codenodenodesdepth_changedepthchange) - [codenode.nodes.depth_change.RelativeDepthChange](#codenodenodesdepth_changerelativedepthchange) - [codenode.nodes.depth_change.AbsoluteDepthChange](#codenodenodesdepth_changeabsolutedepthchange) - [codenode.nodes.indentation.Indentation](#codenodenodesindentationindentation) - [codenode.nodes.indentation.RelativeIndentation](#codenodenodesindentationrelativeindentation) - [codenode.nodes.indentation.AbsoluteIndentation](#codenodenodesindentationabsoluteindentation) - [codenode.nodes.indentation.CurrentIndentation](#codenodenodesindentationcurrentindentation) - [codenode.debug.debug_patch](#codenodedebugdebug_patch) --- ### codenode.dump<a id="codenodedump"></a> > ```python > def dump(node, stream, *, indentation=' ', newline='\n', depth=0, debug=False): ... > ```` > > Process and write out a node tree to a stream. > > > #### Parameters > * > ***node:*** > > Base node of node tree. > * > ***stream:*** > > An object with a 'write' method. > * > ***indentation:*** > > String used for indents in the output. > * > ***newline:*** > > String used for newlines in the output. > * > ***depth:*** > > Base depth (i.e. number of indents) to start at. > * > ***debug:*** > > If True, will print out extra info when an error > > occurs to give a better idea of which node caused it. --- ### codenode.dumps<a id="codenodedumps"></a> > ```python > def dumps(node, *, indentation=' ', newline='\n', depth=0, debug=False) -> str: ... > ```` > > Process and write out a node tree as a string. > > > #### Parameters > * > ***node:*** > > Base node of node tree. > * > ***indentation:*** > > String used for indents in the output. > * > ***newline:*** > > String used for newlines in the output. > * > ***depth:*** > > Base depth (i.e. number of indents) to start at. > * > ***debug:*** > > If True, will print out extra info when an error > > occurs to give a better idea of which node caused it. > > > #### Returns > * > String representation of node tree. > --- ### codenode.line<a id="codenodeline"></a> > ```python > def line(content: 'T') -> 'tuple[Indentation, T, Newline]': ... > ```` > > Convenience function that returns a tuple containing > an indentation node, line content and a newline node. > > > #### Parameters > * > ***content:*** > > content of line > #### Returns > * > tuple containing an indentation node, line content and > a newline node. > --- ### codenode.indent<a id="codenodeindent"></a> > A node representing a single increase in indentation level. --- ### codenode.dedent<a id="codenodededent"></a> > A node representing a single decrease in indentation level. --- ### codenode.newline<a id="codenodenewline"></a> > A placeholder node for line terminators. --- ### codenode.indentation<a id="codenodeindentation"></a> > A placeholder node for indentation whitespace at the start of a line. --- ### codenode.lines<a id="codenodelines"></a> > ```python > def lines(*items) -> tuple[tuple, ...]: ... > ```` > > Convenience function that returns a tuple of lines, > where each argument is the content of one line. > > > #### Parameters > * > ***items:*** > > contents of lines > #### Returns > * > tuple of lines > --- ### codenode.empty_lines<a id="codenodeempty_lines"></a> > ```python > def empty_lines(count: int) -> 'tuple[Newline, ...]': ... > ```` > > Convenience function that returns a tuple of newline nodes. > > > #### Parameters > * > ***count:*** > > Number of newlines. > #### Returns > * > Tuple of newlines. > --- ### codenode.indented<a id="codenodeindented"></a> > ```python > def indented(*nodes) -> tuple: ... > ```` > > Convenience function that returns a tuple containing an indent node, > some inner nodes, and a dedent node. > > > #### Parameters > * > ***nodes:*** > > inner nodes > #### Returns > * > tuple containing an indent node, inner nodes, and a dedent node. > --- ### codenode.default_writer_type<a id="codenodedefault_writer_type"></a> > Default Writer type used in codenode.dump and codenode.dumps. --- ### codenode.writer.Writer<a id="codenodewriterwriter"></a> > ```python > class Writer: ... > ``` > > Processes node trees into strings then writes out the result. > > Each instance is intended to be used once then discarded. > After a single call to either dump or dumps, the Writer > instance is no longer useful. #### Methods > ##### `__init__` > ```python > class Writer: > def __init__(self, node: 'NodeType', *, indentation=' ', newline='\n', depth=0): ... > ```` > > > #### Parameters > * > ***node:*** > > Base node of node tree. > * > ***indentation:*** > > Initial string used for indents in the output. > * > ***newline:*** > > Initial string used for newlines in the output. > * > ***depth:*** > > Base depth (i.e. number of indents) to start at. > ##### `process_node` > ```python > class Writer: > def process_node(self, node) -> 'Iterable[str]': ... > ```` > > Yield strings representing a node and/or apply any of its > associated side effects to the writer > > for example: > > - yield indentation string when an indentation node is encountered > > - increase the current writer depth if an indent is encountered > > - append an iterator to the stack when an iterable is encountered > > > #### Parameters > * > ***node:*** > > node to be processed > #### Returns > * > strings of text chunks representing the node > > ##### `dump_iter` > ```python > class Writer: > def dump_iter(self) -> 'Iterable[str]': ... > ```` > > Process and write out a node tree as an iterable of > string chunks. > > > #### Returns > * > Iterable of string chunks. > > ##### `dump` > ```python > class Writer: > def dump(self, stream): ... > ```` > > Process and write out a node tree to a stream. > > > #### Parameters > * > ***stream:*** > > An object with a 'write' method. > ##### `dumps` > ```python > class Writer: > def dumps(self): ... > ```` > > Process and write out a node tree as a string. > > > #### Returns > * > String representation of node tree. > #### Attributes > ***node:*** > Base node of node tree > ***stack:*** > WriterStack used to iterate over the node tree > ***indentation:*** > Current string used for indents in the output > ***newline:*** > Current string used for line termination in the output > ***depth:*** > Current output depth (i.e. number of indents) --- ### codenode.writer.WriterStack<a id="codenodewriterwriterstack"></a> > ```python > class WriterStack: ... > ``` > > A stack of iterators. > Used by the Writer class to traverse node trees. > > Each instance is intended to be used once then discarded. #### Methods > ##### `push` > ```python > class WriterStack: > def push(self, node: 'NodeType'): ... > ```` > > Converts a node to an iterator then places it at > the top of the stack. > > > #### Parameters > * > ***node:*** > > iterable node > ##### `__iter__` > ```python > class WriterStack: > def __iter__(self) -> 'Iterable[NodeType]': ... > ```` > > Continually iterates the top iterator in the stack's items, > yielding each result then popping each iterator off when they > are exhausted. > #### Attributes > ***items:*** collections.deque - > Current items in the stack. --- ### codenode.nodes.newline.Newline<a id="codenodenodesnewlinenewline"></a> > ```python > class Newline: ... > ``` > > Nodes that represent the end of a line. --- ### codenode.nodes.depth_change.DepthChange<a id="codenodenodesdepth_changedepthchange"></a> > ```python > class DepthChange: ... > ``` > > Nodes that represent a change in indentation depth. #### Methods > ##### `new_depth_for` > ```python > class DepthChange: > def new_depth_for(self, depth: int) -> int: ... > ```` > > Method used to calculate the new depth based on the current one. > > > #### Parameters > * > ***depth:*** > > Current depth. > #### Returns > * > New depth. > --- ### codenode.nodes.depth_change.RelativeDepthChange<a id="codenodenodesdepth_changerelativedepthchange"></a> > ```python > class RelativeDepthChange: ... > ``` > > Nodes that represent a change in indentation depth relative to the > current depth by some preset amount. #### Methods > ##### `__init__` > ```python > class RelativeDepthChange: > def __init__(self, offset: int): ... > ```` > > > #### Parameters > * > ***offset:*** > > Amount by which to increase/decrease depth. #### Attributes > ***offset:*** > Amount by which to increase/decrease depth when this node is > processed. --- ### codenode.nodes.depth_change.AbsoluteDepthChange<a id="codenodenodesdepth_changeabsolutedepthchange"></a> > ```python > class AbsoluteDepthChange: ... > ``` > > Nodes that represent a change in indentation depth without taking > the current depth into account. #### Methods > ##### `__init__` > ```python > class AbsoluteDepthChange: > def __init__(self, value: int): ... > ```` > > > #### Parameters > * > ***value:*** > > Value to set depth to. #### Attributes > ***value:*** > Value to which depth will be set to when this node is > processed. --- ### codenode.nodes.indentation.Indentation<a id="codenodenodesindentationindentation"></a> > ```python > class Indentation: ... > ``` > > Nodes that represent indentation whitespace at the start of a line. #### Methods > ##### `indents_for` > ```python > class Indentation: > def indents_for(self, depth: int) -> int: ... > ```` > > > #### Parameters > * > ***depth:*** > > Current depth. > #### Returns > * > Number of indents to include in whitespace when this > node is processed. > --- ### codenode.nodes.indentation.RelativeIndentation<a id="codenodenodesindentationrelativeindentation"></a> > ```python > class RelativeIndentation: ... > ``` > > Nodes that represent indentation whitespace at the start of a line, > with a number of indents relative to the current depth by some > preset amount. #### Methods > ##### `__init__` > ```python > class RelativeIndentation: > def __init__(self, offset: int): ... > ```` > > > #### Parameters > * > ***offset:*** > > Amount of indents relative to the current depth. #### Attributes > ***offset:*** > Amount of indents relative to the current depth that will be > output when this node is processed. --- ### codenode.nodes.indentation.AbsoluteIndentation<a id="codenodenodesindentationabsoluteindentation"></a> > ```python > class AbsoluteIndentation: ... > ``` > > Nodes that represent indentation whitespace at the start of a line, > with a number of indents independent of the current depth. #### Methods > ##### `__init__` > ```python > class AbsoluteIndentation: > def __init__(self, value: int): ... > ```` > > > #### Parameters > * > ***value:*** > > Amount of indents. #### Attributes > ***value:*** > Amount of indents that will be output when this node is processed. --- ### codenode.nodes.indentation.CurrentIndentation<a id="codenodenodesindentationcurrentindentation"></a> > ```python > class CurrentIndentation: ... > ``` > > Nodes that represent indentation whitespace at the start of a line, > with a number of indents equal to the current depth. --- ### codenode.debug.debug_patch<a id="codenodedebugdebug_patch"></a> > ```python > def debug_patch(writer_type: typing.Type[Writer]) -> typing.Type[Writer]: ... > ```` > > Creates a modified version of a writer type > which prints out some extra info when encountering > an error to give a better ballpark idea of what caused it. > Used in codenode.dump/dumps to implement the debug parameter. > > > #### Parameters > * > ***writer_type:*** > > Base writer type. > #### Returns > * > New child writer type with debug modifications. >
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/README.md
README.md
from setuptools import setup, find_packages from docs import generate_pypi_readme setup( name='0xf0f-codenode', version='1.0rc1', packages=[ 'codenode', 'codenode.nodes', 'codenode_utilities', ], url='https://github.com/0xf0f/codenode', license='MIT', author='0xf0f', author_email='0xf0f.dev@gmail.com', long_description=generate_pypi_readme.run(), long_description_content_type='text/markdown', description='a simple framework for code generation', classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.9', )
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/setup.py
setup.py
import collections import functools import io import pprint import typing from .writer import Writer, WriterStack class DebugIterator: def __init__(self, iterable): self.iterable = iterable self.iterator = iter(iterable) self.items_yielded = 0 self.item_buffer = collections.deque(maxlen=8) def __iter__(self): return self def __next__(self): item = next(self.iterator) self.items_yielded += 1 self.item_buffer.append(item) return item @property def current_item(self): return self.item_buffer[-1] if len(self.item_buffer) else None def print_writer_stack(writer: Writer, stream): pretty_print = functools.partial( pprint.pprint, stream=stream, depth=2, compact=False, indent=2, width=128, ) for index, iterator in enumerate(writer.stack.items): stream.write(f'node #{index}: \n') stream.write(f'type: {type(iterator.iterable)}\n') if isinstance(iterator, DebugIterator): if isinstance(iterator.iterable, typing.Sequence): for sub_index, sub_item in enumerate(iterator.iterable): stream.write(f' item {sub_index}: ') pretty_print(sub_item) else: pretty_print(iterator.iterable) stream.write( f' last {len(iterator.item_buffer)} items processed: ' f'({iterator.items_yielded} total)\n' ) for item in iterator.item_buffer: stream.write(' ') pretty_print(item) else: stream.write(repr(iterator)) stream.write('\n') stream.write('\n') def debug_patch(writer_type: typing.Type[Writer]) -> typing.Type[Writer]: """ Creates a modified version of a writer type which prints out some extra info when encountering an error to give a better ballpark idea of what caused it. Used in codenode.dump/dumps to implement the debug parameter. :param writer_type: Base writer type. :return: New child writer type with debug modifications. """ class PatchedWriter(writer_type): @property def stack(self): return self._stack @stack.setter def stack(self, stack: WriterStack): push = stack.push stack.push = lambda node: push(DebugIterator(node)) self._stack = stack def dump_iter(self): try: yield from super().dump_iter() except Exception as e: buffer = io.StringIO() buffer.write(''.join(map(str, e.args))) buffer.write('\n\nWriter stack:\n') print_writer_stack(self, buffer) e.args = (buffer.getvalue(),) raise return PatchedWriter
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode/debug.py
debug.py
import collections import io import typing from .nodes.newline import Newline from .nodes.indentation import Indentation from .nodes.depth_change import DepthChange if typing.TYPE_CHECKING: from typing import Union, Iterable NodeType = Iterable[Union[str, 'NodeType']] class WriterStack: """ A stack of iterators. Used by the Writer class to traverse node trees. Each instance is intended to be used once then discarded. """ def __init__(self): self.items: collections.deque = collections.deque() """ Current items in the stack. """ def push(self, node: 'NodeType'): """ Converts a node to an iterator then places it at the top of the stack. :param node: iterable node """ self.items.append(iter(node)) def __iter__(self) -> 'Iterable[NodeType]': """ Continually iterates the top iterator in the stack's items, yielding each result then popping each iterator off when they are exhausted. """ while self.items: try: yield next(self.items[-1]) except StopIteration: self.items.pop() class Writer: """ Processes node trees into strings then writes out the result. Each instance is intended to be used once then discarded. After a single call to either dump or dumps, the Writer instance is no longer useful. """ def __init__( self, node: 'NodeType', *, indentation=' ', newline='\n', depth=0, ): """ :param node: Base node of node tree. :param indentation: Initial string used for indents in the output. :param newline: Initial string used for newlines in the output. :param depth: Base depth (i.e. number of indents) to start at. """ self.node = node "Base node of node tree" self.stack = WriterStack() "WriterStack used to iterate over the node tree" self.stack.push((node,)) self.indentation = indentation "Current string used for indents in the output" self.newline = newline "Current string used for line termination in the output" self.depth = depth "Current output depth (i.e. number of indents)" def process_node(self, node) -> 'Iterable[str]': """ Yield strings representing a node and/or apply any of its associated side effects to the writer for example: - yield indentation string when an indentation node is encountered - increase the current writer depth if an indent is encountered - append an iterator to the stack when an iterable is encountered :param node: node to be processed :returns: strings of text chunks representing the node """ if isinstance(node, str): yield node elif isinstance(node, DepthChange): self.depth = node.new_depth_for(self.depth) elif isinstance(node, Indentation): yield self.indentation * node.indents_for(self.depth) elif isinstance(node, Newline): yield self.newline else: try: self.stack.push(node) except TypeError as error: raise TypeError( f'Unable to process node "{node}".\n' 'Either convert it to a string, iterable or ' 'override Writer.process_node to handle nodes ' 'of this type.' ) from error def dump_iter(self) -> 'Iterable[str]': """ Process and write out a node tree as an iterable of string chunks. :return: Iterable of string chunks. """ for node in self.stack: yield from self.process_node(node) def dump(self, stream): """ Process and write out a node tree to a stream. :param stream: An object with a 'write' method. """ for chunk in self.dump_iter(): stream.write(chunk) def dumps(self): """ Process and write out a node tree as a string. :return: String representation of node tree. """ buffer = io.StringIO() self.dump(buffer) return buffer.getvalue()
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode/writer.py
writer.py
from .writer import Writer from .nodes.depth_change import RelativeDepthChange from .nodes.indentation import CurrentIndentation from .nodes.newline import Newline from .debug import debug_patch default_writer_type = Writer "Default Writer type used in codenode.dump and codenode.dumps." indent = RelativeDepthChange(1) "A node representing a single increase in indentation level." dedent = RelativeDepthChange(-1) "A node representing a single decrease in indentation level." indentation = CurrentIndentation() "A placeholder node for indentation whitespace at the start of a line." newline = Newline() "A placeholder node for line terminators." def line(content: 'T') -> 'tuple[Indentation, T, Newline]': """ Convenience function that returns a tuple containing an indentation node, line content and a newline node. :param content: content of line :return: tuple containing an indentation node, line content and a newline node. """ return indentation, content, newline def lines(*items) -> tuple[tuple, ...]: """ Convenience function that returns a tuple of lines, where each argument is the content of one line. :param items: contents of lines :return: tuple of lines """ return tuple(map(line, items)) def empty_lines(count: int) -> 'tuple[Newline, ...]': """ Convenience function that returns a tuple of newline nodes. :param count: Number of newlines. :return: Tuple of newlines. """ return (newline,) * count def indented(*nodes) -> tuple: """ Convenience function that returns a tuple containing an indent node, some inner nodes, and a dedent node. :param nodes: inner nodes :return: tuple containing an indent node, inner nodes, and a dedent node. """ return indent, nodes, dedent def dump( node, stream, *, indentation=' ', newline='\n', depth=0, debug=False, ): """ Process and write out a node tree to a stream. :param node: Base node of node tree. :param stream: An object with a 'write' method. :param indentation: String used for indents in the output. :param newline: String used for newlines in the output. :param depth: Base depth (i.e. number of indents) to start at. :param debug: If True, will print out extra info when an error occurs to give a better idea of which node caused it. """ if debug: writer_type = debug_patch(default_writer_type) else: writer_type = default_writer_type return writer_type( node, indentation=indentation, newline=newline, depth=depth, ).dump(stream) def dumps( node, *, indentation=' ', newline='\n', depth=0, debug=False, ) -> str: """ Process and write out a node tree as a string. :param node: Base node of node tree. :param indentation: String used for indents in the output. :param newline: String used for newlines in the output. :param depth: Base depth (i.e. number of indents) to start at. :param debug: If True, will print out extra info when an error occurs to give a better idea of which node caused it. :return: String representation of node tree. """ if debug: writer_type = debug_patch(default_writer_type) else: writer_type = default_writer_type return writer_type( node, indentation=indentation, newline=newline, depth=depth, ).dumps() __all__ = [ 'indent', 'dedent', 'indented', 'indentation', 'newline', 'line', 'lines', 'empty_lines', 'dump', 'dumps', 'default_writer_type', ]
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode/__init__.py
__init__.py
class Indentation: """ Nodes that represent indentation whitespace at the start of a line. """ def indents_for(self, depth: int) -> int: """ :param depth: Current depth. :return: Number of indents to include in whitespace when this node is processed. """ raise NotImplementedError class RelativeIndentation(Indentation): """ Nodes that represent indentation whitespace at the start of a line, with a number of indents relative to the current depth by some preset amount. """ def __init__(self, offset: int): """ :param offset: Amount of indents relative to the current depth. """ self.offset = offset """ Amount of indents relative to the current depth that will be output when this node is processed. """ def indents_for(self, depth: int) -> int: return depth + self.offset def __repr__(self): return f'<RelativeIndentation {self.offset:+}>' class AbsoluteIndentation(Indentation): """ Nodes that represent indentation whitespace at the start of a line, with a number of indents independent of the current depth. """ def __init__(self, value: int): """ :param value: Amount of indents. """ self.value = value """ Amount of indents that will be output when this node is processed. """ def indents_for(self, depth: int) -> int: return self.value def __repr__(self): return f'<AbsoluteIndentation {self.value}>' class CurrentIndentation(Indentation): """ Nodes that represent indentation whitespace at the start of a line, with a number of indents equal to the current depth. """ def indents_for(self, depth: int) -> int: return depth def __repr__(self): return f'<Indentation>'
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode/nodes/indentation.py
indentation.py
class DepthChange: """ Nodes that represent a change in indentation depth. """ def new_depth_for(self, depth: int) -> int: """ Method used to calculate the new depth based on the current one. :param depth: Current depth. :return: New depth. """ raise NotImplementedError class RelativeDepthChange(DepthChange): """ Nodes that represent a change in indentation depth relative to the current depth by some preset amount. """ def __init__(self, offset: int): """ :param offset: Amount by which to increase/decrease depth. """ self.offset = offset """ Amount by which to increase/decrease depth when this node is processed. """ def new_depth_for(self, depth: int) -> int: return depth + self.offset def __repr__(self): return f'<RelativeDepthChange {self.offset:+}>' class AbsoluteDepthChange(DepthChange): """ Nodes that represent a change in indentation depth without taking the current depth into account. """ def __init__(self, value: int): """ :param value: Value to set depth to. """ self.value = value """ Value to which depth will be set to when this node is processed. """ def new_depth_for(self, depth: int) -> int: return self.value def __repr__(self): return f'<AbsoluteDepthChange {self.value}>'
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode/nodes/depth_change.py
depth_change.py
class Newline: """ Nodes that represent the end of a line. """ def __repr__(self): return '<Newline>'
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode/nodes/newline.py
newline.py
from codenode import indent, dedent, dump, dumps import typing T = typing.TypeVar('T') class PartitionedNode: """ A node with three separate sections: a header, an indented body and a footer. Keeps track of child nodes using a list, which is yielded as the default body. Has convenience methods for adding children and dumping output using the default Writer type. """ def __init__(self): self.children = [] """ Node in the body section. """ def header(self) -> 'Iterable': """ Starting section of node. """ yield from () def body(self) -> 'Iterable': """ Middle section of node. Yields children by default. """ yield from self.children def footer(self) -> 'Iterable': """ Ending section of node. """ yield from () def __iter__(self): yield from self.header() yield indent yield from self.body() yield dedent yield from self.footer() def add_child(self, node: 'T') -> 'T': """ Add a node to this node's children. :param node: Node to add. :return: Added node. """ self.children.append(node) return node def add_children(self, nodes: typing.Iterable[T]) -> typing.Iterable[T]: """ Add multiple nodes to this node's children. :param nodes: Nodes to add. :return: The added nodes """ self.children.extend(nodes) return nodes def dump( self, stream, *, indentation=' ', newline='\n', depth=0, debug=False, ): """ Process and write out this node to a stream. :param stream: An object with a 'write' method. :param indentation: String used for indents in the output. :param newline: String used for newlines in the output. :param depth: Base depth (i.e. number of indents) to start at. :param debug: If True, will print out extra info when an error occurs to give a better idea of which node caused it. """ return dump( self, stream, indentation=indentation, newline=newline, depth=depth, debug=debug, ) def dumps( self, *, indentation=' ', newline='\n', depth=0, debug=False, ): """ Process and write out this node as a string. :param indentation: String used for indents in the output. :param newline: String used for newlines in the output. :param depth: Base depth (i.e. number of indents) to start at. :param debug: If True, will print out extra info when an error occurs to give a better idea of which node caused it. :return: String representation of node. """ return dumps( self, indentation=indentation, newline=newline, depth=depth, debug=debug, )
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode_utilities/partitioned_node.py
partitioned_node.py
# import itertools from codenode import newline sentinel = object() def joined(nodes, *, start='', separator=newline, end=newline): """ yields a starting node, then a sequence of nodes with a separator between each one, then an ending node :param nodes: sequence of nodes in the middle :param start: node at the start :param separator: node repeated between middle nodes :param end: ending node :return: iterable consisting of starting node, middle nodes with separators, and an ending node """ # iterator = iter(nodes) # # yield start # # try: # yield next(iterator) # except StopIteration: # pass # else: # yield from itertools.chain.from_iterable( # zip( # itertools.repeat(separator), # iterator, # ) # ) # # yield end iterator = iter(nodes) item = next(iterator, sentinel) yield start while item is not sentinel: yield item item = next(iterator, sentinel) if item is not sentinel: yield separator else: yield end
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode_utilities/joined.py
joined.py
import typing from codenode.writer import Writer T = typing.TypeVar('T', bound=typing.Type[Writer]) def auto_coerce_patch( writer_type: T, coerce=str, ) -> T: """ Returns an altered version of a writer type that will automatically convert unprocessable nodes to another type. :param writer_type: Base writer type. :param coerce: Callable used to convert nodes. str by default. :return: Descendant writer type that will convert unprocessable nodes. """ class PatchedWriter(writer_type): def process_node(self, node): try: yield from super().process_node(node) except TypeError: yield from super().process_node(coerce(node)) return PatchedWriter
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode_utilities/auto_coerce.py
auto_coerce.py
import functools def node_transformer(func): """ decorator for creating functions that are used to recursively transform node trees. :param func: transformer function applied to each node :return: a function which recursively applies the transformer function to each node in the tree. """ @functools.wraps(func) def wrapper(node): if isinstance(node, str): yield func(node) else: try: yield from map(wrapper, node) except TypeError: yield func(node) return wrapper # class NodeTransformer: # """ # has a repr for extra debug info # """ # # def __init__(self, node): # self.node = node # # def transform(self, node): # raise NotImplementedError # # def __iter__(self): # if isinstance(self.node, str): # yield self.transform(self.node) # else: # try: # yield from map(type(self), self.node) # except TypeError: # yield self.transform(self.node) # # def __repr__(self): # return f'{super().__repr__()}({self.node})' #
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode_utilities/node_transformer.py
node_transformer.py
import codenode import io import typing # from .node_transformer import node_transformer # from codenode.nodes.indentation import AbsoluteIndentation, CurrentIndentation # from codenode.nodes.depth_change import RelativeDepthChange # # # def prefixer(prefix): # """ # # :param prefix: # :return: # """ # def prefixed(node): # indents = 0 # # @node_transformer # def transform(node): # nonlocal indents # if isinstance(node, RelativeDepthChange): # indents += node.offset # yield node # elif isinstance(node, CurrentIndentation): # yield RelativeDepthChange(-indents) # yield node # yield prefix # yield AbsoluteIndentation(indents) # yield RelativeDepthChange(indents) # else: # yield node # # yield from transform(node) # return prefixed # from .node_transformer import NodeTransformer # # # def prefixer(prefix: str): # def prefixed(node): # indents = 0 # # class Prefixer(NodeTransformer): # def transform(self, node): # nonlocal indents # if isinstance(node, RelativeDepthChange): # indents += node.offset # yield node # elif isinstance(node, CurrentIndentation): # yield RelativeDepthChange(-indents) # yield node # yield prefix # yield AbsoluteIndentation(indents) # yield RelativeDepthChange(indents) # else: # yield node # # return Prefixer(node) # # return prefixed # import inspect # # def get_writer_type(): # stack = inspect.stack() # for frame_info in stack: # try: # cls = frame_info.frame.f_locals['__class__'] # except KeyError: # continue # else: # if issubclass(cls, codenode.Writer): # return cls # # def yield_lines(iterator: typing.Iterable[str]): buffer = io.StringIO() for chunk in iterator: newline_position = chunk.find('\n') if newline_position >= 0: buffer.write(chunk[:newline_position]) yield buffer.getvalue() buffer.seek(0) buffer.write(chunk[newline_position+1:]) buffer.truncate() else: buffer.write(chunk) if buffer.tell(): yield buffer.getvalue() # # # def prefixer(prefix: str): # def prefixed( # node, # dump_iter=None, # ): # if dump_iter is None: # writer_type = get_writer_type() # dump_iter = lambda node: writer_type(node).dump_iter() # # for line_content in yield_lines(dump_iter(node)): # yield codenode.line(f'{prefix}{line_content}') # return prefixed def prefixer(prefix: str): """ Returns a node transformer that adds a string to the start of every line in the output of a node. :param prefix: String to place at the start of lines. :return: A function that takes a node as an argument, along with a function to convert a node to a string (i.e. codenode.dumps). It calls this function with the given node, then returns new nodes containing each line in the string along with the prefix at the start. """ def prefixed( node, dumps=lambda node: codenode.dumps(node), ): for line_content in dumps(node).splitlines(): yield codenode.line(f'{prefix}{line_content}') return prefixed def prefixer_iter(prefix: str): """ Returns a node transformer that adds a string to the start of every line in the output of a node. Works iteratively, line by line, rather than rendering out the node all at once. :param prefix: String to place at the start of lines. :return: A function that takes a node as an argument, along with a function to convert a node to an iterable of strings (i.e. codenode.Writer.dump_iter). It calls this function with the given node, then returns new nodes containing each line in the output along with the prefix at the start. """ def prefixed( node, dump_iter=lambda node: codenode.default_writer_type(node).dump_iter() ): for line_content in yield_lines(dump_iter(node)): yield codenode.line(f'{prefix}{line_content}') return prefixed
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode_utilities/prefixer.py
prefixer.py
from .node_transformer import node_transformer from .prefixer import prefixer from .suffixer import suffixer from .joined import joined from .auto_coerce import auto_coerce_patch from .partitioned_node import PartitionedNode
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode_utilities/__init__.py
__init__.py
import codenode from codenode import indentation, newline def suffixer( suffix: str, dumps=lambda node: codenode.dumps(node), ): """ Returns a node transformer that adds a string to the end of every line in the output of a node. Padding is added automatically to align all suffixes to the end of the longest line. :param suffix: String to place at the end of lines. :return: A function that takes a node as an argument, along with a function to convert a node to a string (i.e. codenode.dumps). It calls this function with the given node, then returns new nodes containing each line in the string along with the suffix at the end. """ def suffixed(node): output_lines = dumps(node).splitlines() max_line_length = max(map(len, output_lines)) for index, line_text in enumerate(output_lines): yield indentation yield line_text yield ' ' * (max_line_length - len(line_text)) yield suffix yield newline return suffixed
0xf0f-codenode
/0xf0f-codenode-1.0rc1.tar.gz/0xf0f-codenode-1.0rc1/codenode_utilities/suffixer.py
suffixer.py
from . import lib1 from . import lib2
1-test-package
/1_test_package-0.0.5-py3-none-any.whl/pkg/__init__.py
__init__.py
from . import math_x # __all__ = ["math_x"]
1-test-package
/1_test_package-0.0.5-py3-none-any.whl/pkg/lib2/__init__.py
__init__.py
def add_x(a, b): return a + b
1-test-package
/1_test_package-0.0.5-py3-none-any.whl/pkg/lib2/math_x.py
math_x.py
import numpy as np from ..lib2.math_x import * # relative path # . means current folder, e.g. lib1 # .. means one folder above, e.g. pkg # ..lib2.math_x -> pkg.lib2.math_x class Eye_Diagram(object): def __init__(self, ui, spb, ipn, x_bin, y_bin): self.folder_path = '' self.UI = ui self.SPB = spb self.ipn = ipn # interpolation, number of points inserted between every 2 adjacent samples. self.x_bin = x_bin self.y_bin = y_bin self.x_min = -self.UI/2 # self.x_max = self.UI/2 self.y_min = None self.y_max = None self.number_of_symbols = 0 # total sampled symbols by clock ticks. self.eye_1D = np.empty([2, 1], dtype=object) # let's store eye_1D in RAM at first, i.e. on the fly self.eye_2D = np.zeros([self.y_bin, self.x_bin]) # let's store eye_2D in RAM at first, i.e. on the fly. # both eyes are in 1 UI. self.eye_1D_2UI = None self.eye_2D_2UI = None self.create_eye_1D = False # generate eye_1D or not. def add_test(self): return self.x_bin + self.y_bin def lib1_double_add(a, b): c = add_x(a, b) return 2 * c def new_add(a, b): return a + b + 100
1-test-package
/1_test_package-0.0.5-py3-none-any.whl/pkg/lib1/eye_diagram.py
eye_diagram.py
def wf_ten(a): return a * 10
1-test-package
/1_test_package-0.0.5-py3-none-any.whl/pkg/lib1/waveform.py
waveform.py
from . import eye_diagram from . import waveform # __all__ = ["eye_diagram", "waveform"]
1-test-package
/1_test_package-0.0.5-py3-none-any.whl/pkg/lib1/__init__.py
__init__.py
# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['10_0_0_55'] package_data = \ {'': ['*']} install_requires = \ ['requests>=2.27.1,<3.0.0'] setup_kwargs = { 'name': '10-0-0-55', 'version': '2.0.4', 'description': 'A headless login / logout script for 10.0.0.55', 'long_description': None, 'author': 'spencerwooo', 'author_email': 'spencer.woo@outlook.com', 'maintainer': None, 'maintainer_email': None, 'url': None, 'packages': packages, 'package_data': package_data, 'install_requires': install_requires, 'python_requires': '>=3.8', } setup(**setup_kwargs)
10-0-0-55
/10_0_0_55-2.0.4.tar.gz/10_0_0_55-2.0.4/setup.py
setup.py
import argparse import sys from .action import Action from .config import read_config from .user import User def main(): parser = argparse.ArgumentParser(description="Login to BIT network") parser.add_argument("action", choices=["login", "logout"], help="login or logout") parser.add_argument("-u", "--username") parser.add_argument("-p", "--password") parser.add_argument("-v", "--verbose", action="store_true") parser.add_argument("-s", "--silent", action="store_true") parser.add_argument("-nc", "--no-color", action="store_true") args = parser.parse_args() if args.username and args.password: user = User(args.username, args.password) elif conf := read_config(): user = User(*conf) else: parser.print_usage() sys.exit(1) try: if args.action == "login": res = user.do_action(Action.LOGIN) # Output login result by default if not silent if not args.silent: print(f"{res.get('username')} ({res.get('real_name')}) logged in") else: res = user.do_action(Action.LOGOUT) # Output logout result by default if not silent if not args.silent: print(res.get("online_ip"), "logged out") # Output direct result of response if verbose if args.verbose: if args.no_color: print("Info:", res) else: print("\33[34m[Info]\033[0m", res) except Exception as e: if args.no_color: print("Error:", e) else: print("\033[91m[Error]", e, "\033[0m") # Throw with error code 1 for scripts to pick up error state sys.exit(1) if __name__ == "__main__": main()
10-0-0-55
/10_0_0_55-2.0.4.tar.gz/10_0_0_55-2.0.4/10_0_0_55/__main__.py
__main__.py
import json import os from typing import Optional, Tuple def get_config_path(filename: str) -> map: paths = ["/etc/"] if os.geteuid(): xdg_config_home = os.getenv("XDG_CONFIG_HOME") if xdg_config_home: paths.append(xdg_config_home) else: paths.append(os.path.expanduser("~/.config")) return map(lambda path: os.path.join(path, filename), paths) def read_config() -> Optional[Tuple[str, str]]: paths = get_config_path("bit-user.json") for path in paths: try: with open(path) as f: data = json.loads(f.read()) return data["username"], data["password"] except Exception: continue return None
10-0-0-55
/10_0_0_55-2.0.4.tar.gz/10_0_0_55-2.0.4/10_0_0_55/config.py
config.py
from enum import Enum class Action(Enum): LOGIN = "login" LOGOUT = "logout"
10-0-0-55
/10_0_0_55-2.0.4.tar.gz/10_0_0_55-2.0.4/10_0_0_55/action.py
action.py
import math from base64 import b64encode from html.parser import HTMLParser from typing import Optional, Tuple from urllib.parse import parse_qs, urlparse import requests API_BASE = "http://10.0.0.55" def parse_homepage() -> Tuple[str, str]: """Parse homepage of 10.0.0.55 and get the acid + ip of current session Raises: Exception: Throw exception if acid not present in the redirected URL Exception: Throw exception if response text does not contain IP Returns: Tuple[str, str]: Both the ip and the acid of the current session """ res = requests.get(API_BASE) # ac_id appears in the url query parameter of the redirected URL query = parse_qs(urlparse(res.url).query) ac_id = query.get("ac_id") if not ac_id: raise Exception("failed to get acid") # ip appears in the response HTML class IPParser(HTMLParser): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ip = None def handle_starttag(self, tag, attrs): if tag == "input": attr_dict = dict(attrs) if attr_dict.get("name") == "user_ip": self.ip = attr_dict["value"] def feed(self, *args, **kwargs): super().feed(*args, **kwargs) return self.ip parser = IPParser() ip = parser.feed(res.text) if not ip: raise Exception("failed to get ip") return ip, ac_id[0] def get_user_info() -> Tuple[bool, Optional[str]]: """Get current logged in user info if exists Returns: tuple[bool, Optional[str]] - a boolean indicating whether the current IP is logged in - the username of the current logged in user if exists """ is_logged_in = True username = None resp = requests.get(API_BASE + "/cgi-bin/rad_user_info") data = resp.text if data == "not_online_error": is_logged_in = False else: username = data.split(",")[0] return is_logged_in, username def fkbase64(raw_s: str) -> str: """Encode string with a magic base64 mask""" trans = str.maketrans( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "LVoJPiCN2R8G90yg+hmFHuacZ1OWMnrsSTXkYpUq/3dlbfKwv6xztjI7DeBE45QA", ) ret = b64encode(bytes(ord(i) & 0xFF for i in raw_s)) return ret.decode().translate(trans) def xencode(msg, key) -> str: def sencode(msg, key): def ordat(msg, idx): if len(msg) > idx: return ord(msg[idx]) return 0 msg_len = len(msg) pwd = [] for i in range(0, msg_len, 4): pwd.append(ordat(msg, i) | ordat(msg, i + 1) << 8 | ordat(msg, i + 2) << 16 | ordat(msg, i + 3) << 24) if key: pwd.append(msg_len) return pwd def lencode(msg, key) -> str: msg_len = len(msg) ll = (msg_len - 1) << 2 if key: m = msg[msg_len - 1] if m < ll - 3 or m > ll: return "" ll = m for i in range(0, msg_len): msg[i] = chr(msg[i] & 0xFF) + chr(msg[i] >> 8 & 0xFF) + chr(msg[i] >> 16 & 0xFF) + chr(msg[i] >> 24 & 0xFF) if key: return "".join(msg)[0:ll] return "".join(msg) if msg == "": return "" pwd = sencode(msg, True) pwdk = sencode(key, False) if len(pwdk) < 4: pwdk = pwdk + [0] * (4 - len(pwdk)) n = len(pwd) - 1 z = pwd[n] y = pwd[0] c = 0x86014019 | 0x183639A0 m = 0 e = 0 p = 0 q = math.floor(6 + 52 / (n + 1)) d = 0 while 0 < q: d = d + c & (0x8CE0D9BF | 0x731F2640) e = d >> 2 & 3 p = 0 while p < n: y = pwd[p + 1] m = z >> 5 ^ y << 2 m = m + ((y >> 3 ^ z << 4) ^ (d ^ y)) m = m + (pwdk[(p & 3) ^ e] ^ z) pwd[p] = pwd[p] + m & (0xEFB8D130 | 0x10472ECF) z = pwd[p] p = p + 1 y = pwd[0] m = z >> 5 ^ y << 2 m = m + ((y >> 3 ^ z << 4) ^ (d ^ y)) m = m + (pwdk[(p & 3) ^ e] ^ z) pwd[n] = pwd[n] + m & (0xBB390742 | 0x44C6F8BD) z = pwd[n] q = q - 1 return lencode(pwd, False)
10-0-0-55
/10_0_0_55-2.0.4.tar.gz/10_0_0_55-2.0.4/10_0_0_55/utils.py
utils.py
import hmac import json from hashlib import sha1 from typing import Dict, Union from requests import Session from .action import Action from .exception import AlreadyLoggedOutException, AlreadyOnlineException, UsernameUnmatchedException from .utils import fkbase64, get_user_info, parse_homepage, xencode API_BASE = "http://10.0.0.55" TYPE_CONST = 1 N_CONST = 200 class User: def __init__(self, username: str, password: str): self.username = username self.password = password self.ip, self.acid = parse_homepage() self.session = Session() def do_action(self, action: Action) -> Dict[str, Union[str, int]]: # Check current state - whether device is logged in and whether current user the same as the provided one is_logged_in, username = get_user_info() if is_logged_in and action is Action.LOGIN: raise AlreadyOnlineException(f"{username}, you are already online") if not is_logged_in and action is Action.LOGOUT: raise AlreadyLoggedOutException("you have already logged out") # Raise exception only if username exists on this IP and command line arguments provided another username if username and username != self.username: raise UsernameUnmatchedException( f"current logged in user {username} and provided username {self.username} does not match" ) # Perform login or logout action params = self._make_params(action) response = self.session.get(API_BASE + "/cgi-bin/srun_portal", params=params) return json.loads(response.text[6:-1]) def _get_token(self) -> str: params = {"callback": "jsonp", "username": self.username, "ip": self.ip} response = self.session.get(API_BASE + "/cgi-bin/get_challenge", params=params) result = json.loads(response.text[6:-1]) return result["challenge"] def _make_params(self, action: Action) -> Dict[str, str]: token = self._get_token() params = { "callback": "jsonp", "username": self.username, "action": action.value, "ac_id": self.acid, "ip": self.ip, "type": TYPE_CONST, "n": N_CONST, } data = { "username": self.username, "password": self.password, "acid": self.acid, "ip": self.ip, "enc_ver": "srun_bx1", } hmd5 = hmac.new(token.encode(), b"", "MD5").hexdigest() json_data = json.dumps(data, separators=(",", ":")) info = "{SRBX1}" + fkbase64(xencode(json_data, token)) chksum = sha1( "{0}{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}".format( token, self.username, hmd5, self.acid, self.ip, N_CONST, TYPE_CONST, info ).encode() ).hexdigest() params.update({"password": "{MD5}" + hmd5, "chksum": chksum, "info": info}) return params
10-0-0-55
/10_0_0_55-2.0.4.tar.gz/10_0_0_55-2.0.4/10_0_0_55/user.py
user.py
class AlreadyOnlineException(Exception): pass class AlreadyLoggedOutException(Exception): pass class UsernameUnmatchedException(Exception): pass
10-0-0-55
/10_0_0_55-2.0.4.tar.gz/10_0_0_55-2.0.4/10_0_0_55/exception.py
exception.py
# 80+ Python Projects by MRayan Asim 🐍🚀 <p align="center"> <img src="https://github.com/mrayanasim09/python-projects/raw/main/MRayan.png" alt="My Logo" style="max-width: 100%; max-height: 100%;"> </p> ## Table of Contents - [Repository Structure 📂](#repository-structure-) - [Categories 🗂️](#categories-%EF%B8%8F) - [Projects 🔥](#projects-) - [*GUI 🖥️*](#gui-️) - [*Calculator 🧮*](#calculator-) - [*Games 🎮*](#games-) - [*Machine Learning 🤖📚🧠*](#machine-learning-) - [*Utilities 🛠️*](#utilities-️) - [Skill Level Tags ⭐](#skill-level-tags-) - [Installation ⚙️](#installation-️) - [About the Author 👤](#about-the-author-) - [License 📝](#license-) - [Note 📌](#note-) - [FAQ 🗒️](#frequently-asked-questions-faq-%EF%B8%8F) **🚀 Welcome to the mesmerizing realm of the Python Projects repository, curated by MRayan Asim! Get ready to embark on an exhilarating coding odyssey, where a trove of captivating Python creations awaits to inspire and empower developers of all levels. Whether you're taking your first coding steps or you're a seasoned programmer crafting intricate algorithms, this repository serves as your gateway to a world of endless possibilities. Discover gems that boost your resume's brilliance and engage in student projects that foster learning. Uncover a wealth of resources, expert guidance, and hands-on code examples that breathe life into your Python-based projects. Join us on this thrilling journey as we unveil the extraordinary potential of Python together! 💡🔥** <p align="center"> <a href="https://forms.gle/SzJ4VA1zWZ3ehqGC6"> <img src="https://img.shields.io/badge/Google%20Forms-Give%20Your%20Feedback-red?style=for-the-badge&logo=google-forms" alt="Give me your feedback"> </a> </p> ## Repository Structure 📂 The repository is organized into different categories, each containing specific project folders. This structure allows for easy navigation and helps you find projects that align with your interests. Each project is tagged with appropriate labels to indicate the recommended skill level. Let's take a look at the categories available: ## Categories 🗂️ * [GUI](https://github.com/drik493/python\_projects/tree/main/GUI) 🖥️ * [Calculator](https://github.com/drik493/python\_projects/tree/main/Calculator) 🧮 * [Games](https://github.com/drik493/python\_projects/tree/main/Game) 🎮 * [Machine learning](https://github.com/mrayanasim09/python-projects/tree/main/machine\_learning) 🤖📚🧠 * [Utilities](https://github.com/drik493/python\_projects/tree/main/Utilities) 🛠️ ## Projects 🔥 Explore the projects in each category to find detailed information, documentation, and code examples. Here's a glimpse of the projects available within each category: ## *GUI 🖥️* * [Form](https://github.com/drik493/python\_projects/blob/main/GUI/Form.py) 📝 * [A basic GUI calculator](https://github.com/drik493/python\_projects/blob/main/GUI/A\_basic\_gui\_calculator.py) 🧮 * [A working GUI clock also download the clock image](GUI/clock.py) 🕤 * [Tick cross (with GUI) ](GUI/tick\_cross.py)✔️❌ * [Todo list (with GUI)](GUI/todo.py) ✅📝 * [Notepad](https://github.com/drik493/python\_projects/blob/main/GUI/notepad.py) 📄 * [A snake and ladder game ](GUI/snake\_ladder.py)and [(also download the images with it)](GUI/ezgif-5-ad15f112d4.gif) 🐍🪜 * [A paint application](GUI/paint.py)🖌️🎨 * [A file explorer](GUI/file\_explorer.py) 📂🔎 * [Youtube video downloader](GUI/youtube\_download.py) 📺🔽💾 * [spelling correction](GUI/spelling.py) 🔤📏🔍 * [Figet spinner (use it on windows with space bar)](GUI/spinner.py) ߷ * [A beautiful design using turtle](GUI/graphics.py) 🐢🎨 * [A quiz application for asking common questions ](https://github.com/mrayanasim09/python-projects/blob/main/GUI/Quiz.py) 👉📜 * [Pikachu using turtle](GUI/Pikachu.py) (っ◔◡◔)っ * [Doraemon using turtle](GUI/doramon.py)🐱‍🚀 * [Rainbow with turtle ](GUI/rainbow.py)🌈 * [A happy birthday message to the user with its name](GUI/happy\_birth\_day.py)🎂 * [Search installed applications](GUI/search\_applications.py) 🔍 * [A GUI calendar ](GUI/clender.py)📅 ## *Calculator 🧮* * [Quadratic Equation (with graph)](https://github.com/drik493/python\_projects/blob/main/Calculator/Quadratic\_Equation.py) 📈 * [A mega calculator with all operations](https://github.com/drik493/python\_projects/blob/main/Calculator/mega\_calculator.py) 🖩 * [A stock analyzer with its short form](Calculator/stock.py) 💵📊📈 * [Number base converter](https://github.com/drik493/python\_projects/blob/main/Calculator/number\_base.py) 🔢 * [Integration and differentiation](https://github.com/drik493/python\_projects/blob/main/Calculator/int\_diff.py) ∫ * [BMI calculator](https://github.com/drik493/python\_projects/blob/main/Calculator/bmi.py) 🏋️ * [Roman number convertor to decimal number](Calculator/roman\_number.py) 🧠 * [Time calculator](https://github.com/mrayanasim09/python-projects/blob/main/Calculator/time_calulator.py) ☀️🌙 * [special theory of relativity calculator](Calculator/special\_relativity\_calculator.py) ⌛📏⚡ * [Collatz Conjecture (3x+1) (with GUI)](https://github.com/drik493/python\_projects/blob/main/Calculator/conject.py) 📐 * [Fibonacci sequence](https://github.com/drik493/python\_projects/blob/main/Calculator/sequence.py) 🐇 * [Graph calculator from equation (with graph)](https://github.com/drik493/python\_projects/blob/main/Calculator/graph.py) 📊 * [Montly Mortgage calculator](Calculator/Mortgage.py) 📈💴 * [12 hour time into 24 hour time](Calculator/12\_to\_24.py) 🕰️🕛 * [Grade calculator](https://github.com/drik493/python\_projects/blob/main/Calculator/grade.py) 🎓 * [Sudoku solver](https://github.com/drik493/python\_projects/blob/main/Calculator/sudukko.py) 🧩 * [A program to find the ASCII value of characters](Calculator/ASCII%20.py) 💻🔧 ## *Games 🎮* * [2048 game (without GUI)](https://github.com/drik493/python\_projects/blob/main/Game/2048.py) 🎲 * [Snake game (with GUI)](https://github.com/drik493/python\_projects/blob/main/Game/snake\_game.py) 🐍 * [Hangman](https://github.com/drik493/python\_projects/blob/main/Game/hangman.py) 🪓 * [Colox (a box colliding game with GUI)](Game/colox.py) 📦❄️ * [A color guessing game with GUI](Game/color\_guessing.py) 🎨🔍🌈 * [Master Mind](https://github.com/drik493/python\_projects/blob/main/Game/master\_mid.py) 🔐 * [A number details (prime, odd, co-prime, etc)](https://github.com/drik493/python\_projects/blob/main/Game/number\_details.py) 🔢 * Tick cross [(with GUI)](https://github.com/drik493/python\_projects/blob/main/Game/tick\_cross.py) or [(without GUI)](Game/tick\_cross\_gui.py) ❌⭕ * [Rock, paper, and scissors (without GUI)](https://github.com/drik493/python\_projects/blob/main/Game/rock,paper,scissors.py) ✊🖐✌️ * [A snake and ladder game ](Game/snake\_ladder.py)and [(also download the images with it)](Game/ezgif-5-ad15f112d4.gif) 🐍🪜 * [21 or 20 plus game](https://github.com/drik493/python\_projects/blob/main/Game/21.py) 🃏 * [Typing speed test](Game/typing\_speed.py) 🎮 * [Star patterns (7 types of patterns)](https://github.com/drik493/python\_projects/blob/main/Game/star.py) ✨ * [Dice rolling (With user guess without GUI)](https://github.com/drik493/python\_projects/blob/main/Game/dice.py) 🎲 * [Number guessing game](https://github.com/drik493/python\_projects/blob/main/Game/number\_guessing.py) 🔢❓ ## *Machine Learning 🤖📚🧠* * [Brightness controller with your hand](machine\_learning/brightness\_controllor.py) 🌞💡🎛️ * [Eye blink detection (also download the . XML files)](machine\_learning/eye\_blink.py) 👁️🔍😴 * [Text to speech](machine\_learning/text\_to\_speech.py) 🔤🔉 * [A language detector ](machine\_learning/lang\_dect.py)🔍🌐 * [A spam message delectation using machine learning ](machine\_learning/spam\_dect.py)🎁🎉🎈 * [Crypto price predictions (for days ahead of days entered by the user)](machine\_learning/crypto\_prices.py) 🚀🌕 * [Gold price predictions (for days ahead of days entered by the user)](machine\_learning/gold\_price.py) 💰🪙 * [Your phone camera on your PC ](machine\_learning/camera.py)you can check more about it [here](https://www.makeuseof.com/tag/ip-webcam-android-phone-as-a-web-cam/) 📱💻📸 * [A sentiments checker](machine\_learning/sentiments.py) 🤔💬💭 * [A sketch maker of image ](machine\_learning/sketch.py)🖌️ ## *Utilities 🛠️* * [Network passwords (only for the networks you have been connected to)](https://github.com/drik493/python\_projects/blob/main/Utilities/network.py) 🔐 * [Your own browser](Utilities/browser.py) 🌐 * [A site connection checker and timer](https://github.com/mrayanasim09/python-projects/blob/main/Utilities/connectivity.py) 🔗🌐 * [Count down (timer)](https://github.com/drik493/python\_projects/blob/main/Utilities/count\_down.py) ⏳ * [Tells basic information of an Instagram account only from user name](Utilities/inta.py) 📸 * [Transfer file (generate QR code for easy access)](https://github.com/drik493/python\_projects/blob/main/Utilities/transfer.py) 📁 * [Google search (from terminal)](https://github.com/drik493/python\_projects/blob/main/Utilities/google.py) 🔍 * [A password manager with a master key and encryption and decryption of passwords](Utilities/password\_manager.py) 🔐 * [bitcoin mining simulator](Utilities/btc.py) ₿ * [QR code generator](https://github.com/drik493/python\_projects/blob/main/Utilities/url.py) 🔗 * [Wattsapp spam messages sender (you should click on the message bar of WhatsApp after running it)](Utilities/whatsapp\_spam.py) 📧🔁📧🔁📧🔁 * [Github repository details finder (only with username and name of the repository)](Utilities/github.py) :octocat: * [Secret code generator (with decoding support)](https://github.com/drik493/python\_projects/blob/main/Utilities/secret\_code.py) 🤐 * [Password to hash form (md5)](https://github.com/drik493/python\_projects/blob/main/Utilities/password\_hash.py) 🔒 * [Hash password cracking (md5 only, using rockyou.txt)](https://github.com/drik493/python\_projects/blob/main/Utilities/password.py) 🚫🔍 * [Password generator](https://github.com/drik493/python\_projects/blob/main/Utilities/passwrd\_generator.py) 🔐🔢 * [Birth Day Finder (also zodiac sign, life path number, your birth date according to Islam and birthstone and birth flower)](https://github.com/drik493/python\_projects/blob/main/Utilities/birthday.py) 🎂🎉 * [words and letter count of given text](Utilities/word\_count.py) 🔢🔄️ * [A program to make short forms for the entered words](Utilities/short\_form.py) 🔤🔄 ## Skill Level Tags ⭐ Projects are labeled with the following tags to help you identify their recommended skill level: * Beginner: Suitable for beginners who are new to Python programming. 🌱 * Intermediate: Projects that require a moderate level of Python programming knowledge. 🚀 * Advanced: Projects that involve advanced concepts and techniques in Python. 🧠 ## Installation ⚙️ we used these packages in our repository: * Pygame 🎮 * Tkinter 🖼️ * GoogleSearch 🔍 * qrcode 📷 * Matplotlib 📊 * yfinance 💵📈 * Turtle 🐢 * Random 🎲 * Time ⏰ * Pillow 🖼️ * NumPy 🔢 * openpyxl 📄 * Datetime ⌚ * math ➗ * requests 🌐 * hijri\_converter 🌙 * threading 🧵 * instaloader 📥 * string 🔡 * hashlib 🔒 * socketserver 🖧 * socket 🧦 * http.server 🌐 * os 🖥️ * opencv 📷👁️ * langdetect 🌍 * sys 🔄💻 * json 🧩📄🔍 * re 🧩 * pyshorteners 🧹 * PyQt5 🐍🖼️🔌 * PyQtWebEngine: 🕸️🖼️🔌 * Panda 🐼🎉🐾 * textblob 📝📊🔍 * vaderSentiment 🤖💭📈 * pyttsx3 🔊🗣️ * winapps 👁️📂 * pytube 📼 * screen-brightness-control 🌞🖥️🔆 * pyautogui 📦🔧💻🐍 * mediapipe 🎥📡🤝 * prophet 🔮📈 * seaborn 📊🌈 You can install these packages using pip, the Python package manager. Open your terminal or command prompt and run the following commands: ```shell pip install pygame pip install googlesearch-python pip install qrcode pip install pyautogui pip install pyttsx3 pip install winapps pip install matplotlib pip install tkcalendar pip install pyqt5 pip install pyqtwebengine pip install yfinance pip install pillow pip install openpyxl pip install sympy pip install pytube pip install hijri_converter pip install requests pip install instaloader pip install opencv-python pip install textblob pip install vaderSentiment pip install langdetect pip install screen-brightness-control pip install numpy pip install prophet pip install seaborn pip install mediapipe pip install pyshorteners ``` ### *To view more details on how to use this repository you can go* [_**here**_](How\_to\_use.md) If you encounter any issues running the code, please report an issue, and I will respond as quickly as possible. 🐞 # About the Author 👤 MRayan Asim maintains this repository. As a passionate Python enthusiast, MRayan Asim is dedicated to developing practical and innovative projects. Whether you're a beginner or an experienced developer, MRayan Asim strives to provide projects that cater to various skill levels. If you have any questions or suggestions regarding the projects in this repository, feel free to reach out. 🚀\ [![Join our Discord](https://img.shields.io/badge/Join%20our%20Discord-7289DA?style=flat\&logo=discord\&logoColor=white)](https://discord.gg/uRfXYjub) [![Join Our Reddit Community](https://img.shields.io/badge/Join%20the%20Community-Reddit-orange)](https://www.reddit.com/r/Python\_projects\_rayan/) [![Email](https://img.shields.io/badge/Email-mrayanasim09%40gmail.com-%23D14836?logo=gmail)](mailto:mrayanasim09@gmail.com) [![LinkedIn](https://img.shields.io/badge/LinkedIn-View%20Profile-blue?logo=linkedin)](https://www.linkedin.com/in/mrayan-asim-044836275/) [![GitHub](https://img.shields.io/badge/GitHub-mrayanasim09-blue?logo=github)](https://github.com/mrayanasim09) ### *If you are thinking about how to start learning programming so you can check out my* [_roadmap on medium_](https://mrayanasim09.medium.com/how-to-start-learning-programming-from-beginners-to-advance-14248dcc7afa) # License 📝 ### *⚠️ DISCLAIMER: For educational purposes only. Code provided under* [![MIT License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE/) ⚖️ # **Note 📌** #### Feeling inspired to be a part of our dynamic community? Begin your journey by familiarizing yourself with our [**Code of Conduct**](code\_of\_conduct.md). We believe in a supportive and inclusive environment where everyone can thrive. #### Ready to make your mark on our projects? Check out our [**How to Contribute**](CONTRIBUTING.md) guide, and embark on your coding adventure with us! #### Excited to play a vital role in securing our projects? Explore the essential steps and best practices in our [**Security Policies**](SECURITY.md) to safeguard our coding community. Join hands with us on this crucial mission! #### Discover a treasure trove of Python projects! From GUIs to machine learning, this repository offers many practical code examples and resources. **[Check out the summary](summary.md)** to explore our diverse collection and embark on your coding adventure with us! ### 🔍 To view the requirements for the system and Python version, you can check out the [prerequisites](https://github.com/mrayanasim09/python-projects/blob/main/prerequisites.md) 📋 # Frequently Asked Questions (FAQ) 🗒️ ## *For common questions and troubleshooting tips, please check our [FAQ](FAQ.md)* ### *Remember, the world of coding is full of wonders, and your journey starts right here! 🌟* # 🌟 **Sponsor Me and Fuel My Creativity** 🌟 If you find my Python projects valuable and would like to show your support, consider sponsoring me! Your generous contribution empowers me to continue developing innovative and practical projects for the coding community. A simple gesture like buying me a coffee goes a long way in keeping me fueled for more coding sessions. ☕️ <p align="center"> <a href="https://www.buymeacoffee.com/mrayanasim" target="_blank"> <img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" height="50px"> </a> </p> 💎 For those who prefer cryptocurrency, you can send some Ether (ETH) to my Ethereum wallet address: _**0xEC55fFf7a8387eeaa0Ef886305350Ab3578CE5D3**_. Your sponsorship means the world to me and serves as a powerful motivation to keep creating exciting Python projects for everyone to enjoy. 🚀🐍 🙏 Thank you for your incredible support! Your contributions inspire me to reach new heights and make a positive impact in the coding community. Let's create something amazing together! 🌟 ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/mrayanasim09/python-projects) ![GitHub repo size](https://img.shields.io/github/repo-size/mrayanasim09/python-projects) ![GitHub top language](https://img.shields.io/github/languages/top/mrayanasim09/python-projects) ![GitHub contributors](https://img.shields.io/github/contributors-anon/mrayanasim09/python-projects) ![Visitors](https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fgithub.com%2Fmrayanasim09%2Fpython-projects\&label=Views\&countColor=%23555555\&style=flat-square) [![codebeat badge](https://codebeat.co/badges/6fdc6dd9-f8b4-4af7-82bf-5dfc44c69273)](https://codebeat.co/projects/github-com-mrayanasim09-python-projects-main) [![CodeFactor](https://www.codefactor.io/repository/github/mrayanasim09/python-projects/badge)](https://www.codefactor.io/repository/github/mrayanasim09/python-projects) [![DeepSource](https://app.deepsource.com/gh/mrayanasim09/python-projects.svg/?label=active+issues&show_trend=true&token=R4sWBGxzRPv6AjY4YoLiE-wT)](https://app.deepsource.com/gh/mrayanasim09/python-projects/?ref=repository-badge) [![Backup Status](https://cloudback.it/badge/mrayanasim09/python-projects)](https://cloudback.it) ![GitHub last commit (branch)](https://img.shields.io/github/last-commit/mrayanasim09/python-projects/main) ![GitHub commit activity (branch)](https://img.shields.io/github/commit-activity/w/mrayanasim09/python-projects/main) ![GitHub release (with filter)](https://img.shields.io/github/v/release/mrayanasim09/python-projects) ## *To View full Documentations you can go [here](https://mrayans.gitbook.io/python--projects/)* <script src="//code.tidio.co/ytw5wbhm91dwsvp9mv9gdiob6za99eer.js" async></script> <script src="https://cdn.ingest-lr.com/LogRocket.min.js" crossorigin="anonymous"></script> <script>window.LogRocket && window.LogRocket.init('93y3w1/python-projects');</script>
100-python-projects
/100_python_projects-0.5.tar.gz/100_python_projects-0.5/README.md
README.md
from setuptools import setup, find_packages def print_install_message(): print("***************************************") print("* This package is made by MRayan Asim *") print("***************************************") import atexit atexit.register(print_install_message) setup( name="100_python_projects", version="0.5", description="A collection of Python projects", author="MRayan Asim", author_email="mrayanasim09@gmail.com", packages=find_packages(), )
100-python-projects
/100_python_projects-0.5.tar.gz/100_python_projects-0.5/setup.py
setup.py
<h1></h1> <p> <div class="separator" style="clear: both;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: block; padding: 1em 0px; text-align: center;" target="_blank"></a><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></div><div class="separator" style="clear: both;"><br /><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Would you like to achieve your dream of being a successful Forex trader?&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Take the shortcut to success with the state of the art Forex algorithm from 1000pip Climber. This trading system is rated 5 star on Investing.com and has verififed performance history from MyFXBook, so you can be confident that you are using the best algorithm available.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" target="_blank">&gt;&gt;&gt;Click here to learn more</a></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This unique Forex system continuously analyses the FX market, looking for potentially high probability price movements. Once identified the software will notify you visually, audibly, and via email.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">ALL key parameters are provided; entry price, take profit and stop loss. The Forex system is easy to set up and is designed to be followed 100% mechanically – just try the Forex system and see the results. This Forex system really is the simplest way to follow the FX market.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This is a rare opportunity to use a professional Forex trading algorithm that has produced highly accurate and consistent results. Join our group of loyal members and see how you can revolutionize your trading.</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><br /></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; font-family: -webkit-standard; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></p></div> # 1000pip Climber System Free Download ```bash pip3 1000pip Climber System Free Download
1000-pip-Climber-System-Download
/1000%20pip%20Climber%20System%20Download-2023.tar.gz/1000 pip Climber System Download-2023/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # 1000 pip Climber System Download name="1000 pip Climber System Download", version="2023", author="1000 pip Climber System Download", author_email="1000pip@ClimberSystemfreedownload.com", description="1000 pip Climber System Download", long_description=long_description, long_description_content_type="text/markdown", url="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000-pip-Climber-System-Download
/1000%20pip%20Climber%20System%20Download-2023.tar.gz/1000 pip Climber System Download-2023/setup.py
setup.py
<h1></h1> <p> <div class="separator" style="clear: both;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: block; padding: 1em 0px; text-align: center;" target="_blank"></a><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></div><div class="separator" style="clear: both;"><br /><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Would you like to achieve your dream of being a successful Forex trader?&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Take the shortcut to success with the state of the art Forex algorithm from 1000pip Climber. This trading system is rated 5 star on Investing.com and has verififed performance history from MyFXBook, so you can be confident that you are using the best algorithm available.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" target="_blank">&gt;&gt;&gt;Click here to learn more</a></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This unique Forex system continuously analyses the FX market, looking for potentially high probability price movements. Once identified the software will notify you visually, audibly, and via email.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">ALL key parameters are provided; entry price, take profit and stop loss. The Forex system is easy to set up and is designed to be followed 100% mechanically – just try the Forex system and see the results. This Forex system really is the simplest way to follow the FX market.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This is a rare opportunity to use a professional Forex trading algorithm that has produced highly accurate and consistent results. Join our group of loyal members and see how you can revolutionize your trading.</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><br /></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; font-family: -webkit-standard; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></p></div> # 1000pip Climber System Free Download ```bash pip3 1000pip Climber System Free Download
1000-pip-Climber-System-cracked
/1000%20pip%20Climber%20System%20cracked-2023.tar.gz/1000 pip Climber System cracked-2023/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # 1000 pip Climber System cracked name="1000 pip Climber System cracked", version="2023", author="1000 pip Climber System cracked", author_email="1000pip@ClimberSystemfreedownload.com", description="1000 pip Climber System cracked", long_description=long_description, long_description_content_type="text/markdown", url="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000-pip-Climber-System-cracked
/1000%20pip%20Climber%20System%20cracked-2023.tar.gz/1000 pip Climber System cracked-2023/setup.py
setup.py
<h1></h1> <p> <div class="separator" style="clear: both;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: block; padding: 1em 0px; text-align: center;" target="_blank"></a><a href="https://1cc5e9nl-wm84kdoa-ckkk3w4q.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></div><div class="separator" style="clear: both;"><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><br /></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><br /></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><br /></p></div> # 1000pip builder forex signals review ```bash pip3 1000pip builder forex signals review
1000pip-Builder-Forex-Signals
/1000pip%20Builder%20Forex%20Signals-2022.tar.gz/1000pip Builder Forex Signals-2022/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # pip3 1000pip Builder Forex Signals name="1000pip Builder Forex Signals", version="2022", author="1000pip Builder Forex Signals", author_email="1000pip@BuilderForexSignals.com", description="1000pip Builder Forex Signals", long_description=long_description, long_description_content_type="text/markdown", url="https://1cc5e9nl-wm84kdoa-ckkk3w4q.hop.clickbank.net/?tid=py", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000pip-Builder-Forex-Signals
/1000pip%20Builder%20Forex%20Signals-2022.tar.gz/1000pip Builder Forex Signals-2022/setup.py
setup.py
<h1></h1> <p> <p>&nbsp;</p><div class="separator" style="clear: both; text-align: center;"><a href="https://bfca1bsjtxsz0qao2rakno2q6w.hop.clickbank.net/?tid=pypi" rel="nofollow" style="margin-left: 1em; margin-right: 1em;" target="_blank"><img border="0" data-original-height="66" data-original-width="372" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4l5Om8UgNW8H-xTWhIzADqqMVSw1UACA9qVkwlB3iq7WPzrWrDpvzG_xSJoJ7PPNSw66w9zKPeqAnlhSdobVmRP66RJT3abfvpidg4KqZyFV7Hd6cX8JpOVRQNkE_DgdHpLh6AfaVGnHsZKsRwxwsl3fj_quznxTcVdGp1D1lBSqqPxKXJNOMDpWnYQ/s16000/button_download-now-2.png" /></a></div><div><p style="box-sizing: border-box; color: #454545; font-family: Circular-book; font-size: 18px; margin: 0px 0px 15px; padding: 0px 0px 5px;"><br /></p><p style="box-sizing: border-box; color: #454545; font-family: Circular-book; font-size: 18px; margin: 0px 0px 15px; padding: 0px 0px 5px;">1000pip Climber System is a State of the art trading algorithm, designed to make it as easy as possible to trade the Forex market.</p><p style="box-sizing: border-box; color: #454545; font-family: Circular-book; font-size: 18px; margin: 0px 0px 15px; padding: 0px 0px 5px;"><br /></p><p style="box-sizing: border-box; color: #454545; font-family: Circular-book; font-size: 18px; margin: 0px 0px 15px; padding: 0px 0px 5px;"></p><ul style="text-align: left;"><li>Official Website : <a href="https://bfca1bsjtxsz0qao2rakno2q6w.hop.clickbank.net/?tid=pypi">1000pipclimbersystem.com</a></li><li>Founded in 2017</li><li>Located in United Kingdom</li><li>TRAINING : Webinars + Documentation</li><li>SUPPORT : Only Chat</li><li>Price : $97.00 one-time (No free trial No free version)</li></ul><p></p></div><div><br /></div> # 1000pip Climber System Free Download ```bash pip3 1000pip Climber System Free Download
1000pip-Climber-System-Free-Download
/1000pip%20Climber%20System%20Free%20Download-1.tar.gz/1000pip Climber System Free Download-1/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # pip3 1000pip Climber System Free Download name="1000pip Climber System Free Download", version="1", author="1000pip Climber System Free Download", author_email="1000pip@ClimberSystem.com", description="1000pip Climber System Free Download", long_description=long_description, long_description_content_type="text/markdown", url="https://bfca1bsjtxsz0qao2rakno2q6w.hop.clickbank.net/?tid=pypi", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000pip-Climber-System-Free-Download
/1000pip%20Climber%20System%20Free%20Download-1.tar.gz/1000pip Climber System Free Download-1/setup.py
setup.py
<h1></h1> <p> <p>&nbsp;</p><div class="separator" style="clear: both; text-align: center;"><a href="https://bfca1bsjtxsz0qao2rakno2q6w.hop.clickbank.net/?tid=pypi" rel="nofollow" style="margin-left: 1em; margin-right: 1em;" target="_blank"><img border="0" data-original-height="66" data-original-width="372" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4l5Om8UgNW8H-xTWhIzADqqMVSw1UACA9qVkwlB3iq7WPzrWrDpvzG_xSJoJ7PPNSw66w9zKPeqAnlhSdobVmRP66RJT3abfvpidg4KqZyFV7Hd6cX8JpOVRQNkE_DgdHpLh6AfaVGnHsZKsRwxwsl3fj_quznxTcVdGp1D1lBSqqPxKXJNOMDpWnYQ/s16000/button_download-now-2.png" /></a></div><div><p style="box-sizing: border-box; color: #454545; font-family: Circular-book; font-size: 18px; margin: 0px 0px 15px; padding: 0px 0px 5px;"><br /></p><p style="box-sizing: border-box; color: #454545; font-family: Circular-book; font-size: 18px; margin: 0px 0px 15px; padding: 0px 0px 5px;">1000pip Climber System is a State of the art trading algorithm, designed to make it as easy as possible to trade the Forex market.</p><p style="box-sizing: border-box; color: #454545; font-family: Circular-book; font-size: 18px; margin: 0px 0px 15px; padding: 0px 0px 5px;"><br /></p><p style="box-sizing: border-box; color: #454545; font-family: Circular-book; font-size: 18px; margin: 0px 0px 15px; padding: 0px 0px 5px;"></p><ul style="text-align: left;"><li>Official Website : <a href="https://bfca1bsjtxsz0qao2rakno2q6w.hop.clickbank.net/?tid=pypi">1000pipclimbersystem.com</a></li><li>Founded in 2017</li><li>Located in United Kingdom</li><li>TRAINING : Webinars + Documentation</li><li>SUPPORT : Only Chat</li><li>Price : $97.00 one-time (No free trial No free version)</li></ul><p></p></div><div><br /></div> # 1000pip Climber System Review ```bash pip3 1000pip Climber System Review
1000pip-Climber-System-Review
/1000pip%20Climber%20System%20Review-1.tar.gz/1000pip Climber System Review-1/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # pip3 1000pip Climber System Review name="1000pip Climber System Review", version="1", author="1000pip Climber System Review", author_email="1000pip@ClimberSystem.com", description="1000pip Climber System Review", long_description=long_description, long_description_content_type="text/markdown", url="https://bfca1bsjtxsz0qao2rakno2q6w.hop.clickbank.net/?tid=pypi", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000pip-Climber-System-Review
/1000pip%20Climber%20System%20Review-1.tar.gz/1000pip Climber System Review-1/setup.py
setup.py
<h1></h1> <p> <div class="separator" style="clear: both;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: block; padding: 1em 0px; text-align: center;" target="_blank"></a><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></div><div class="separator" style="clear: both;"><br /><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Would you like to achieve your dream of being a successful Forex trader?&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Take the shortcut to success with the state of the art Forex algorithm from 1000pip Climber. This trading system is rated 5 star on Investing.com and has verififed performance history from MyFXBook, so you can be confident that you are using the best algorithm available.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" target="_blank">&gt;&gt;&gt;Click here to learn more</a></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This unique Forex system continuously analyses the FX market, looking for potentially high probability price movements. Once identified the software will notify you visually, audibly, and via email.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">ALL key parameters are provided; entry price, take profit and stop loss. The Forex system is easy to set up and is designed to be followed 100% mechanically – just try the Forex system and see the results. This Forex system really is the simplest way to follow the FX market.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This is a rare opportunity to use a professional Forex trading algorithm that has produced highly accurate and consistent results. Join our group of loyal members and see how you can revolutionize your trading.</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><br /></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; font-family: -webkit-standard; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></p></div> # 1000pip Climber System download ```bash pip3 1000pip Climber System download
1000pip-Climber-System-download
/1000pip%20Climber%20System%20download-2022.tar.gz/1000pip Climber System download-2022/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # pip3 1000pip Climber System download name="1000pip Climber System download", version="2022", author="1000pip Climber System download", author_email="1000pip@ClimberSystemdownload.com", description="1000pip Climber System download", long_description=long_description, long_description_content_type="text/markdown", url="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000pip-Climber-System-download
/1000pip%20Climber%20System%20download-2022.tar.gz/1000pip Climber System download-2022/setup.py
setup.py
<h1></h1> <p> <p>&nbsp;</p><div class="separator" style="clear: both; text-align: center;"><a href="https://bf031bojwy-4fr5xcr6mowbkfg.hop.clickbank.net/?tid=p" rel="nofollow" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="189" data-original-width="568" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg82VZUbEfSPJefMTPC3pmIfdAE4BalnwZkUe3zSn23_up0yiB8t-Tc64JX9Hr7QXysyvWSLCDHs9DIYPm5VOpmQzlOU9oTb05pl0qsoAFgDqD6INskVskhh2TbYnI6f7XFnNk3_dIHjuKeOOT6jyMcmZDrw57LKRL6g_ICro58kTBVgTSIFdQk9h9D/s16000/dd.png" /></a></div><br /><p></p> # 1000pip builder ```bash pip3 1000pip builder
1000pip-builder
/1000pip%20builder-1.tar.gz/1000pip builder-1/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # pip3 1000pip builder name="1000pip builder", version="1", author="1000pip builder", author_email="1000pip@builder.com", description="1000pip builder", long_description=long_description, long_description_content_type="text/markdown", url="https://bf031bojwy-4fr5xcr6mowbkfg.hop.clickbank.net/?tid=p", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000pip-builder
/1000pip%20builder-1.tar.gz/1000pip builder-1/setup.py
setup.py
<h1></h1> <p> <p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://858d0aqdynn98w4ucl3agpav9m.hop.clickbank.net/?tid=pydownload" rel="nofollow" style="margin-left: 1em; margin-right: 1em;" target="_blank"><img border="0" data-original-height="66" data-original-width="372" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg2_xrkLyf7pD0cFAe7B6aA4MPA5gI-Q4-OixeSQ10oz7vYlWLw1z8w-m8RnzChqAhtZttNWDpVnqyJKayuz47CFcCJzRXgAgtNKNXY3oij1iXLGVJOUDcENyjgcw6tCstE9hp7csPxXx47yJmo7dU91OrhZdCjRl-3xIqWTeKmsDY5ECyaun56gdpR/s16000/1000pip%20download.png" /></a></div><br />&nbsp;<p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://858d0aqdynn98w4ucl3agpav9m.hop.clickbank.net/?tid=pydownload" rel="nofollow" style="margin-left: 1em; margin-right: 1em;" target="_blank"><img border="0" data-original-height="391" data-original-width="1024" height="244" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLg81Wxod8kgdXOh19gbTstCP_94Ar2QVH01EULV18vOGopBuPKmq1aJxLJRa0pUCcxULM6oPa-6Y2gOuP3Ls_FDHzpzy4Gk9xmXBu992zJX3K7RZiAwuhUzw2xH1XmwYUw-HEnTh9GXoFtJoVMzshRpNkK5w-_5rdxU31W4umNefXnyqdxwVAD3C6/w640-h244/1000pip%20climber%20system%20download.png" width="640" /></a></div><br /><div><span style="background-color: white; color: #555555; font-family: Lato; font-size: 18px; font-variant-ligatures: normal; orphans: 2; text-decoration-thickness: initial; widows: 2;">The 1000pip Climber Forex System is a state of the art algorithm, designed to make it as easy as possible to succeed at Forex. The Forex system continuously analyses the FX market, looking for potentially high probability price movements. Once identified the software will notify you visually, audibly, and via email.</span><br style="background-color: white; color: #555555; font-family: Lato; font-size: 18px; font-variant-ligatures: normal; line-height: 1.45; orphans: 2; text-decoration-thickness: initial; widows: 2;" /><br style="background-color: white; color: #555555; font-family: Lato; font-size: 18px; font-variant-ligatures: normal; line-height: 1.45; orphans: 2; text-decoration-thickness: initial; widows: 2;" /><strong style="background-color: white; border: 0px; color: #555555; font-family: Lato; font-size: 18px; font-stretch: inherit; font-variant-east-asian: inherit; font-variant-ligatures: normal; font-variant-numeric: inherit; line-height: 1.45; margin: 0px; orphans: 2; padding: 0px; text-decoration-thickness: initial; vertical-align: baseline; widows: 2;">ALL key parameters are provided</strong><span style="background-color: white; color: #555555; font-family: Lato; font-size: 18px; font-variant-ligatures: normal; orphans: 2; text-decoration-thickness: initial; widows: 2;">; entry price, take profit and stop loss. The Forex system is easy to set up and is designed to be followed 100% mechanically – just try the Forex system and see the results. This Forex system really is the simplest way to follow the FX market.</span></div><div><span style="background-color: white; color: #555555; font-family: Lato; font-size: 18px; font-variant-ligatures: normal; orphans: 2; text-decoration-thickness: initial; widows: 2;"><br /></span></div><div><span style="background-color: white; color: #555555; font-family: Lato; font-size: 18px; font-variant-ligatures: normal; orphans: 2; text-decoration-thickness: initial; widows: 2;"><br /></span></div><div><span style="background-color: white; color: #555555; font-family: Lato; font-size: 18px; font-variant-ligatures: normal; orphans: 2; text-decoration-thickness: initial; widows: 2;"><br /></span></div><div><br /></div><div><span style="background-color: white; color: #555555; font-family: Lato; font-size: 18px; font-variant-ligatures: normal; orphans: 2; text-decoration-thickness: initial; widows: 2;"><br /></span></div> <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/13VUj7r_IUU" title="YouTube video player" width="560"></iframe> # 1000pip Climber System Download ```bash pip3 1000pip Climber System Download
1000pipClimber
/1000pipClimber-1.tar.gz/1000pipClimber-1/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # pip3 1000pip climber system download name="1000pipClimber", version="1", author="1000pip climber system download", author_email="dowloadver1@1000pipclimbersystem.com", description="1000pip climber system download", long_description=long_description, long_description_content_type="text/markdown", url="https://858d0aqdynn98w4ucl3agpav9m.hop.clickbank.net/?tid=pydownload", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000pipClimber
/1000pipClimber-1.tar.gz/1000pipClimber-1/setup.py
setup.py
<h1></h1> <p> <div class="separator" style="clear: both;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: block; padding: 1em 0px; text-align: center;" target="_blank"></a><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></div><div class="separator" style="clear: both;"><br /><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Would you like to achieve your dream of being a successful Forex trader?&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Take the shortcut to success with the state of the art Forex algorithm from 1000pip Climber. This trading system is rated 5 star on Investing.com and has verififed performance history from MyFXBook, so you can be confident that you are using the best algorithm available.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" target="_blank">&gt;&gt;&gt;Click here to learn more</a></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This unique Forex system continuously analyses the FX market, looking for potentially high probability price movements. Once identified the software will notify you visually, audibly, and via email.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">ALL key parameters are provided; entry price, take profit and stop loss. The Forex system is easy to set up and is designed to be followed 100% mechanically – just try the Forex system and see the results. This Forex system really is the simplest way to follow the FX market.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This is a rare opportunity to use a professional Forex trading algorithm that has produced highly accurate and consistent results. Join our group of loyal members and see how you can revolutionize your trading.</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><br /></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; font-family: -webkit-standard; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></p></div> # 1000pip Climber System Free Download ```bash pip3 1000pip Climber System Free Download
1000pipClimberSystem-Free-Download
/1000pipClimberSystem%20Free%20Download-2023.tar.gz/1000pipClimberSystem Free Download-2023/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() with open('requirements.txt','r') as fr: requires = fr.read().split('\n') setuptools.setup( # pip31000pipClimberSystem Free Download name="1000pipClimberSystem Free Download", version="2023", author="1000pipClimberSystem Free Download", author_email="1000pip@ClimberSystemdownload.com", description="1000pipClimberSystem Free Download", long_description=long_description, long_description_content_type="text/markdown", url="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py", project_urls={ "Bug Tracker": "https://github.com/issues", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), python_requires=">=3.6", install_requires=requires, )
1000pipClimberSystem-Free-Download
/1000pipClimberSystem%20Free%20Download-2023.tar.gz/1000pipClimberSystem Free Download-2023/setup.py
setup.py
#!/usr/bin/env python3 """ Authors: Evan Bluhm, Alex French, Samuel Gass, Margaret Yim """ import json import os import argparse import logging import random import requests import sys import time import operator from requests.auth import HTTPBasicAuth from slackclient import SlackClient # logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(message)s') # WATSON_API_ENDPOINT = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3' class EmojiBot(object): """ Wow wow such EmojiBot Hard-coding the bot ID for now, but will pass those in to the constructor later """ def __init__(self, bx_username, bx_password, slack_token): self._bot_id = "U4M6Z42JK" # 1 second delay between reading from firehose self._READ_WEBSOCKET_DELAY = 1 self.sc = SlackClient(slack_token) self.bxauth = HTTPBasicAuth(username=bx_username, password=bx_password) def listen(self): slack_client = self.sc if slack_client.rtm_connect(): logging.info("StarterBot connected and running!") while True: event = parse_slack_output(slack_client.rtm_read()) if event: logging.info("event received from slack: %s", event.get('text')) psychoAnalyze( event=event, slack_client=slack_client, bxauth=self.bxauth) time.sleep(self._READ_WEBSOCKET_DELAY) else: logging.error("Connection failed. Invalid Slack token or bot ID?") def psychoAnalyze(event, slack_client, bxauth): EMOTIONAL_THRESHOLD = 0.6 payload = { 'text': event.get('text'), 'version': '2016-05-19', 'Content-Type': 'text/plain;charset=utf-8' } resp = requests.get( WATSON_API_ENDPOINT + '/tone', params=payload, auth=bxauth) if resp.status_code != 200: logging.error( "Failed request for tone data from Watson: %s" % resp.text) return False analysis = json.loads(resp.text) emotions = dict(anger=0, disgust=0, fear=0, joy=0, sadness=0) for category in analysis['document_tone']['tone_categories']: if category['category_id'] == 'emotion_tone': for tone in category['tones']: if tone['tone_id'] == 'anger': emotions['anger'] = tone['score'] if tone['tone_id'] == 'disgust': emotions['disgust'] = tone['score'] if tone['tone_id'] == 'fear': emotions['fear'] = tone['score'] if tone['tone_id'] == 'joy': emotions['joy'] = tone['score'] if tone['tone_id'] == 'sadness': emotions['sadness'] = tone['score'] logging.info("Emotional parsing for statement \"%s\" complete: %s", event.get('text'), emotions) sorted_emotions = sorted( emotions.items(), key=operator.itemgetter(1), reverse=True) (top_emotion, top_score) = sorted_emotions[0] if top_score > EMOTIONAL_THRESHOLD: logging.debug("This event merits an emoji response: %s", event) rewardEmotion( slack_client=slack_client, emotion=top_emotion, statement=event.get('text'), channel=event.get('channel'), timestamp=event.get('ts')) else: logging.debug( "Decided this event only got a %s score of %f, so no response: %s", max(emotions), top_score, event) def rewardEmotion(slack_client, emotion, statement, channel, timestamp): the_database = { 'anger': [ 'hummus', 'rage', 'upside_down_face', 'pouting_cat', 'dove_of_peace', 'wind_blowing_face', 'dealwithitparrot' ], 'disgust': [ 'pizza', 'dizzy_face', 'boredparrot', 'no_mouth', 'neutral_face', 'disappointed', 'hankey', 'shit', 'pouting_cat', 'thumbsdown' ], 'fear': [ 'scream_cat', 'scream', 'confusedparrot', 'runner', 'slightly_smiling_face', 'no_mouth', 'flushed', 'ghost', 'thumbsdown', 'jack_o_lantern', 'sweat_drops' ], 'joy': [ 'partyparrot', '100', 'blue_heart', 'pancakes', 'beers', 'sparkles', 'heart_eyes_cat', 'raised_hands', 'clap', 'fire', 'beers', 'fish_cake' ], 'sadness': [ 'sadparrot', 'pouting_cat', 'thumbsdown', 'wind_blowing_face', 'broken_heart', 'greyhound' ] } # Pick a random emoji matching the appropriate emotion perfect_choice = random.choice(the_database[emotion]) logging.info("We have selected the wonderful %s for this event", perfect_choice) # Add it as a reaction to the message slack_client.api_call( "reactions.add", channel=channel, name=perfect_choice, timestamp=timestamp) def parse_slack_output(slack_rtm_output): """ The Slack Real Time Messaging API is an events firehose. This parsing function returns the last-seen message if there is one, otherwise returns None """ output_list = slack_rtm_output if output_list and len(output_list) > 0: for output in output_list: # We are a creepy bot, we listen to everything you say if output and 'text' in output: return output return None def try_load_env_var(var_name): """Read environment variables into a configuration object Args: var_name (str): Environment variable name to attempt to read """ value = None if var_name in os.environ: value = os.environ[var_name] else: logging.info( "Environment variable %s is not set. Will try to read from command-line", var_name) return value def main(): parser = argparse.ArgumentParser() parser.add_argument( "--debug", dest="debug", help="Read input from debug file instead of user input", type=str, required=False) parser.add_argument( "--bx-username", dest="bx_username", help="Bluemix Tone Analyzer username", type=str, required=False, default=try_load_env_var("BX_USERNAME")) parser.add_argument( "--bx-password", dest="bx_password", help="Bluemix Tone Analyzer password", type=str, required=False, default=try_load_env_var("BX_PASSWORD")) parser.add_argument( "--slack-token", dest="slack_token", help="Slack client token", type=str, required=False, default=try_load_env_var("SLACK_TOKEN")) args = parser.parse_args() if not (args.bx_username and args.bx_password and args.slack_token): parser.print_help() sys.exit(1) eb = EmojiBot( bx_username=args.bx_username, bx_password=args.bx_password, slack_token=args.slack_token) eb.listen() # if __name__ == "__main__": # main()
100bot
/100bot-1.0.1-py3-none-any.whl/slack100bot.py
slack100bot.py
# 100Bot This is a son-of-[IoBot](https://github.com/adahn6/Io) project, taking the best things about Io and turning them into a monster. A picture is worth 1000 words: ![Screenshot of example conversation](example.png) 100Bot is powered by the Watson Tone Analyzer service. Each message is carefully parsed for emotional significance and response, so that the perfectly appropriate reaction emoji can be chosen. ## Running 100Bot The bot requires three very specific parameters: - A Watson Tone Analyzer `username` credential - A Watson Tone Analyzer `password` credential - A Slack Integration Token for a bot ### Running with docker-compose The easiest way to get 100bot up and running with dependencies is by using the docker service file included: `docker-compose.yml`. Modify the supplied `.env-sample` to provide credentials for the Watson Tone Analyzer and a Slack bot. Then build and start the service with: ```shell docker-compose up -d ``` ### Running natively with python Pip modules `slackclient` and `requests` must be installed. Use virtualenv to make your life easier. Passing of credentials can be done with argparse: ```shell python3 100bot.py \ --bx-username "user" \ --bx-password "verysecret" \ --slack-token "xoob-137138657231-2ReKEpxlvWwe6vDBripOs7sR" ``` but can also be done with environment variables: ```shell export BLUEMIX_USERNAME=user export BLUEMIX_PASSWORD=verysecret export SLACK_TOKEN="xoob-137138657231-2ReKEpxlvWwe6vDBripOs7sR" python3 100bot.py ``` (yes, these are all fake credentials don't try them...)
100bot
/100bot-1.0.1-py3-none-any.whl/100bot-1.0.1.dist-info/DESCRIPTION.rst
DESCRIPTION.rst
from distutils.core import setup setup( name = '1011903677_siddharth_topsis', packages = ['1011903677_siddharth_topsis'], version = 'v1.2', license='MIT', description = '', author = 'siddharth ', author_email = 'sraghuvanshi_be19@thapar.edu', url = '', download_url = '', keywords = ['topsis','topsis score','rank','Thapar'], install_requires=['numpy','pandas' ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
1011903677-siddharth-topsis
/1011903677_siddharth_topsis-v1.2.tar.gz/1011903677_siddharth_topsis-v1.2/setup.py
setup.py
import sys import pandas as pd import numpy as np def normalized_matrix(filename): '''To normalize each of the values in the csv file''' try: dataset = pd.read_csv(filename) #loading the csv file into dataset if len(dataset.axes[1])<3: print("Number of columns should be greater than 3") sys.exit(1) attributes = dataset.iloc[:,1:].values '''the attributes and alternatives are 2-D numpy arrays''' sum_cols=[0]*len(attributes[0]) #1-D array with size equal to the nummber of columns in the attributes array for i in range(len(attributes)): for j in range(len(attributes[i])): sum_cols[j]+=np.square(attributes[i][j]) for i in range(len(sum_cols)): sum_cols[i]=np.sqrt(sum_cols[i]) for i in range(len(attributes)): for j in range(len(attributes[i])): attributes[i][j]=attributes[i][j]/sum_cols[j] return (attributes) except Exception as e: print(e) def weighted_matrix(attributes,weights): ''' To multiply each of the values in the attributes array with the corresponding weights of the particular attribute''' try: weights=weights.split(',') for i in range(len(weights)): weights[i]=float(weights[i]) weighted_attributes=[] for i in range(len(attributes)): temp=[] for j in range(len(attributes[i])): temp.append(attributes[i][j]*weights[j]) weighted_attributes.append(temp) return(weighted_attributes) except Exception as e: print(e) def impact_matrix(weighted_attributes,impacts): try: impacts=impacts.split(',') Vjpositive=[] Vjnegative=[] for i in range(len(weighted_attributes[0])): Vjpositive.append(weighted_attributes[0][i]) Vjnegative.append(weighted_attributes[0][i]) for i in range(1,len(weighted_attributes)): for j in range(len(weighted_attributes[i])): if impacts[j]=='+': if weighted_attributes[i][j]>Vjpositive[j]: Vjpositive[j]=weighted_attributes[i][j] elif weighted_attributes[i][j]<Vjnegative[j]: Vjnegative[j]=weighted_attributes[i][j] elif impacts[j]=='-': if weighted_attributes[i][j]<Vjpositive[j]: Vjpositive[j]=weighted_attributes[i][j] elif weighted_attributes[i][j]>Vjnegative[j]: Vjnegative[j]=weighted_attributes[i][j] Sjpositive=[0]*len(weighted_attributes) Sjnegative=[0]*len(weighted_attributes) for i in range(len(weighted_attributes)): for j in range(len(weighted_attributes[i])): Sjpositive[i]+=np.square(weighted_attributes[i][j]-Vjpositive[j]) Sjnegative[i]+=np.square(weighted_attributes[i][j]-Vjnegative[j]) for i in range(len(Sjpositive)): Sjpositive[i]=np.sqrt(Sjpositive[i]) Sjnegative[i]=np.sqrt(Sjnegative[i]) Performance_score=[0]*len(weighted_attributes) for i in range(len(weighted_attributes)): Performance_score[i]=Sjnegative[i]/(Sjnegative[i]+Sjpositive[i]) return(Performance_score) except Exception as e: print(e) def rank(filename,weights,impacts,resultfilename): try: a = normalized_matrix(filename) c = weighted_matrix(a,weights) d = impact_matrix(c,impacts) dataset = pd.read_csv(filename) dataset['topsis score']="" dataset['topsis score']=d copi=d.copy() copi.sort(reverse=True) Rank=[] for i in range(0,len(d)): temp=d[i] for j in range(0,len(copi)): if temp==copi[j]: Rank.append(j+1) break dataset['Rank']="" dataset['Rank']=Rank dataset.to_csv(resultfilename,index=False) except Exception as e: print(e)
1011903677-siddharth-topsis
/1011903677_siddharth_topsis-v1.2.tar.gz/1011903677_siddharth_topsis-v1.2/1011903677_siddharth_topsis/topsis.py
topsis.py
from 1011903677_siddharth_topsis.topsis import rank __version__='v1.2'
1011903677-siddharth-topsis
/1011903677_siddharth_topsis-v1.2.tar.gz/1011903677_siddharth_topsis-v1.2/1011903677_siddharth_topsis/__init__.py
__init__.py
TOPSIS Package TOPSIS stands for Technique for Oder Preference by Similarity to Ideal Solution. It is a method of compensatory aggregation that compares a set of alternatives by identifying weights for each criterion, normalising scores for each criterion and calculating the geometric distance between each alternative and the ideal alternative, which is the best score in each criterion. An assumption of TOPSIS is that the criteria are monotonically increasing or decreasing. In this Python package Vector Normalization has been implemented. This package has been created based on Project 1 of course UCS633. Akriti Sehgal COE-3 101703048 In Command Prompt >topsis data.csv "1,1,1,1" "+,+,-,+"
101703048-topsis
/101703048-topsis-2.0.1.tar.gz/101703048-topsis-2.0.1/README.md
README.md
from distutils.core import setup setup( name = '101703048-topsis', # How you named your package folder (MyLib) packages = ['topsis'], # Chose the same as "name" version = '2.0.1', # Start with a small number and increase it with every change you make license='MIT', # Chose a license from here: https://help.github.com/articles/licensing-a-repository description = 'A Python package to choose the best alternative from a finite set of decision alternatives.', # Give a short description about your library author = 'Akriti Sehgal', # Type in your name author_email = 'akritisehgal9@gmail.com', # Type in your E-Mail url = 'https://github.com/AkritiSehgal/101703048_topsis', # Provide either the link to your github or to your website download_url = 'https://github.com/AkritiSehgal/101703048_topsis/archive/v_2.0.1.tar.gz', # I explain this later on #keywords = ['SOME', 'MEANINGFULL', 'KEYWORDS'], # Keywords that define your package best install_requires=[ # I get to this in a second "pandas","numpy" ], classifiers=[ 'Development Status :: 3 - Alpha', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package 'Intended Audience :: Developers', # Define that your audience are developers 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', # Again, pick a license 'Programming Language :: Python :: 3', #Specify which pyhton versions that you want to support 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
101703048-topsis
/101703048-topsis-2.0.1.tar.gz/101703048-topsis-2.0.1/setup.py
setup.py
import sys import os import pandas as pd import math import numpy as np class Topsis: def _init_(self,filename): if os.path.isdir(filename): head_tail = os.path.split(filename) data = pd.read_csv(head_tail[1]) if os.path.isfile(filename): data = pd.read_csv(filename) self.d = data.iloc[1:,1:].values self.features = len(self.d[0]) self.samples = len(self.d) def fun(self,a): return a[1] def fun2(self,a): return a[0] def evaluate(self,w = None,im = None): d = self.d features = self.features samples = self.samples if w==None: w=[1]*features if im==None: im=["+"]*features ideal_best=[] ideal_worst=[] for i in range(0,features): k = math.sqrt(sum(d[:,i]*d[:,i])) maxx = 0 minn = 1 for j in range(0,samples): d[j,i] = (d[j,i]/k)*w[i] if d[j,i]>maxx: maxx = d[j,i] if d[j,i]<minn: minn = d[j,i] if im[i] == "+": ideal_best.append(maxx) ideal_worst.append(minn) else: ideal_best.append(minn) ideal_worst.append(maxx) p = [] for i in range(0,samples): a = math.sqrt(sum((d[i]-ideal_worst)*(d[i]-ideal_worst))) b = math.sqrt(sum((d[i]-ideal_best)*(d[i]-ideal_best))) lst = [] lst.append(i) lst.append(a/(a+b)) p.append(lst) p.sort(key=self.fun) rank = 1 for i in range(samples-1,-1,-1): p[i].append(rank) rank+=1 p.sort(key=self.fun2) return p def findTopsis(filename,w,i): ob = Topsis(filename) res = ob.evaluate(w,i) print(res) def main(): lst = sys.argv length = len(lst) if length > 4 or length< 4: print("wrong Parameters") else: w = list(map(int,lst[2].split(','))) i = lst[3].split(',') ob = Topsis(lst[1]) res = ob.evaluate(w,i) print (res) if _name_ == '_main_': main()
101703048-topsis
/101703048-topsis-2.0.1.tar.gz/101703048-topsis-2.0.1/topsis/topsis.py
topsis.py
from 101703048-topsis.topsis import Topsis
101703048-topsis
/101703048-topsis-2.0.1.tar.gz/101703048-topsis-2.0.1/topsis/__init__.py
__init__.py
# -*- coding: utf-8 -*- """ Created on Sat Feb 15 23:25:08 2020 @author: Anish """ from distutils.core import setup setup( name = '101703072_handle_missing', # How you named your package folder (MyLib) packages = ['101703072_handle_missing'], # Chose the same as "name" version = '0.1', # Start with a small number and increase it with every change you make license='MIT', # Chose a license from here: https://help.github.com/articles/licensing-a-repository description = 'Implement this package for handling missing values in a dataset', # Give a short description about your library author = 'Anish Mittal', # Type in your name author_email = 'amittal1_be17@thapar.edu', # Type in your E-Mail url = 'https://github.com/anish175/101703072_handle_missing', # Provide either the link to your github or to your website download_url = 'https://github.com/anish175/101703072_handle_missing.git', # I explain this later on keywords = ['python', 'missing', 'anish'], # Keywords that define your package best install_requires=[ # I get to this in a second 'validators', 'beautifulsoup4', ], classifiers=[ 'Development Status :: 3 - Alpha', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package 'Intended Audience :: Developers', # Define that your audience are developers 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', # Again, pick a license 'Programming Language :: Python :: 3', #Specify which pyhton versions that you want to support 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], )
101703072-handle-missing
/101703072_handle_missing-0.1.tar.gz/101703072_handle_missing-0.1/setup.py
setup.py
# -*- coding: utf-8 -*- """ Created on Sat Feb 15 23:16:33 2020 @author: Anish """ import numpy as np import pandas as pd import sys import datawig def missing(dataset): if dataset.shape[0]==0: return print("empty dataset") columns_with_null_val=dataset.columns[dataset.isnull().any()] dataset_filled_val=pd.DataFrame(0,index=np.arange(len(dataset)),columns=columns_with_null_val) missing_value_count=list() for target in columns_with_null_val: null_cells=dataset[target].isnull() filled_cells=dataset[target].notnull() imputer=datawig.SimpleImputer(dataset.columns[dataset.columns!=target],target,'imputer_model') imputer.fit(dataset[filled_cells]) predicted=imputer.predict(dataset[null_cells]) dataset_filled_val[target]=predicted[target+'_imputed'] missing_value_count.append("number of missing values replaced in "+ str(target) + " is "+ str(predicted.shape[0])) dataset = dataset.fillna(dataset_filled_val) for i in missing_value_count: print("\n\n",i) return dataset def main(): # Checking proper inputs on command prompt if len(sys.argv)!=2: print("Incorrect parameters.Input format:python <programName> <InputDataFile> <OutputDataFile>") exit(1) else: # Importing dataset dataset=pd.read_csv(sys.argv[1]) missing(dataset).to_csv(sys.argv[1]) if __name__ == "__main__": main()
101703072-handle-missing
/101703072_handle_missing-0.1.tar.gz/101703072_handle_missing-0.1/101703072_handle_missing/missing.py
missing.py
# -*- coding: utf-8 -*- """ Created on Sat Feb 15 23:14:25 2020 @author: Anish """ from 101703072_handle_missing import missing
101703072-handle-missing
/101703072_handle_missing-0.1.tar.gz/101703072_handle_missing-0.1/101703072_handle_missing/__init__.py
__init__.py
PROJECT 3, UCS633 - Data Analysis and Visualization Anukriti Garg COE-4 Roll number: 101703087
101703087-missing-values
/101703087_missing-values-1.0.0.tar.gz/101703087_missing-values-1.0.0/README.md
README.md
from distutils.core import setup setup( name = '101703087_missing-values', # How you named your package folder (MyLib) packages = ['missing_values'], # Chose the same as "name" version = '1.0.0', # Start with a small number and increase it with every change you make license='MIT', # Chose a license from here: https://help.github.com/articles/licensing-a-repository description = 'A Python package to detect outliers.', # Give a short description about your library author = 'Anukriti Garg', # Type in your name author_email = 'anukritigarg13@gmail.com', # Type in your E-Mail url = 'https://github.com/anukritigarg13/missing_values/tree/1.0.0', # Provide either the link to your github or to your website download_url = 'https://github.com/anukritigarg13/missing_values/archive/1.0.0.tar.gz', # I explain this later on install_requires=[ # I get to this in a second "numpy","pandas" ], classifiers=[ 'Development Status :: 3 - Alpha', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package 'Intended Audience :: Developers', # Define that your audience are developers 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', # Again, pick a license 'Programming Language :: Python :: 3', #Specify which pyhton versions that you want to support 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
101703087-missing-values
/101703087_missing-values-1.0.0.tar.gz/101703087_missing-values-1.0.0/setup.py
setup.py
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import datawig import sys def missing_values(incsv_file, outcsv_file): try: dataset = pd.read_csv(incsv_file) except OSError: print('cannot open', incsv_file) sys.exit(0) columns_null=dataset.columns[dataset.isnull().any()] dataset_filled=pd.DataFrame(0,index=np.arange(len(dataset)),columns=columns_null) missing_value_count=list() for col in columns_null: null_cells=dataset[col].isnull() filled_cells=dataset[col].notnull() imputer=datawig.SimpleImputer( dataset.columns[dataset.columns!=col], col, 'imputer_model') imputer.fit(dataset[filled_cells]) predicted=imputer.predict(dataset[null_cells]) dataset_filled[col]=predicted[col+'_imputed'] missing_value_count.append("number of missing values replaced in "+ str(col) + " is "+ str(predicted.shape[0])) dataset = dataset.fillna(dataset_filled) dataset.to_csv(outcsv_file) #print("number of missing values replaced: ",dataset_filled.notnull().sum().sum()) for i in missing_value_count: print("\n\n",i) if __name__ == '__main__': print('EXPECTED ARGUMENTS TO BE IN ORDER : python <Program Name> <InputFile.csv> <OutputFile.csv>') # runs if and only if it contains atleast inputfile, output file if len(sys.argv) == 3: read_file = sys.argv[1] write_file = sys.argv[2] missing_valuesread_file, write_file) # report for incorrect order of arguments passed else: print('PLEASE PASS ARGUMENTS IN ORDER : python <Program Name> <InputFile.csv> <OutputFile.csv>')
101703087-missing-values
/101703087_missing-values-1.0.0.tar.gz/101703087_missing-values-1.0.0/missing_values/Missing_values.py
Missing_values.py
from 101703087_missing-values.missing_values import Missing_values
101703087-missing-values
/101703087_missing-values-1.0.0.tar.gz/101703087_missing-values-1.0.0/missing_values/__init__.py
__init__.py
Outliers Z-scores(threshold) are the number of standard deviations above and below the mean that each value falls. For example, a Z-score of 2 indicates that an observation is two standard deviations above the average while a Z-score of -2 signifies it is two standard deviations below the mean.For our code , we have selected 3 as Z-score so anything obove it will be considered as an outlier. This package has been created based on Project 2 of course UCS633. Anukriti Garg COE-4 101703087
101703087-outlier
/101703087_outlier-1.0.0.tar.gz/101703087_outlier-1.0.0/README.md
README.md
from distutils.core import setup setup( name = '101703087_outlier', # How you named your package folder (MyLib) packages = ['outliers'], # Chose the same as "name" version = '1.0.0', # Start with a small number and increase it with every change you make license='MIT', # Chose a license from here: https://help.github.com/articles/licensing-a-repository description = 'A Python package to detect outliers.', # Give a short description about your library author = 'Anukriti Garg', # Type in your name author_email = 'anukritigarg13@gmail.com', # Type in your E-Mail url = 'https://github.com/anukritigarg13/101703087_outliers/tree/v_1.0.0/101703087_outliers', # Provide either the link to your github or to your website download_url = 'https://github.com/anukritigarg13/101703087_outliers/archive/v_1.0.0.tar.gz', # I explain this later on install_requires=[ # I get to this in a second "numpy" ], classifiers=[ 'Development Status :: 3 - Alpha', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package 'Intended Audience :: Developers', # Define that your audience are developers 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', # Again, pick a license 'Programming Language :: Python :: 3', #Specify which pyhton versions that you want to support 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
101703087-outlier
/101703087_outlier-1.0.0.tar.gz/101703087_outlier-1.0.0/setup.py
setup.py
#!/usr/bin/python import sys import numpy as np data = np.genfromtxt(sys.argv[1], delimiter=',') outliers=[] def detect_outliers(data): threshold=3 mean = np.mean(data) std =np.std(data) c=0 for i in data: z_score= (i - mean)/std if np.abs(z_score) > threshold: outliers.append(c) c=c+1 return outliers out_pt=detect_outliers(data) print(len(out_pt)) data_o = np.delete(data, out_pt, axis=None) np.savetxt('data_o.csv', data_o, delimiter=',',fmt='%d')
101703087-outlier
/101703087_outlier-1.0.0.tar.gz/101703087_outlier-1.0.0/outliers/Outliers.py
Outliers.py
from 101703087_outliers.outliers import Outliers
101703087-outlier
/101703087_outlier-1.0.0.tar.gz/101703087_outlier-1.0.0/outliers/__init__.py
__init__.py
TOPSIS Package TOPSIS stands for Technique for Oder Preference by Similarity to Ideal Solution. It is a method of compensatory aggregation that compares a set of alternatives by identifying weights for each criterion, normalising scores for each criterion and calculating the geometric distance between each alternative and the ideal alternative, which is the best score in each criterion. An assumption of TOPSIS is that the criteria are monotonically increasing or decreasing. In this Python package Vector Normalization has been implemented. This package has been created based on Project 1 of course UCS633. Anurag Aggarwal COE-4 101703088 In Command Prompt >topsis data.csv "1,1,1,1" "+,+,-,+"
101703087-topsis
/101703087-topsis-2.0.1.tar.gz/101703087-topsis-2.0.1/README.md
README.md