body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
85cca5172a15971100e8036a8282fadd517ab02cda926c1b8dac01fcec671fcb
def load_best_model(self): 'Load best model.' torch.cuda.empty_cache() self._model.load_state_dict(torch.load((self._path / 'best.model')))
Load best model.
sastvd/helpers/ml.py
load_best_model
davidhin/linevd
13
python
def load_best_model(self): torch.cuda.empty_cache() self._model.load_state_dict(torch.load((self._path / 'best.model')))
def load_best_model(self): torch.cuda.empty_cache() self._model.load_state_dict(torch.load((self._path / 'best.model')))<|docstring|>Load best model.<|endoftext|>
ec534cff548060a95fd26388847635ad1523b8fab9331ee4a3ccdac7b0ecb55e
def save_logger(self): 'Save class attributes.' with open((self._path / 'log.pkl'), 'wb') as f: f.write(pkl.dumps(dict([(i, getattr(self, i)) for i in self.save_attrs]))) with open((self._path / 'current.model'), 'wb') as f: torch.save(self._model.state_dict(), f)
Save class attributes.
sastvd/helpers/ml.py
save_logger
davidhin/linevd
13
python
def save_logger(self): with open((self._path / 'log.pkl'), 'wb') as f: f.write(pkl.dumps(dict([(i, getattr(self, i)) for i in self.save_attrs]))) with open((self._path / 'current.model'), 'wb') as f: torch.save(self._model.state_dict(), f)
def save_logger(self): with open((self._path / 'log.pkl'), 'wb') as f: f.write(pkl.dumps(dict([(i, getattr(self, i)) for i in self.save_attrs]))) with open((self._path / 'current.model'), 'wb') as f: torch.save(self._model.state_dict(), f)<|docstring|>Save class attributes.<|endoftext|>
ce7e9ecbf41d4f27b82780b8427c708492169cc6846f2614876e2bfb90e76d05
def load_logger(self): 'Load class attributes.' with open((self._path / 'log.pkl'), 'rb') as f: attrs = pkl.load(f) for (k, v) in attrs.items(): setattr(self, k, v) torch.cuda.empty_cache() self._model.load_state_dict(torch.load((self._path / 'current.model')))
Load class attributes.
sastvd/helpers/ml.py
load_logger
davidhin/linevd
13
python
def load_logger(self): with open((self._path / 'log.pkl'), 'rb') as f: attrs = pkl.load(f) for (k, v) in attrs.items(): setattr(self, k, v) torch.cuda.empty_cache() self._model.load_state_dict(torch.load((self._path / 'current.model')))
def load_logger(self): with open((self._path / 'log.pkl'), 'rb') as f: attrs = pkl.load(f) for (k, v) in attrs.items(): setattr(self, k, v) torch.cuda.empty_cache() self._model.load_state_dict(torch.load((self._path / 'current.model')))<|docstring|>Load class attributes.<|endoftext|>
1e7a976fb0d19a3d107fcad9013e74e75f58e74776115ce03c0b0d08d20a2693
async def _start(self) -> None: "Start the worker.\n\n Handles initializing a connection & creating a channel,\n then uses aio-pika's RPC.create to create a new worker,\n & finally registers every route created by the user.\n " self.logger.info(f'Starting {self.worker_name}...') (host, port, self._connection, self._channel) = (await connect(self._connection_params)) build_route = (await self._pre_start()) (await asyncio.gather(*[build_route(route) for route in self._routes])) self.logger.info(f'Worker waiting for tasks from {host}:{port}')
Start the worker. Handles initializing a connection & creating a channel, then uses aio-pika's RPC.create to create a new worker, & finally registers every route created by the user.
amqp_worker/worker_base.py
_start
cheese-drawer/lib-python-amqp-worker
0
python
async def _start(self) -> None: "Start the worker.\n\n Handles initializing a connection & creating a channel,\n then uses aio-pika's RPC.create to create a new worker,\n & finally registers every route created by the user.\n " self.logger.info(f'Starting {self.worker_name}...') (host, port, self._connection, self._channel) = (await connect(self._connection_params)) build_route = (await self._pre_start()) (await asyncio.gather(*[build_route(route) for route in self._routes])) self.logger.info(f'Worker waiting for tasks from {host}:{port}')
async def _start(self) -> None: "Start the worker.\n\n Handles initializing a connection & creating a channel,\n then uses aio-pika's RPC.create to create a new worker,\n & finally registers every route created by the user.\n " self.logger.info(f'Starting {self.worker_name}...') (host, port, self._connection, self._channel) = (await connect(self._connection_params)) build_route = (await self._pre_start()) (await asyncio.gather(*[build_route(route) for route in self._routes])) self.logger.info(f'Worker waiting for tasks from {host}:{port}')<|docstring|>Start the worker. Handles initializing a connection & creating a channel, then uses aio-pika's RPC.create to create a new worker, & finally registers every route created by the user.<|endoftext|>
ef49861f1bf024c931e306e1bda079a25884707792c26dd78ce35e9b896891dc
async def _stop(self) -> None: "Defers to aio-pika.Connection's close method." self.logger.info('Worker stopping...') (await self._connection.close())
Defers to aio-pika.Connection's close method.
amqp_worker/worker_base.py
_stop
cheese-drawer/lib-python-amqp-worker
0
python
async def _stop(self) -> None: self.logger.info('Worker stopping...') (await self._connection.close())
async def _stop(self) -> None: self.logger.info('Worker stopping...') (await self._connection.close())<|docstring|>Defers to aio-pika.Connection's close method.<|endoftext|>
5971fc6ee85b088cbee74322d0d805ca1387703aa0504eff7e6d76218847fc60
def route(self, path: str) -> Callable[([RouteHandler], None)]: "Add new 'route' (consumer queue) to the worker with this Decorator.\n\n Similar to creating a route in Flask, this method listens on a given\n 'path' (queue name) & executes the given handler (callback) when a\n message is received in that queue.\n\n Returns the data returned by the decorated function, wrapped in a\n Response object. Not all Worker types will use this response, but\n any Worker that doesn't will simply ignore the return value.\n " self.logger.debug(f'Begin processing route decorator with given path: {path}') def wrap_handler(path: str, handler: RouteHandler) -> RouteHandler: async def wrapped(data: Any) -> Response: self.logger.info(f'TASK RECEIVED {path}') response: Response try: result = (await handler(data)) response = OkResponse(result) except Exception as err: response = ErrResponse(err) self.logger.info(f'TASK COMPLETED {path}: {repr(response)}') return response return wrapped def decorate_route(handler: RouteHandler) -> None: if inspect.iscoroutinefunction(handler): new_route = Route(path=path, handler=wrap_handler(path, handler)) self.logger.debug(f'Created new route: {new_route}') self._routes.append(new_route) self.logger.debug(f'Pushed new route to _routes: {self._routes}') else: raise TypeError(f'Handler {handler} must be a coroutine function') return decorate_route
Add new 'route' (consumer queue) to the worker with this Decorator. Similar to creating a route in Flask, this method listens on a given 'path' (queue name) & executes the given handler (callback) when a message is received in that queue. Returns the data returned by the decorated function, wrapped in a Response object. Not all Worker types will use this response, but any Worker that doesn't will simply ignore the return value.
amqp_worker/worker_base.py
route
cheese-drawer/lib-python-amqp-worker
0
python
def route(self, path: str) -> Callable[([RouteHandler], None)]: "Add new 'route' (consumer queue) to the worker with this Decorator.\n\n Similar to creating a route in Flask, this method listens on a given\n 'path' (queue name) & executes the given handler (callback) when a\n message is received in that queue.\n\n Returns the data returned by the decorated function, wrapped in a\n Response object. Not all Worker types will use this response, but\n any Worker that doesn't will simply ignore the return value.\n " self.logger.debug(f'Begin processing route decorator with given path: {path}') def wrap_handler(path: str, handler: RouteHandler) -> RouteHandler: async def wrapped(data: Any) -> Response: self.logger.info(f'TASK RECEIVED {path}') response: Response try: result = (await handler(data)) response = OkResponse(result) except Exception as err: response = ErrResponse(err) self.logger.info(f'TASK COMPLETED {path}: {repr(response)}') return response return wrapped def decorate_route(handler: RouteHandler) -> None: if inspect.iscoroutinefunction(handler): new_route = Route(path=path, handler=wrap_handler(path, handler)) self.logger.debug(f'Created new route: {new_route}') self._routes.append(new_route) self.logger.debug(f'Pushed new route to _routes: {self._routes}') else: raise TypeError(f'Handler {handler} must be a coroutine function') return decorate_route
def route(self, path: str) -> Callable[([RouteHandler], None)]: "Add new 'route' (consumer queue) to the worker with this Decorator.\n\n Similar to creating a route in Flask, this method listens on a given\n 'path' (queue name) & executes the given handler (callback) when a\n message is received in that queue.\n\n Returns the data returned by the decorated function, wrapped in a\n Response object. Not all Worker types will use this response, but\n any Worker that doesn't will simply ignore the return value.\n " self.logger.debug(f'Begin processing route decorator with given path: {path}') def wrap_handler(path: str, handler: RouteHandler) -> RouteHandler: async def wrapped(data: Any) -> Response: self.logger.info(f'TASK RECEIVED {path}') response: Response try: result = (await handler(data)) response = OkResponse(result) except Exception as err: response = ErrResponse(err) self.logger.info(f'TASK COMPLETED {path}: {repr(response)}') return response return wrapped def decorate_route(handler: RouteHandler) -> None: if inspect.iscoroutinefunction(handler): new_route = Route(path=path, handler=wrap_handler(path, handler)) self.logger.debug(f'Created new route: {new_route}') self._routes.append(new_route) self.logger.debug(f'Pushed new route to _routes: {self._routes}') else: raise TypeError(f'Handler {handler} must be a coroutine function') return decorate_route<|docstring|>Add new 'route' (consumer queue) to the worker with this Decorator. Similar to creating a route in Flask, this method listens on a given 'path' (queue name) & executes the given handler (callback) when a message is received in that queue. Returns the data returned by the decorated function, wrapped in a Response object. Not all Worker types will use this response, but any Worker that doesn't will simply ignore the return value.<|endoftext|>
aa1d0f77d4b5b516b1db733a5e8b8f9020f2d663a8cb2ba2b2257847a139811c
async def run(self) -> Callable[([], Awaitable[None])]: 'Start the RPC Worker.\n\n Must be called inside an asyncio event loop, such as\n `run_until_complete(run())`.\n ' (await self._start()) return self._stop
Start the RPC Worker. Must be called inside an asyncio event loop, such as `run_until_complete(run())`.
amqp_worker/worker_base.py
run
cheese-drawer/lib-python-amqp-worker
0
python
async def run(self) -> Callable[([], Awaitable[None])]: 'Start the RPC Worker.\n\n Must be called inside an asyncio event loop, such as\n `run_until_complete(run())`.\n ' (await self._start()) return self._stop
async def run(self) -> Callable[([], Awaitable[None])]: 'Start the RPC Worker.\n\n Must be called inside an asyncio event loop, such as\n `run_until_complete(run())`.\n ' (await self._start()) return self._stop<|docstring|>Start the RPC Worker. Must be called inside an asyncio event loop, such as `run_until_complete(run())`.<|endoftext|>
764af12525c5cc79f20c74bca384d7db07693adc8813617c1f26c10b76407102
def checkBannedTags(self): '\n Check for banned hashtags using included dictionary dict.txt\n :return:\n ' with open('dict.txt') as dictFile: dictionary = dictFile.readlines() dictionary = [word.rstrip('\n') for word in dictionary] dictSet = set(dictionary) for item in self.items: try: text = item['caption']['text'] hashtags = {tag.strip('#') for tag in text.split() if tag.startswith('#')} result = hashtags.intersection(dictSet) if (len(result) != 0): print((('===========Post code: ' + item['code']) + '=============')) print(hashtags) print('Found banned hashtags:') print(result) except TypeError: _ self.countHashtags(hashtags) print('========All posts successfully checked========')
Check for banned hashtags using included dictionary dict.txt :return:
main.py
checkBannedTags
tiffany-matsuda/Instagram-API-python
0
python
def checkBannedTags(self): '\n Check for banned hashtags using included dictionary dict.txt\n :return:\n ' with open('dict.txt') as dictFile: dictionary = dictFile.readlines() dictionary = [word.rstrip('\n') for word in dictionary] dictSet = set(dictionary) for item in self.items: try: text = item['caption']['text'] hashtags = {tag.strip('#') for tag in text.split() if tag.startswith('#')} result = hashtags.intersection(dictSet) if (len(result) != 0): print((('===========Post code: ' + item['code']) + '=============')) print(hashtags) print('Found banned hashtags:') print(result) except TypeError: _ self.countHashtags(hashtags) print('========All posts successfully checked========')
def checkBannedTags(self): '\n Check for banned hashtags using included dictionary dict.txt\n :return:\n ' with open('dict.txt') as dictFile: dictionary = dictFile.readlines() dictionary = [word.rstrip('\n') for word in dictionary] dictSet = set(dictionary) for item in self.items: try: text = item['caption']['text'] hashtags = {tag.strip('#') for tag in text.split() if tag.startswith('#')} result = hashtags.intersection(dictSet) if (len(result) != 0): print((('===========Post code: ' + item['code']) + '=============')) print(hashtags) print('Found banned hashtags:') print(result) except TypeError: _ self.countHashtags(hashtags) print('========All posts successfully checked========')<|docstring|>Check for banned hashtags using included dictionary dict.txt :return:<|endoftext|>
243c0d316bf80a6a38df3e5ab1ce401124b2153363a9d8c785f0a3a0e669ebd9
def countHashtags(self, hashtags): '\n Adding/updating hashtags to the hashtag dictionary\n :param hashtags: set of hashtags of a post\n :return:\n ' for hashtag in hashtags: if (hashtag not in self.hashDict.keys()): self.hashDict.update({hashtag: 1}) else: self.hashDict.update({hashtag: (self.hashDict[hashtag] + 1)})
Adding/updating hashtags to the hashtag dictionary :param hashtags: set of hashtags of a post :return:
main.py
countHashtags
tiffany-matsuda/Instagram-API-python
0
python
def countHashtags(self, hashtags): '\n Adding/updating hashtags to the hashtag dictionary\n :param hashtags: set of hashtags of a post\n :return:\n ' for hashtag in hashtags: if (hashtag not in self.hashDict.keys()): self.hashDict.update({hashtag: 1}) else: self.hashDict.update({hashtag: (self.hashDict[hashtag] + 1)})
def countHashtags(self, hashtags): '\n Adding/updating hashtags to the hashtag dictionary\n :param hashtags: set of hashtags of a post\n :return:\n ' for hashtag in hashtags: if (hashtag not in self.hashDict.keys()): self.hashDict.update({hashtag: 1}) else: self.hashDict.update({hashtag: (self.hashDict[hashtag] + 1)})<|docstring|>Adding/updating hashtags to the hashtag dictionary :param hashtags: set of hashtags of a post :return:<|endoftext|>
23967e0a75b31fbc12b41668594f6ec142acc5b3b73d140007f376ed96632600
def getFirstComment(self) -> str: '\n Get First comment of the post\n :return: First comment text\n ' media_id = self.item['id'] has_more_comments = True max_id = '' comments = [] while has_more_comments: _ = api.getMediaComments(media_id, max_id=max_id) for c in reversed(api.LastJson['comments']): comments.append(c) has_more_comments = api.LastJson.get('has_more_comments', False) if has_more_comments: max_id = json.loads(api.LastJson.get('next_max_id', ''))['server_cursor'] if (len(comments) >= self.item['comment_count']): has_more_comments = False return ''
Get First comment of the post :return: First comment text
main.py
getFirstComment
tiffany-matsuda/Instagram-API-python
0
python
def getFirstComment(self) -> str: '\n Get First comment of the post\n :return: First comment text\n ' media_id = self.item['id'] has_more_comments = True max_id = comments = [] while has_more_comments: _ = api.getMediaComments(media_id, max_id=max_id) for c in reversed(api.LastJson['comments']): comments.append(c) has_more_comments = api.LastJson.get('has_more_comments', False) if has_more_comments: max_id = json.loads(api.LastJson.get('next_max_id', ))['server_cursor'] if (len(comments) >= self.item['comment_count']): has_more_comments = False return
def getFirstComment(self) -> str: '\n Get First comment of the post\n :return: First comment text\n ' media_id = self.item['id'] has_more_comments = True max_id = comments = [] while has_more_comments: _ = api.getMediaComments(media_id, max_id=max_id) for c in reversed(api.LastJson['comments']): comments.append(c) has_more_comments = api.LastJson.get('has_more_comments', False) if has_more_comments: max_id = json.loads(api.LastJson.get('next_max_id', ))['server_cursor'] if (len(comments) >= self.item['comment_count']): has_more_comments = False return <|docstring|>Get First comment of the post :return: First comment text<|endoftext|>
ddd081aeabd79922143ba458aa8bfac38e49c0ae6ae4174b738d5d6f14c71c2e
def printAll(self): '\n prints captions of all posts\n :param items:\n :return:\n ' for item in self.items: try: print((('=========Post code: ' + item['code']) + '=============')) print(item['caption']['text']) except TypeError: print('(Empty caption text)')
prints captions of all posts :param items: :return:
main.py
printAll
tiffany-matsuda/Instagram-API-python
0
python
def printAll(self): '\n prints captions of all posts\n :param items:\n :return:\n ' for item in self.items: try: print((('=========Post code: ' + item['code']) + '=============')) print(item['caption']['text']) except TypeError: print('(Empty caption text)')
def printAll(self): '\n prints captions of all posts\n :param items:\n :return:\n ' for item in self.items: try: print((('=========Post code: ' + item['code']) + '=============')) print(item['caption']['text']) except TypeError: print('(Empty caption text)')<|docstring|>prints captions of all posts :param items: :return:<|endoftext|>
b4549659e3d1768d2efed60746dff7cf1be47d53f698e062c504596c47bcb9b6
def printHashtagsDict(self): '\n Prints top 10 hashtags of user\n :return:\n ' print('========Top 10 Hashtags=========') hashtagList = sorted(reader.hashDict, key=reader.hashDict.get, reverse=True) count = 0 for hashtag in hashtagList: print(hashtag, self.hashDict[hashtag]) count += 1 if (count >= 10): return
Prints top 10 hashtags of user :return:
main.py
printHashtagsDict
tiffany-matsuda/Instagram-API-python
0
python
def printHashtagsDict(self): '\n Prints top 10 hashtags of user\n :return:\n ' print('========Top 10 Hashtags=========') hashtagList = sorted(reader.hashDict, key=reader.hashDict.get, reverse=True) count = 0 for hashtag in hashtagList: print(hashtag, self.hashDict[hashtag]) count += 1 if (count >= 10): return
def printHashtagsDict(self): '\n Prints top 10 hashtags of user\n :return:\n ' print('========Top 10 Hashtags=========') hashtagList = sorted(reader.hashDict, key=reader.hashDict.get, reverse=True) count = 0 for hashtag in hashtagList: print(hashtag, self.hashDict[hashtag]) count += 1 if (count >= 10): return<|docstring|>Prints top 10 hashtags of user :return:<|endoftext|>
c75b6789df1faacf55597ec27203c9f5c81c9739f7ea00094807098cfa768737
def use_cache() -> int: '\n Only use caching when running the test suite to reduce its duration.\n In production, this won\'t always give us fresh enough data, especially\n when using the "MOST_RECENT" request option. So, let\'s skip it for that\n purpose for now.\n\n https://stackoverflow.com/a/58866220\n\n :return: Cache TTL in seconds.\n ' if (('PYTEST_CURRENT_TEST' in os.environ) and ('CI' not in os.environ)): return (2 * 60) else: return 0
Only use caching when running the test suite to reduce its duration. In production, this won't always give us fresh enough data, especially when using the "MOST_RECENT" request option. So, let's skip it for that purpose for now. https://stackoverflow.com/a/58866220 :return: Cache TTL in seconds.
wetterdienst/provider/dwd/radar/index.py
use_cache
bh-chaker/wetterdienst
155
python
def use_cache() -> int: '\n Only use caching when running the test suite to reduce its duration.\n In production, this won\'t always give us fresh enough data, especially\n when using the "MOST_RECENT" request option. So, let\'s skip it for that\n purpose for now.\n\n https://stackoverflow.com/a/58866220\n\n :return: Cache TTL in seconds.\n ' if (('PYTEST_CURRENT_TEST' in os.environ) and ('CI' not in os.environ)): return (2 * 60) else: return 0
def use_cache() -> int: '\n Only use caching when running the test suite to reduce its duration.\n In production, this won\'t always give us fresh enough data, especially\n when using the "MOST_RECENT" request option. So, let\'s skip it for that\n purpose for now.\n\n https://stackoverflow.com/a/58866220\n\n :return: Cache TTL in seconds.\n ' if (('PYTEST_CURRENT_TEST' in os.environ) and ('CI' not in os.environ)): return (2 * 60) else: return 0<|docstring|>Only use caching when running the test suite to reduce its duration. In production, this won't always give us fresh enough data, especially when using the "MOST_RECENT" request option. So, let's skip it for that purpose for now. https://stackoverflow.com/a/58866220 :return: Cache TTL in seconds.<|endoftext|>
62848d042ad73d0bb8cd73f2d41234a1416fdbc64216ac128bff253b88652d9b
@fileindex_cache_five_minutes.cache_on_arguments(expiration_time=use_cache) def create_fileindex_radar(parameter: DwdRadarParameter, site: Optional[DwdRadarSite]=None, fmt: Optional[DwdRadarDataFormat]=None, subset: Optional[DwdRadarDataSubset]=None, resolution: Optional[Resolution]=None, period: Optional[Period]=None, parse_datetime: bool=False) -> pd.DataFrame: '\n Function to create a file index of the DWD radar data, which is shipped as\n bin bufr or odim-hdf5 data. The file index is created for a single parameter.\n\n :param parameter: The radar moment to request\n :param site: Site/station if parameter is one of\n RADAR_PARAMETERS_SITES\n :param fmt: Data format (BINARY, BUFR, HDF5)\n :param subset: The subset (simple or polarimetric) for HDF5 data.\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n :param parse_datetime: Whether to parse datetimes from file names\n\n :return: File index as pandas.DataFrame with FILENAME\n and DATETIME columns\n ' parameter_path = build_path_to_parameter(parameter=parameter, site=site, fmt=fmt, subset=subset, resolution=resolution, period=period) url = urljoin(DWD_SERVER, parameter_path) files_server = list_remote_files_fsspec(url, recursive=True) files_server = pd.DataFrame(files_server, columns=[DwdColumns.FILENAME.value], dtype='str') if (fmt is not None): if (fmt == DwdRadarDataFormat.BINARY): files_server = files_server[files_server[DwdColumns.FILENAME.value].str.contains('--bin')] elif (fmt == DwdRadarDataFormat.BUFR): files_server = files_server[files_server[DwdColumns.FILENAME.value].str.contains('--buf')] if parse_datetime: files_server[DwdColumns.DATETIME.value] = files_server[DwdColumns.FILENAME.value].apply(get_date_from_filename) files_server = files_server.dropna() return files_server
Function to create a file index of the DWD radar data, which is shipped as bin bufr or odim-hdf5 data. The file index is created for a single parameter. :param parameter: The radar moment to request :param site: Site/station if parameter is one of RADAR_PARAMETERS_SITES :param fmt: Data format (BINARY, BUFR, HDF5) :param subset: The subset (simple or polarimetric) for HDF5 data. :param resolution: Time resolution for RadarParameter.RADOLAN_CDC, either daily or hourly or 5 minutes. :param period: Period type for RadarParameter.RADOLAN_CDC :param parse_datetime: Whether to parse datetimes from file names :return: File index as pandas.DataFrame with FILENAME and DATETIME columns
wetterdienst/provider/dwd/radar/index.py
create_fileindex_radar
bh-chaker/wetterdienst
155
python
@fileindex_cache_five_minutes.cache_on_arguments(expiration_time=use_cache) def create_fileindex_radar(parameter: DwdRadarParameter, site: Optional[DwdRadarSite]=None, fmt: Optional[DwdRadarDataFormat]=None, subset: Optional[DwdRadarDataSubset]=None, resolution: Optional[Resolution]=None, period: Optional[Period]=None, parse_datetime: bool=False) -> pd.DataFrame: '\n Function to create a file index of the DWD radar data, which is shipped as\n bin bufr or odim-hdf5 data. The file index is created for a single parameter.\n\n :param parameter: The radar moment to request\n :param site: Site/station if parameter is one of\n RADAR_PARAMETERS_SITES\n :param fmt: Data format (BINARY, BUFR, HDF5)\n :param subset: The subset (simple or polarimetric) for HDF5 data.\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n :param parse_datetime: Whether to parse datetimes from file names\n\n :return: File index as pandas.DataFrame with FILENAME\n and DATETIME columns\n ' parameter_path = build_path_to_parameter(parameter=parameter, site=site, fmt=fmt, subset=subset, resolution=resolution, period=period) url = urljoin(DWD_SERVER, parameter_path) files_server = list_remote_files_fsspec(url, recursive=True) files_server = pd.DataFrame(files_server, columns=[DwdColumns.FILENAME.value], dtype='str') if (fmt is not None): if (fmt == DwdRadarDataFormat.BINARY): files_server = files_server[files_server[DwdColumns.FILENAME.value].str.contains('--bin')] elif (fmt == DwdRadarDataFormat.BUFR): files_server = files_server[files_server[DwdColumns.FILENAME.value].str.contains('--buf')] if parse_datetime: files_server[DwdColumns.DATETIME.value] = files_server[DwdColumns.FILENAME.value].apply(get_date_from_filename) files_server = files_server.dropna() return files_server
@fileindex_cache_five_minutes.cache_on_arguments(expiration_time=use_cache) def create_fileindex_radar(parameter: DwdRadarParameter, site: Optional[DwdRadarSite]=None, fmt: Optional[DwdRadarDataFormat]=None, subset: Optional[DwdRadarDataSubset]=None, resolution: Optional[Resolution]=None, period: Optional[Period]=None, parse_datetime: bool=False) -> pd.DataFrame: '\n Function to create a file index of the DWD radar data, which is shipped as\n bin bufr or odim-hdf5 data. The file index is created for a single parameter.\n\n :param parameter: The radar moment to request\n :param site: Site/station if parameter is one of\n RADAR_PARAMETERS_SITES\n :param fmt: Data format (BINARY, BUFR, HDF5)\n :param subset: The subset (simple or polarimetric) for HDF5 data.\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n :param parse_datetime: Whether to parse datetimes from file names\n\n :return: File index as pandas.DataFrame with FILENAME\n and DATETIME columns\n ' parameter_path = build_path_to_parameter(parameter=parameter, site=site, fmt=fmt, subset=subset, resolution=resolution, period=period) url = urljoin(DWD_SERVER, parameter_path) files_server = list_remote_files_fsspec(url, recursive=True) files_server = pd.DataFrame(files_server, columns=[DwdColumns.FILENAME.value], dtype='str') if (fmt is not None): if (fmt == DwdRadarDataFormat.BINARY): files_server = files_server[files_server[DwdColumns.FILENAME.value].str.contains('--bin')] elif (fmt == DwdRadarDataFormat.BUFR): files_server = files_server[files_server[DwdColumns.FILENAME.value].str.contains('--buf')] if parse_datetime: files_server[DwdColumns.DATETIME.value] = files_server[DwdColumns.FILENAME.value].apply(get_date_from_filename) files_server = files_server.dropna() return files_server<|docstring|>Function to create a file index of the DWD radar data, which is shipped as bin bufr or odim-hdf5 data. The file index is created for a single parameter. :param parameter: The radar moment to request :param site: Site/station if parameter is one of RADAR_PARAMETERS_SITES :param fmt: Data format (BINARY, BUFR, HDF5) :param subset: The subset (simple or polarimetric) for HDF5 data. :param resolution: Time resolution for RadarParameter.RADOLAN_CDC, either daily or hourly or 5 minutes. :param period: Period type for RadarParameter.RADOLAN_CDC :param parse_datetime: Whether to parse datetimes from file names :return: File index as pandas.DataFrame with FILENAME and DATETIME columns<|endoftext|>
c063d18496d83b5c23c9e87fc3adcaf27a04772cbb91357a47f148bebec97e84
@fileindex_cache_five_minutes.cache_on_arguments() def create_fileindex_radolan_cdc(resolution: Resolution, period: Period) -> pd.DataFrame: '\n Function used to create a file index for the RADOLAN_CDC product. The file index\n will include both recent as well as historical files. A datetime column is created\n from the filenames which contain some datetime formats. This datetime column is\n required for later filtering for the requested file.\n\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n\n :return: File index as DataFrame\n ' file_index = create_fileindex_radar(parameter=DwdRadarParameter.RADOLAN_CDC, resolution=resolution, period=period) file_index = file_index[(file_index[DwdColumns.FILENAME.value].str.contains('/bin/') & file_index[DwdColumns.FILENAME.value].str.endswith((Extension.GZ.value, Extension.TAR_GZ.value)))].copy() file_index[DwdColumns.DATETIME.value] = file_index[DwdColumns.FILENAME.value].apply((lambda filename: parse(RADOLAN_DT_PATTERN.findall(filename)[0], date_formats=[DatetimeFormat.YM.value, DatetimeFormat.ymdhm.value]))) return file_index
Function used to create a file index for the RADOLAN_CDC product. The file index will include both recent as well as historical files. A datetime column is created from the filenames which contain some datetime formats. This datetime column is required for later filtering for the requested file. :param resolution: Time resolution for RadarParameter.RADOLAN_CDC, either daily or hourly or 5 minutes. :param period: Period type for RadarParameter.RADOLAN_CDC :return: File index as DataFrame
wetterdienst/provider/dwd/radar/index.py
create_fileindex_radolan_cdc
bh-chaker/wetterdienst
155
python
@fileindex_cache_five_minutes.cache_on_arguments() def create_fileindex_radolan_cdc(resolution: Resolution, period: Period) -> pd.DataFrame: '\n Function used to create a file index for the RADOLAN_CDC product. The file index\n will include both recent as well as historical files. A datetime column is created\n from the filenames which contain some datetime formats. This datetime column is\n required for later filtering for the requested file.\n\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n\n :return: File index as DataFrame\n ' file_index = create_fileindex_radar(parameter=DwdRadarParameter.RADOLAN_CDC, resolution=resolution, period=period) file_index = file_index[(file_index[DwdColumns.FILENAME.value].str.contains('/bin/') & file_index[DwdColumns.FILENAME.value].str.endswith((Extension.GZ.value, Extension.TAR_GZ.value)))].copy() file_index[DwdColumns.DATETIME.value] = file_index[DwdColumns.FILENAME.value].apply((lambda filename: parse(RADOLAN_DT_PATTERN.findall(filename)[0], date_formats=[DatetimeFormat.YM.value, DatetimeFormat.ymdhm.value]))) return file_index
@fileindex_cache_five_minutes.cache_on_arguments() def create_fileindex_radolan_cdc(resolution: Resolution, period: Period) -> pd.DataFrame: '\n Function used to create a file index for the RADOLAN_CDC product. The file index\n will include both recent as well as historical files. A datetime column is created\n from the filenames which contain some datetime formats. This datetime column is\n required for later filtering for the requested file.\n\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n\n :return: File index as DataFrame\n ' file_index = create_fileindex_radar(parameter=DwdRadarParameter.RADOLAN_CDC, resolution=resolution, period=period) file_index = file_index[(file_index[DwdColumns.FILENAME.value].str.contains('/bin/') & file_index[DwdColumns.FILENAME.value].str.endswith((Extension.GZ.value, Extension.TAR_GZ.value)))].copy() file_index[DwdColumns.DATETIME.value] = file_index[DwdColumns.FILENAME.value].apply((lambda filename: parse(RADOLAN_DT_PATTERN.findall(filename)[0], date_formats=[DatetimeFormat.YM.value, DatetimeFormat.ymdhm.value]))) return file_index<|docstring|>Function used to create a file index for the RADOLAN_CDC product. The file index will include both recent as well as historical files. A datetime column is created from the filenames which contain some datetime formats. This datetime column is required for later filtering for the requested file. :param resolution: Time resolution for RadarParameter.RADOLAN_CDC, either daily or hourly or 5 minutes. :param period: Period type for RadarParameter.RADOLAN_CDC :return: File index as DataFrame<|endoftext|>
56b60430bcbbbbe3bd88c85387f2166acf4d844c48d5ab9f4c319d6f45e7bffe
def build_path_to_parameter(parameter: DwdRadarParameter, site: Optional[DwdRadarSite]=None, fmt: Optional[DwdRadarDataFormat]=None, subset: Optional[DwdRadarDataSubset]=None, resolution: Optional[Resolution]=None, period: Optional[Period]=None) -> str: '\n Compute URL path to data product.\n\n Supports composite- and site-based radar data as well as RADOLAN_CDC.\n\n Composites\n ----------\n - https://opendata.dwd.de/weather/radar/composit/\n - https://opendata.dwd.de/weather/radar/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/daily/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/hourly/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/5_minutes/radolan/\n\n Sites\n -----\n - https://opendata.dwd.de/weather/radar/sites/\n\n\n :param parameter: The radar moment to request\n :param site: Site/station if parameter is one of\n RADAR_PARAMETERS_SITES\n :param fmt: Data format (BINARY, BUFR, HDF5)\n :param subset: The subset (simple or polarimetric) for HDF5 data.\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n\n :return: URL path to data product\n ' if (parameter == DwdRadarParameter.RADOLAN_CDC): if (resolution == Resolution.MINUTE_5): parameter_path = f'{DWD_CDC_PATH}/grids_germany/{resolution.value}/radolan/reproc/2017_002/bin' else: parameter_path = f'{DWD_CDC_PATH}/grids_germany/{resolution.value}/radolan/{period.value}/bin' elif (parameter in RADAR_PARAMETERS_COMPOSITES): parameter_path = f'weather/radar/composit/{parameter.value}' elif (parameter in RADAR_PARAMETERS_RADOLAN): parameter_path = f'weather/radar/radolan/{parameter.value}' elif (parameter in RADAR_PARAMETERS_RADVOR): parameter_path = f'weather/radar/radvor/{parameter.value}' elif (parameter in RADAR_PARAMETERS_SITES): if (site is None): raise ValueError("Argument 'site' is missing") if (fmt is None): ambiguous_parameters = [DwdRadarParameter.PE_ECHO_TOP, DwdRadarParameter.PL_VOLUME_SCAN, DwdRadarParameter.PR_VELOCITY, DwdRadarParameter.PX_REFLECTIVITY, DwdRadarParameter.PZ_CAPPI] candidates = None if (parameter in ambiguous_parameters): candidates = [DwdRadarDataFormat.BINARY, DwdRadarDataFormat.BUFR] if (parameter in RADAR_PARAMETERS_SWEEPS): candidates = [DwdRadarDataFormat.BUFR, DwdRadarDataFormat.HDF5] if candidates: raise ValueError(f"Argument 'format' is missing, use one of {candidates}") parameter_path = f'weather/radar/sites/{parameter.value}/{site.value}' if (fmt == DwdRadarDataFormat.HDF5): if (subset is None): candidates = [DwdRadarDataSubset.SIMPLE, DwdRadarDataSubset.POLARIMETRIC] raise ValueError(f"Argument 'subset' is missing, use one of {candidates}") parameter_path = f'{parameter_path}/{fmt.value}/filter_{subset.value}/' else: raise NotImplementedError(f'Acquisition for {parameter} not implemented yet') return parameter_path
Compute URL path to data product. Supports composite- and site-based radar data as well as RADOLAN_CDC. Composites ---------- - https://opendata.dwd.de/weather/radar/composit/ - https://opendata.dwd.de/weather/radar/radolan/ - https://opendata.dwd.de/climate_environment/CDC/grids_germany/daily/radolan/ - https://opendata.dwd.de/climate_environment/CDC/grids_germany/hourly/radolan/ - https://opendata.dwd.de/climate_environment/CDC/grids_germany/5_minutes/radolan/ Sites ----- - https://opendata.dwd.de/weather/radar/sites/ :param parameter: The radar moment to request :param site: Site/station if parameter is one of RADAR_PARAMETERS_SITES :param fmt: Data format (BINARY, BUFR, HDF5) :param subset: The subset (simple or polarimetric) for HDF5 data. :param resolution: Time resolution for RadarParameter.RADOLAN_CDC, either daily or hourly or 5 minutes. :param period: Period type for RadarParameter.RADOLAN_CDC :return: URL path to data product
wetterdienst/provider/dwd/radar/index.py
build_path_to_parameter
bh-chaker/wetterdienst
155
python
def build_path_to_parameter(parameter: DwdRadarParameter, site: Optional[DwdRadarSite]=None, fmt: Optional[DwdRadarDataFormat]=None, subset: Optional[DwdRadarDataSubset]=None, resolution: Optional[Resolution]=None, period: Optional[Period]=None) -> str: '\n Compute URL path to data product.\n\n Supports composite- and site-based radar data as well as RADOLAN_CDC.\n\n Composites\n ----------\n - https://opendata.dwd.de/weather/radar/composit/\n - https://opendata.dwd.de/weather/radar/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/daily/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/hourly/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/5_minutes/radolan/\n\n Sites\n -----\n - https://opendata.dwd.de/weather/radar/sites/\n\n\n :param parameter: The radar moment to request\n :param site: Site/station if parameter is one of\n RADAR_PARAMETERS_SITES\n :param fmt: Data format (BINARY, BUFR, HDF5)\n :param subset: The subset (simple or polarimetric) for HDF5 data.\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n\n :return: URL path to data product\n ' if (parameter == DwdRadarParameter.RADOLAN_CDC): if (resolution == Resolution.MINUTE_5): parameter_path = f'{DWD_CDC_PATH}/grids_germany/{resolution.value}/radolan/reproc/2017_002/bin' else: parameter_path = f'{DWD_CDC_PATH}/grids_germany/{resolution.value}/radolan/{period.value}/bin' elif (parameter in RADAR_PARAMETERS_COMPOSITES): parameter_path = f'weather/radar/composit/{parameter.value}' elif (parameter in RADAR_PARAMETERS_RADOLAN): parameter_path = f'weather/radar/radolan/{parameter.value}' elif (parameter in RADAR_PARAMETERS_RADVOR): parameter_path = f'weather/radar/radvor/{parameter.value}' elif (parameter in RADAR_PARAMETERS_SITES): if (site is None): raise ValueError("Argument 'site' is missing") if (fmt is None): ambiguous_parameters = [DwdRadarParameter.PE_ECHO_TOP, DwdRadarParameter.PL_VOLUME_SCAN, DwdRadarParameter.PR_VELOCITY, DwdRadarParameter.PX_REFLECTIVITY, DwdRadarParameter.PZ_CAPPI] candidates = None if (parameter in ambiguous_parameters): candidates = [DwdRadarDataFormat.BINARY, DwdRadarDataFormat.BUFR] if (parameter in RADAR_PARAMETERS_SWEEPS): candidates = [DwdRadarDataFormat.BUFR, DwdRadarDataFormat.HDF5] if candidates: raise ValueError(f"Argument 'format' is missing, use one of {candidates}") parameter_path = f'weather/radar/sites/{parameter.value}/{site.value}' if (fmt == DwdRadarDataFormat.HDF5): if (subset is None): candidates = [DwdRadarDataSubset.SIMPLE, DwdRadarDataSubset.POLARIMETRIC] raise ValueError(f"Argument 'subset' is missing, use one of {candidates}") parameter_path = f'{parameter_path}/{fmt.value}/filter_{subset.value}/' else: raise NotImplementedError(f'Acquisition for {parameter} not implemented yet') return parameter_path
def build_path_to_parameter(parameter: DwdRadarParameter, site: Optional[DwdRadarSite]=None, fmt: Optional[DwdRadarDataFormat]=None, subset: Optional[DwdRadarDataSubset]=None, resolution: Optional[Resolution]=None, period: Optional[Period]=None) -> str: '\n Compute URL path to data product.\n\n Supports composite- and site-based radar data as well as RADOLAN_CDC.\n\n Composites\n ----------\n - https://opendata.dwd.de/weather/radar/composit/\n - https://opendata.dwd.de/weather/radar/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/daily/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/hourly/radolan/\n - https://opendata.dwd.de/climate_environment/CDC/grids_germany/5_minutes/radolan/\n\n Sites\n -----\n - https://opendata.dwd.de/weather/radar/sites/\n\n\n :param parameter: The radar moment to request\n :param site: Site/station if parameter is one of\n RADAR_PARAMETERS_SITES\n :param fmt: Data format (BINARY, BUFR, HDF5)\n :param subset: The subset (simple or polarimetric) for HDF5 data.\n :param resolution: Time resolution for RadarParameter.RADOLAN_CDC,\n either daily or hourly or 5 minutes.\n :param period: Period type for RadarParameter.RADOLAN_CDC\n\n :return: URL path to data product\n ' if (parameter == DwdRadarParameter.RADOLAN_CDC): if (resolution == Resolution.MINUTE_5): parameter_path = f'{DWD_CDC_PATH}/grids_germany/{resolution.value}/radolan/reproc/2017_002/bin' else: parameter_path = f'{DWD_CDC_PATH}/grids_germany/{resolution.value}/radolan/{period.value}/bin' elif (parameter in RADAR_PARAMETERS_COMPOSITES): parameter_path = f'weather/radar/composit/{parameter.value}' elif (parameter in RADAR_PARAMETERS_RADOLAN): parameter_path = f'weather/radar/radolan/{parameter.value}' elif (parameter in RADAR_PARAMETERS_RADVOR): parameter_path = f'weather/radar/radvor/{parameter.value}' elif (parameter in RADAR_PARAMETERS_SITES): if (site is None): raise ValueError("Argument 'site' is missing") if (fmt is None): ambiguous_parameters = [DwdRadarParameter.PE_ECHO_TOP, DwdRadarParameter.PL_VOLUME_SCAN, DwdRadarParameter.PR_VELOCITY, DwdRadarParameter.PX_REFLECTIVITY, DwdRadarParameter.PZ_CAPPI] candidates = None if (parameter in ambiguous_parameters): candidates = [DwdRadarDataFormat.BINARY, DwdRadarDataFormat.BUFR] if (parameter in RADAR_PARAMETERS_SWEEPS): candidates = [DwdRadarDataFormat.BUFR, DwdRadarDataFormat.HDF5] if candidates: raise ValueError(f"Argument 'format' is missing, use one of {candidates}") parameter_path = f'weather/radar/sites/{parameter.value}/{site.value}' if (fmt == DwdRadarDataFormat.HDF5): if (subset is None): candidates = [DwdRadarDataSubset.SIMPLE, DwdRadarDataSubset.POLARIMETRIC] raise ValueError(f"Argument 'subset' is missing, use one of {candidates}") parameter_path = f'{parameter_path}/{fmt.value}/filter_{subset.value}/' else: raise NotImplementedError(f'Acquisition for {parameter} not implemented yet') return parameter_path<|docstring|>Compute URL path to data product. Supports composite- and site-based radar data as well as RADOLAN_CDC. Composites ---------- - https://opendata.dwd.de/weather/radar/composit/ - https://opendata.dwd.de/weather/radar/radolan/ - https://opendata.dwd.de/climate_environment/CDC/grids_germany/daily/radolan/ - https://opendata.dwd.de/climate_environment/CDC/grids_germany/hourly/radolan/ - https://opendata.dwd.de/climate_environment/CDC/grids_germany/5_minutes/radolan/ Sites ----- - https://opendata.dwd.de/weather/radar/sites/ :param parameter: The radar moment to request :param site: Site/station if parameter is one of RADAR_PARAMETERS_SITES :param fmt: Data format (BINARY, BUFR, HDF5) :param subset: The subset (simple or polarimetric) for HDF5 data. :param resolution: Time resolution for RadarParameter.RADOLAN_CDC, either daily or hourly or 5 minutes. :param period: Period type for RadarParameter.RADOLAN_CDC :return: URL path to data product<|endoftext|>
687443bd236b7db072b7a974f23cb4eebf679c3960172064c32f142453768e20
def print_dumped(source): 'Pretty print the AST' if isinstance(source, str): module = extast.parse(source) if (len(module.body) == 1): node = module.body[0] else: node = module else: node = source print(dump(node))
Pretty print the AST
transonic/analyses/util.py
print_dumped
fluiddyn/transonic
88
python
def print_dumped(source): if isinstance(source, str): module = extast.parse(source) if (len(module.body) == 1): node = module.body[0] else: node = module else: node = source print(dump(node))
def print_dumped(source): if isinstance(source, str): module = extast.parse(source) if (len(module.body) == 1): node = module.body[0] else: node = module else: node = source print(dump(node))<|docstring|>Pretty print the AST<|endoftext|>
095175e9aace162de875d5a4ac93f74fa999ae639554e922aa8c21d6e6e0e5df
def print_unparsed(node): 'Print the code corresponding to a tree or a node' print(extast.unparse(node))
Print the code corresponding to a tree or a node
transonic/analyses/util.py
print_unparsed
fluiddyn/transonic
88
python
def print_unparsed(node): print(extast.unparse(node))
def print_unparsed(node): print(extast.unparse(node))<|docstring|>Print the code corresponding to a tree or a node<|endoftext|>
03653c32a3925397a364374eb78c48267127b5bbca56db3c10480d8c24bbec02
def get_annotations(object_def, namespace): 'Create the annotations from a definition node' ast_annotations = ast.Assign(targets=[extast.Name('annotations', ast.Store())], value=ast.Dict(keys=[], values=[]), type_comment=None) if isinstance(object_def, ast.FunctionDef): _fill_ast_annotations_function(object_def, ast_annotations) elif isinstance(object_def, ast.ClassDef): _fill_ast_annotations_class(object_def, ast_annotations) else: raise NotImplementedError source = extast.unparse(ast_annotations) try: del namespace['__builtins__'] except KeyError: pass exec(source, namespace) return namespace['annotations']
Create the annotations from a definition node
transonic/analyses/util.py
get_annotations
fluiddyn/transonic
88
python
def get_annotations(object_def, namespace): ast_annotations = ast.Assign(targets=[extast.Name('annotations', ast.Store())], value=ast.Dict(keys=[], values=[]), type_comment=None) if isinstance(object_def, ast.FunctionDef): _fill_ast_annotations_function(object_def, ast_annotations) elif isinstance(object_def, ast.ClassDef): _fill_ast_annotations_class(object_def, ast_annotations) else: raise NotImplementedError source = extast.unparse(ast_annotations) try: del namespace['__builtins__'] except KeyError: pass exec(source, namespace) return namespace['annotations']
def get_annotations(object_def, namespace): ast_annotations = ast.Assign(targets=[extast.Name('annotations', ast.Store())], value=ast.Dict(keys=[], values=[]), type_comment=None) if isinstance(object_def, ast.FunctionDef): _fill_ast_annotations_function(object_def, ast_annotations) elif isinstance(object_def, ast.ClassDef): _fill_ast_annotations_class(object_def, ast_annotations) else: raise NotImplementedError source = extast.unparse(ast_annotations) try: del namespace['__builtins__'] except KeyError: pass exec(source, namespace) return namespace['annotations']<|docstring|>Create the annotations from a definition node<|endoftext|>
b978493d949853417155503b5438a0ddce131df3d2eda49414752393a8247496
def filter_code_typevars(module, duc, ancestors): 'Create a filtered code with what is needed to create the annotations' module_filtered = ast.Module() kept = module_filtered.body = [] module_filtered.type_ignores = [] suppressed = set() def fill_suppressed(def_): for user in def_.users(): parent_in_body = ancestors.parents(user.node)[1] suppressed.add(parent_in_body) fill_suppressed(user) for node in module.body: if (node in suppressed): continue if isinstance(node, ast.Import): if (node.names[0].name in ['transonic', 'numpy']): kept.append(node) else: def_ = duc.chains[node.names[0]] fill_suppressed(def_) elif isinstance(node, ast.ImportFrom): if (node.module in ['transonic', 'numpy']): kept.append(node) elif isinstance(node, (ast.Assign, ast.AugAssign)): kept.append(node) return extast.unparse(module_filtered)
Create a filtered code with what is needed to create the annotations
transonic/analyses/util.py
filter_code_typevars
fluiddyn/transonic
88
python
def filter_code_typevars(module, duc, ancestors): module_filtered = ast.Module() kept = module_filtered.body = [] module_filtered.type_ignores = [] suppressed = set() def fill_suppressed(def_): for user in def_.users(): parent_in_body = ancestors.parents(user.node)[1] suppressed.add(parent_in_body) fill_suppressed(user) for node in module.body: if (node in suppressed): continue if isinstance(node, ast.Import): if (node.names[0].name in ['transonic', 'numpy']): kept.append(node) else: def_ = duc.chains[node.names[0]] fill_suppressed(def_) elif isinstance(node, ast.ImportFrom): if (node.module in ['transonic', 'numpy']): kept.append(node) elif isinstance(node, (ast.Assign, ast.AugAssign)): kept.append(node) return extast.unparse(module_filtered)
def filter_code_typevars(module, duc, ancestors): module_filtered = ast.Module() kept = module_filtered.body = [] module_filtered.type_ignores = [] suppressed = set() def fill_suppressed(def_): for user in def_.users(): parent_in_body = ancestors.parents(user.node)[1] suppressed.add(parent_in_body) fill_suppressed(user) for node in module.body: if (node in suppressed): continue if isinstance(node, ast.Import): if (node.names[0].name in ['transonic', 'numpy']): kept.append(node) else: def_ = duc.chains[node.names[0]] fill_suppressed(def_) elif isinstance(node, ast.ImportFrom): if (node.module in ['transonic', 'numpy']): kept.append(node) elif isinstance(node, (ast.Assign, ast.AugAssign)): kept.append(node) return extast.unparse(module_filtered)<|docstring|>Create a filtered code with what is needed to create the annotations<|endoftext|>
7c057214f9c8feb62d1b6a6a604b1462da79037bff581f3e229b33aa3f7578a0
def gather_rawcode_comments(node, code_module): 'Get the comments in a node' analysis = AnalyseLines(node) rawcode = dedent(analysis.get_code(code_module)) comments = dedent('\n'.join((line for line in rawcode.split('\n') if line.strip().startswith('#')))) return (rawcode, comments)
Get the comments in a node
transonic/analyses/util.py
gather_rawcode_comments
fluiddyn/transonic
88
python
def gather_rawcode_comments(node, code_module): analysis = AnalyseLines(node) rawcode = dedent(analysis.get_code(code_module)) comments = dedent('\n'.join((line for line in rawcode.split('\n') if line.strip().startswith('#')))) return (rawcode, comments)
def gather_rawcode_comments(node, code_module): analysis = AnalyseLines(node) rawcode = dedent(analysis.get_code(code_module)) comments = dedent('\n'.join((line for line in rawcode.split('\n') if line.strip().startswith('#')))) return (rawcode, comments)<|docstring|>Get the comments in a node<|endoftext|>
76e6050cf36b99cea2d4370048d25f61608f2585f5deed80b5120fc651fc0137
def find_path(node: object, pathfile: str): 'Return the path of node (instance of ast.Import or ast.ImportFrom)' name = str() path = str() if isinstance(node, ast.ImportFrom): name = node.module if (name in packages_supported_by_pythran): return (None, None) else: parent = Path(pathfile).parent path = (parent / (str(name.replace('.', '/')) + '.py')) elif (node.names[0].name in packages_supported_by_pythran): pass else: raise NotImplementedError return (name, path)
Return the path of node (instance of ast.Import or ast.ImportFrom)
transonic/analyses/util.py
find_path
fluiddyn/transonic
88
python
def find_path(node: object, pathfile: str): name = str() path = str() if isinstance(node, ast.ImportFrom): name = node.module if (name in packages_supported_by_pythran): return (None, None) else: parent = Path(pathfile).parent path = (parent / (str(name.replace('.', '/')) + '.py')) elif (node.names[0].name in packages_supported_by_pythran): pass else: raise NotImplementedError return (name, path)
def find_path(node: object, pathfile: str): name = str() path = str() if isinstance(node, ast.ImportFrom): name = node.module if (name in packages_supported_by_pythran): return (None, None) else: parent = Path(pathfile).parent path = (parent / (str(name.replace('.', '/')) + '.py')) elif (node.names[0].name in packages_supported_by_pythran): pass else: raise NotImplementedError return (name, path)<|docstring|>Return the path of node (instance of ast.Import or ast.ImportFrom)<|endoftext|>
055f032b1f961ef45c73a5ecb481754dbbb3d6d60fce102153f4cef4a889c9f7
def change_import_name(code_dep: str, changed_node: object, func_name: str, relative: str=None): 'Change the name of changed_node in code_dep by adding "__" + func + "__"\n at the beginning of the imported module, and return the modified code\n ' mod = extast.parse(code_dep) for node in mod.body: if (extast.unparse(node) == extast.unparse(changed_node)): if isinstance(node, ast.ImportFrom): node.module = f'__ext__{func_name}__{node.module}' elif isinstance(node, ast.Import): node.names[0].name = f'__ext__{func_name}__{node.names[0].name}' if (not relative): node.level = 0 return extast.unparse(mod)
Change the name of changed_node in code_dep by adding "__" + func + "__" at the beginning of the imported module, and return the modified code
transonic/analyses/util.py
change_import_name
fluiddyn/transonic
88
python
def change_import_name(code_dep: str, changed_node: object, func_name: str, relative: str=None): 'Change the name of changed_node in code_dep by adding "__" + func + "__"\n at the beginning of the imported module, and return the modified code\n ' mod = extast.parse(code_dep) for node in mod.body: if (extast.unparse(node) == extast.unparse(changed_node)): if isinstance(node, ast.ImportFrom): node.module = f'__ext__{func_name}__{node.module}' elif isinstance(node, ast.Import): node.names[0].name = f'__ext__{func_name}__{node.names[0].name}' if (not relative): node.level = 0 return extast.unparse(mod)
def change_import_name(code_dep: str, changed_node: object, func_name: str, relative: str=None): 'Change the name of changed_node in code_dep by adding "__" + func + "__"\n at the beginning of the imported module, and return the modified code\n ' mod = extast.parse(code_dep) for node in mod.body: if (extast.unparse(node) == extast.unparse(changed_node)): if isinstance(node, ast.ImportFrom): node.module = f'__ext__{func_name}__{node.module}' elif isinstance(node, ast.Import): node.names[0].name = f'__ext__{func_name}__{node.names[0].name}' if (not relative): node.level = 0 return extast.unparse(mod)<|docstring|>Change the name of changed_node in code_dep by adding "__" + func + "__" at the beginning of the imported module, and return the modified code<|endoftext|>
14c28ba862efe9e2eb0a0d7ead67324c6e5cc4eca4c0a992fce96c2b3088b19d
def filter_external_code(module: object, names: list): 'Filter the module to keep only the necessary nodes\n needed by functions or class in the parameter names\n ' code_dependance_annotations = '' lines_code = [] for node in module.body: for name in names: if isinstance(node, ast.FunctionDef): if (node.name == extast.unparse(name).rstrip('\n\r').strip()): ancestors = beniget.Ancestors() ancestors.visit(module) duc = beniget.DefUseChains() duc.visit(module) udc = beniget.UseDefChains(duc) capturex = CaptureX([node], module, ancestors, defuse_chains=duc, usedef_chains=udc, consider_annotations=None) lines_code.append(str(extast.unparse(node))) code_dependance_annotations = capturex.make_code_external() if isinstance(node, ast.Assign): if (node.targets[0].id == extast.unparse(name).rstrip('\n\r').strip()): lines_code.append(str(extast.unparse(node))) if isinstance(node, ast.ClassDef): if (node.name == extast.unparse(name).rstrip('\n\r').strip()): lines_code.append(str(extast.unparse(node))) return ((code_dependance_annotations + '\n') + '\n'.join(lines_code))
Filter the module to keep only the necessary nodes needed by functions or class in the parameter names
transonic/analyses/util.py
filter_external_code
fluiddyn/transonic
88
python
def filter_external_code(module: object, names: list): 'Filter the module to keep only the necessary nodes\n needed by functions or class in the parameter names\n ' code_dependance_annotations = lines_code = [] for node in module.body: for name in names: if isinstance(node, ast.FunctionDef): if (node.name == extast.unparse(name).rstrip('\n\r').strip()): ancestors = beniget.Ancestors() ancestors.visit(module) duc = beniget.DefUseChains() duc.visit(module) udc = beniget.UseDefChains(duc) capturex = CaptureX([node], module, ancestors, defuse_chains=duc, usedef_chains=udc, consider_annotations=None) lines_code.append(str(extast.unparse(node))) code_dependance_annotations = capturex.make_code_external() if isinstance(node, ast.Assign): if (node.targets[0].id == extast.unparse(name).rstrip('\n\r').strip()): lines_code.append(str(extast.unparse(node))) if isinstance(node, ast.ClassDef): if (node.name == extast.unparse(name).rstrip('\n\r').strip()): lines_code.append(str(extast.unparse(node))) return ((code_dependance_annotations + '\n') + '\n'.join(lines_code))
def filter_external_code(module: object, names: list): 'Filter the module to keep only the necessary nodes\n needed by functions or class in the parameter names\n ' code_dependance_annotations = lines_code = [] for node in module.body: for name in names: if isinstance(node, ast.FunctionDef): if (node.name == extast.unparse(name).rstrip('\n\r').strip()): ancestors = beniget.Ancestors() ancestors.visit(module) duc = beniget.DefUseChains() duc.visit(module) udc = beniget.UseDefChains(duc) capturex = CaptureX([node], module, ancestors, defuse_chains=duc, usedef_chains=udc, consider_annotations=None) lines_code.append(str(extast.unparse(node))) code_dependance_annotations = capturex.make_code_external() if isinstance(node, ast.Assign): if (node.targets[0].id == extast.unparse(name).rstrip('\n\r').strip()): lines_code.append(str(extast.unparse(node))) if isinstance(node, ast.ClassDef): if (node.name == extast.unparse(name).rstrip('\n\r').strip()): lines_code.append(str(extast.unparse(node))) return ((code_dependance_annotations + '\n') + '\n'.join(lines_code))<|docstring|>Filter the module to keep only the necessary nodes needed by functions or class in the parameter names<|endoftext|>
20205589bd86a464b67ff927d82bcec3bd57f568eb73cf5efecb9adb5bde0965
def adapt_code_dependance(func: str, codes_dependance: str, jitted_dicts: dict): '\n Adapt code_dependance to the call of a jitted function in a jitted function:\n - Remove the import transonic\n - Remove the jitted function statement (i.e func = jit(func))\n - Add a import statement to the jitted function\n - remove the definition of the jitted function if its on the file, or remove the import statement\n ' special = [] module = extast.parse(codes_dependance) module_body = module.body.copy() jitted_functions = [] for node in module_body: if isinstance(node, ast.ImportFrom): if (node.module == 'transonic'): module.body.remove(node) elif (isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and (node.value.func.id == 'jit')): if (node.targets[0].id != node.value.args[0].id): def_func = extast.unparse(jitted_dicts['functions'][func]) spl = re.split('(\\W+)', def_func) spl = [(node.value.args[0].id if (x == node.targets[0].id) else x) for x in spl] st = ''.join((str(e) for e in spl)) jitted_dicts['functions'][func] = extast.parse(st) special.append(func) jitted_functions.append(node.value.args[0].id) else: jitted_functions.append(node.targets[0].id) module.body.remove(node) module.body.insert(0, [extast.parse(((('from ' + node.value.args[0].id) + ' import ') + node.value.args[0].id))]) for node in module_body: if isinstance(node, ast.FunctionDef): if (node.name in jitted_functions): module.body.remove(node) if isinstance(node, ast.ImportFrom): for name in node.names: if (name.name in jitted_functions): node.names.remove(name) if (not node.names): module.body.remove(node) return (extast.unparse(module), jitted_dicts, special, jitted_functions)
Adapt code_dependance to the call of a jitted function in a jitted function: - Remove the import transonic - Remove the jitted function statement (i.e func = jit(func)) - Add a import statement to the jitted function - remove the definition of the jitted function if its on the file, or remove the import statement
transonic/analyses/util.py
adapt_code_dependance
fluiddyn/transonic
88
python
def adapt_code_dependance(func: str, codes_dependance: str, jitted_dicts: dict): '\n Adapt code_dependance to the call of a jitted function in a jitted function:\n - Remove the import transonic\n - Remove the jitted function statement (i.e func = jit(func))\n - Add a import statement to the jitted function\n - remove the definition of the jitted function if its on the file, or remove the import statement\n ' special = [] module = extast.parse(codes_dependance) module_body = module.body.copy() jitted_functions = [] for node in module_body: if isinstance(node, ast.ImportFrom): if (node.module == 'transonic'): module.body.remove(node) elif (isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and (node.value.func.id == 'jit')): if (node.targets[0].id != node.value.args[0].id): def_func = extast.unparse(jitted_dicts['functions'][func]) spl = re.split('(\\W+)', def_func) spl = [(node.value.args[0].id if (x == node.targets[0].id) else x) for x in spl] st = .join((str(e) for e in spl)) jitted_dicts['functions'][func] = extast.parse(st) special.append(func) jitted_functions.append(node.value.args[0].id) else: jitted_functions.append(node.targets[0].id) module.body.remove(node) module.body.insert(0, [extast.parse(((('from ' + node.value.args[0].id) + ' import ') + node.value.args[0].id))]) for node in module_body: if isinstance(node, ast.FunctionDef): if (node.name in jitted_functions): module.body.remove(node) if isinstance(node, ast.ImportFrom): for name in node.names: if (name.name in jitted_functions): node.names.remove(name) if (not node.names): module.body.remove(node) return (extast.unparse(module), jitted_dicts, special, jitted_functions)
def adapt_code_dependance(func: str, codes_dependance: str, jitted_dicts: dict): '\n Adapt code_dependance to the call of a jitted function in a jitted function:\n - Remove the import transonic\n - Remove the jitted function statement (i.e func = jit(func))\n - Add a import statement to the jitted function\n - remove the definition of the jitted function if its on the file, or remove the import statement\n ' special = [] module = extast.parse(codes_dependance) module_body = module.body.copy() jitted_functions = [] for node in module_body: if isinstance(node, ast.ImportFrom): if (node.module == 'transonic'): module.body.remove(node) elif (isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and (node.value.func.id == 'jit')): if (node.targets[0].id != node.value.args[0].id): def_func = extast.unparse(jitted_dicts['functions'][func]) spl = re.split('(\\W+)', def_func) spl = [(node.value.args[0].id if (x == node.targets[0].id) else x) for x in spl] st = .join((str(e) for e in spl)) jitted_dicts['functions'][func] = extast.parse(st) special.append(func) jitted_functions.append(node.value.args[0].id) else: jitted_functions.append(node.targets[0].id) module.body.remove(node) module.body.insert(0, [extast.parse(((('from ' + node.value.args[0].id) + ' import ') + node.value.args[0].id))]) for node in module_body: if isinstance(node, ast.FunctionDef): if (node.name in jitted_functions): module.body.remove(node) if isinstance(node, ast.ImportFrom): for name in node.names: if (name.name in jitted_functions): node.names.remove(name) if (not node.names): module.body.remove(node) return (extast.unparse(module), jitted_dicts, special, jitted_functions)<|docstring|>Adapt code_dependance to the call of a jitted function in a jitted function: - Remove the import transonic - Remove the jitted function statement (i.e func = jit(func)) - Add a import statement to the jitted function - remove the definition of the jitted function if its on the file, or remove the import statement<|endoftext|>
314deba27795d64e5c2b587b150df5c0e94d85b0c3b843dd6d501e1335eeefd3
def get_exterior_code(codes_dependance: dict, pathfile: str, previous_file_name=None, classes: str=None, relative: bool=None, jitted_dicts: dict=None): 'Get all imported functions needed by boosted functions and methods at multiple levels,\n (i.e get functions needed by functions imported by boosted function) and add them into code_ext\n ' special = [] treated = [] for (func, dep) in codes_dependance.items(): if (not dep): continue module_ext = extast.parse(dep) for node in module_ext.body: if (not isinstance(node, (ast.ImportFrom, ast.Import))): continue (file_name, file_path) = find_path(node, pathfile) if (file_name == 'transonic'): (codes_dependance[func], jitted_dicts, spe, treat) = adapt_code_dependance(func, codes_dependance[func], jitted_dicts) special = (special + spe) treated = (treated + treat) for (func, dep) in codes_dependance.items(): if (not dep): continue module_ext = extast.parse(dep) for node in module_ext.body: if (not isinstance(node, (ast.ImportFrom, ast.Import))): continue (file_name, file_path) = find_path(node, pathfile) if (not (file_name and (file_name not in treated))): continue new_file_name = f'__ext__{func}__{file_name}' try: with open(str(file_path), 'r') as file: content = file.read() except: raise NotImplementedError((file_name + ' can not be found')) mod = extast.parse(content) code_ext[classes][new_file_name] = str(filter_external_code(mod, node.names)) codes_dependance[func] = change_import_name(codes_dependance[func], node, func, relative) if code_ext[classes][new_file_name]: get_exterior_code({func: code_ext[classes][new_file_name]}, pathfile, new_file_name, classes) if previous_file_name: code_ext[classes][previous_file_name] = change_import_name(code_ext[classes][previous_file_name], node, func, relative) return (codes_dependance, code_ext, jitted_dicts, special)
Get all imported functions needed by boosted functions and methods at multiple levels, (i.e get functions needed by functions imported by boosted function) and add them into code_ext
transonic/analyses/util.py
get_exterior_code
fluiddyn/transonic
88
python
def get_exterior_code(codes_dependance: dict, pathfile: str, previous_file_name=None, classes: str=None, relative: bool=None, jitted_dicts: dict=None): 'Get all imported functions needed by boosted functions and methods at multiple levels,\n (i.e get functions needed by functions imported by boosted function) and add them into code_ext\n ' special = [] treated = [] for (func, dep) in codes_dependance.items(): if (not dep): continue module_ext = extast.parse(dep) for node in module_ext.body: if (not isinstance(node, (ast.ImportFrom, ast.Import))): continue (file_name, file_path) = find_path(node, pathfile) if (file_name == 'transonic'): (codes_dependance[func], jitted_dicts, spe, treat) = adapt_code_dependance(func, codes_dependance[func], jitted_dicts) special = (special + spe) treated = (treated + treat) for (func, dep) in codes_dependance.items(): if (not dep): continue module_ext = extast.parse(dep) for node in module_ext.body: if (not isinstance(node, (ast.ImportFrom, ast.Import))): continue (file_name, file_path) = find_path(node, pathfile) if (not (file_name and (file_name not in treated))): continue new_file_name = f'__ext__{func}__{file_name}' try: with open(str(file_path), 'r') as file: content = file.read() except: raise NotImplementedError((file_name + ' can not be found')) mod = extast.parse(content) code_ext[classes][new_file_name] = str(filter_external_code(mod, node.names)) codes_dependance[func] = change_import_name(codes_dependance[func], node, func, relative) if code_ext[classes][new_file_name]: get_exterior_code({func: code_ext[classes][new_file_name]}, pathfile, new_file_name, classes) if previous_file_name: code_ext[classes][previous_file_name] = change_import_name(code_ext[classes][previous_file_name], node, func, relative) return (codes_dependance, code_ext, jitted_dicts, special)
def get_exterior_code(codes_dependance: dict, pathfile: str, previous_file_name=None, classes: str=None, relative: bool=None, jitted_dicts: dict=None): 'Get all imported functions needed by boosted functions and methods at multiple levels,\n (i.e get functions needed by functions imported by boosted function) and add them into code_ext\n ' special = [] treated = [] for (func, dep) in codes_dependance.items(): if (not dep): continue module_ext = extast.parse(dep) for node in module_ext.body: if (not isinstance(node, (ast.ImportFrom, ast.Import))): continue (file_name, file_path) = find_path(node, pathfile) if (file_name == 'transonic'): (codes_dependance[func], jitted_dicts, spe, treat) = adapt_code_dependance(func, codes_dependance[func], jitted_dicts) special = (special + spe) treated = (treated + treat) for (func, dep) in codes_dependance.items(): if (not dep): continue module_ext = extast.parse(dep) for node in module_ext.body: if (not isinstance(node, (ast.ImportFrom, ast.Import))): continue (file_name, file_path) = find_path(node, pathfile) if (not (file_name and (file_name not in treated))): continue new_file_name = f'__ext__{func}__{file_name}' try: with open(str(file_path), 'r') as file: content = file.read() except: raise NotImplementedError((file_name + ' can not be found')) mod = extast.parse(content) code_ext[classes][new_file_name] = str(filter_external_code(mod, node.names)) codes_dependance[func] = change_import_name(codes_dependance[func], node, func, relative) if code_ext[classes][new_file_name]: get_exterior_code({func: code_ext[classes][new_file_name]}, pathfile, new_file_name, classes) if previous_file_name: code_ext[classes][previous_file_name] = change_import_name(code_ext[classes][previous_file_name], node, func, relative) return (codes_dependance, code_ext, jitted_dicts, special)<|docstring|>Get all imported functions needed by boosted functions and methods at multiple levels, (i.e get functions needed by functions imported by boosted function) and add them into code_ext<|endoftext|>
3a6e6af5da3a67c71315931b770b82760077d07d384cf91d3bcec28307537523
def parse_disease(self, url): '\n 解析疾病页面\n ' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 Maxthon/5.2.1.6000'} html = requests.get(url, headers=headers) html.encoding = 'gbk' d = pq(html.text) name = d('div.spreadhead > div.tit.clearfix > a > h1').eq(0).text() intro = d('dl.intro > dd').eq(0).text() if intro.endswith('详细>>'): intro = intro[:(- 4)] dds = d('div.info > ul > li') dict1 = dict() dict1['url'] = url dict1['疾病名称'] = name dict1['简介'] = intro for i in range(len(dds)): label = dds.eq(i)('i').eq(0).text() s = dds.eq(i).text() if s.endswith('[详细]'): s = s[:(- 4)].strip() ss = [i.strip() for i in s.split(':')] content = dds.eq(i)('a') if (content and (ss[0] in ['典型症状', '临床检查', '并发症', '手术', '常用药品'])): ll = list() for ii in range(len(content)): if content.eq(ii).attr.title: ll.append(content.eq(ii).attr.title) dict1[ss[0]] = ll else: dict1[ss[0]] = ss[1] drug = d('.drug > ul >li').eq(0) if drug: aa = drug('a') if aa: ll = list() for i in range(len(aa)): if aa.get(i).attr.title: ll.append(aa.get(i).attr.title) dict1[drug('i').text()[:(- 1)]] = ll return dict1
解析疾病页面
requestProj/39jiankang/health39util.py
parse_disease
mayi140611/crawl
1
python
def parse_disease(self, url): '\n \n ' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 Maxthon/5.2.1.6000'} html = requests.get(url, headers=headers) html.encoding = 'gbk' d = pq(html.text) name = d('div.spreadhead > div.tit.clearfix > a > h1').eq(0).text() intro = d('dl.intro > dd').eq(0).text() if intro.endswith('详细>>'): intro = intro[:(- 4)] dds = d('div.info > ul > li') dict1 = dict() dict1['url'] = url dict1['疾病名称'] = name dict1['简介'] = intro for i in range(len(dds)): label = dds.eq(i)('i').eq(0).text() s = dds.eq(i).text() if s.endswith('[详细]'): s = s[:(- 4)].strip() ss = [i.strip() for i in s.split(':')] content = dds.eq(i)('a') if (content and (ss[0] in ['典型症状', '临床检查', '并发症', '手术', '常用药品'])): ll = list() for ii in range(len(content)): if content.eq(ii).attr.title: ll.append(content.eq(ii).attr.title) dict1[ss[0]] = ll else: dict1[ss[0]] = ss[1] drug = d('.drug > ul >li').eq(0) if drug: aa = drug('a') if aa: ll = list() for i in range(len(aa)): if aa.get(i).attr.title: ll.append(aa.get(i).attr.title) dict1[drug('i').text()[:(- 1)]] = ll return dict1
def parse_disease(self, url): '\n \n ' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 Maxthon/5.2.1.6000'} html = requests.get(url, headers=headers) html.encoding = 'gbk' d = pq(html.text) name = d('div.spreadhead > div.tit.clearfix > a > h1').eq(0).text() intro = d('dl.intro > dd').eq(0).text() if intro.endswith('详细>>'): intro = intro[:(- 4)] dds = d('div.info > ul > li') dict1 = dict() dict1['url'] = url dict1['疾病名称'] = name dict1['简介'] = intro for i in range(len(dds)): label = dds.eq(i)('i').eq(0).text() s = dds.eq(i).text() if s.endswith('[详细]'): s = s[:(- 4)].strip() ss = [i.strip() for i in s.split(':')] content = dds.eq(i)('a') if (content and (ss[0] in ['典型症状', '临床检查', '并发症', '手术', '常用药品'])): ll = list() for ii in range(len(content)): if content.eq(ii).attr.title: ll.append(content.eq(ii).attr.title) dict1[ss[0]] = ll else: dict1[ss[0]] = ss[1] drug = d('.drug > ul >li').eq(0) if drug: aa = drug('a') if aa: ll = list() for i in range(len(aa)): if aa.get(i).attr.title: ll.append(aa.get(i).attr.title) dict1[drug('i').text()[:(- 1)]] = ll return dict1<|docstring|>解析疾病页面<|endoftext|>
ed1bfe8f3ef738ec370d9b45ef64a125b911757440808681c3a6bfbedb60cf85
def setUp(self): 'Set up the test case.' self.regex = SeqparseRegexMixin()
Set up the test case.
seqparse/test/test_regex.py
setUp
hoafaloaf/seqparse
1
python
def setUp(self): self.regex = SeqparseRegexMixin()
def setUp(self): self.regex = SeqparseRegexMixin()<|docstring|>Set up the test case.<|endoftext|>
55813b4e469bd84381ebca9b95a1b014ac9df4691b09a6bce9298703c35681bb
def test_bits_match(self): 'SeqparseRegexMixin: Test the bits_match method.' good_chunks = [('0001', dict(first='0001', last=None, step=None)), ('001-002', dict(first='001', last='002', step=None)), ('1-2', dict(first='1', last='2', step=None)), ('1-10', dict(first='1', last='10', step=None)), ('0001-0010x2', dict(first='0001', last='0010', step='2')), ('001-101x2', dict(first='001', last='101', step='2')), ('1-11x2', dict(first='1', last='11', step='2'))] bad_chunks = ['-0001', '0001-', '0001x2', 'x2'] print('\n\n GOOD CHUNKS\n -----------') for (chunk, result) in good_chunks: bits_dict = self.regex.bits_match(chunk, as_dict=True) print(' o "{}" --> {}'.format(chunk, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('first', 'last', 'step'))) self.assertEqual(self.regex.bits_match(chunk), result_tuple) print('\n BAD SEQUENCES\n -------------') for chunk in bad_chunks: print(' o "{}"'.format(chunk)) self.assertIsNone(self.regex.bits_match(chunk)) print('')
SeqparseRegexMixin: Test the bits_match method.
seqparse/test/test_regex.py
test_bits_match
hoafaloaf/seqparse
1
python
def test_bits_match(self): good_chunks = [('0001', dict(first='0001', last=None, step=None)), ('001-002', dict(first='001', last='002', step=None)), ('1-2', dict(first='1', last='2', step=None)), ('1-10', dict(first='1', last='10', step=None)), ('0001-0010x2', dict(first='0001', last='0010', step='2')), ('001-101x2', dict(first='001', last='101', step='2')), ('1-11x2', dict(first='1', last='11', step='2'))] bad_chunks = ['-0001', '0001-', '0001x2', 'x2'] print('\n\n GOOD CHUNKS\n -----------') for (chunk, result) in good_chunks: bits_dict = self.regex.bits_match(chunk, as_dict=True) print(' o "{}" --> {}'.format(chunk, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('first', 'last', 'step'))) self.assertEqual(self.regex.bits_match(chunk), result_tuple) print('\n BAD SEQUENCES\n -------------') for chunk in bad_chunks: print(' o "{}"'.format(chunk)) self.assertIsNone(self.regex.bits_match(chunk)) print()
def test_bits_match(self): good_chunks = [('0001', dict(first='0001', last=None, step=None)), ('001-002', dict(first='001', last='002', step=None)), ('1-2', dict(first='1', last='2', step=None)), ('1-10', dict(first='1', last='10', step=None)), ('0001-0010x2', dict(first='0001', last='0010', step='2')), ('001-101x2', dict(first='001', last='101', step='2')), ('1-11x2', dict(first='1', last='11', step='2'))] bad_chunks = ['-0001', '0001-', '0001x2', 'x2'] print('\n\n GOOD CHUNKS\n -----------') for (chunk, result) in good_chunks: bits_dict = self.regex.bits_match(chunk, as_dict=True) print(' o "{}" --> {}'.format(chunk, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('first', 'last', 'step'))) self.assertEqual(self.regex.bits_match(chunk), result_tuple) print('\n BAD SEQUENCES\n -------------') for chunk in bad_chunks: print(' o "{}"'.format(chunk)) self.assertIsNone(self.regex.bits_match(chunk)) print()<|docstring|>SeqparseRegexMixin: Test the bits_match method.<|endoftext|>
52cb261bcd2dea3bb31c7763fcc941ac483f60fe0139f64bfeffc24304622024
def test_file_name_match(self): 'SeqparseRegexMixin: Test the file_name_match method.' good_names = [('0001.exr', dict(name=None, frame='0001', ext='exr')), ('kitty.1.jpg', dict(name='kitty', frame='1', ext='jpg')), ('/i/like/cats/kitty.0001.tif'.replace('/', os.sep), dict(name='/i/like/cats/kitty'.replace('/', os.sep), frame='0001', ext='tif'))] bad_names = ['kitty.0001', '1', '.111', '111.', '.22.tif'] bad_names.extend(self._singletons) print('\n\n GOOD NAMES\n ----------') for (file_name, result) in good_names: bits_dict = self.regex.file_name_match(file_name, as_dict=True) print(' o "{}" --> {}'.format(file_name, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('name', 'frame', 'ext'))) self.assertEqual(self.regex.file_name_match(file_name), result_tuple) print('\n BAD SEQUENCES\n -------------') for file_name in bad_names: print(' o "{}"'.format(file_name)) self.assertIsNone(self.regex.file_name_match(file_name)) print('')
SeqparseRegexMixin: Test the file_name_match method.
seqparse/test/test_regex.py
test_file_name_match
hoafaloaf/seqparse
1
python
def test_file_name_match(self): good_names = [('0001.exr', dict(name=None, frame='0001', ext='exr')), ('kitty.1.jpg', dict(name='kitty', frame='1', ext='jpg')), ('/i/like/cats/kitty.0001.tif'.replace('/', os.sep), dict(name='/i/like/cats/kitty'.replace('/', os.sep), frame='0001', ext='tif'))] bad_names = ['kitty.0001', '1', '.111', '111.', '.22.tif'] bad_names.extend(self._singletons) print('\n\n GOOD NAMES\n ----------') for (file_name, result) in good_names: bits_dict = self.regex.file_name_match(file_name, as_dict=True) print(' o "{}" --> {}'.format(file_name, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('name', 'frame', 'ext'))) self.assertEqual(self.regex.file_name_match(file_name), result_tuple) print('\n BAD SEQUENCES\n -------------') for file_name in bad_names: print(' o "{}"'.format(file_name)) self.assertIsNone(self.regex.file_name_match(file_name)) print()
def test_file_name_match(self): good_names = [('0001.exr', dict(name=None, frame='0001', ext='exr')), ('kitty.1.jpg', dict(name='kitty', frame='1', ext='jpg')), ('/i/like/cats/kitty.0001.tif'.replace('/', os.sep), dict(name='/i/like/cats/kitty'.replace('/', os.sep), frame='0001', ext='tif'))] bad_names = ['kitty.0001', '1', '.111', '111.', '.22.tif'] bad_names.extend(self._singletons) print('\n\n GOOD NAMES\n ----------') for (file_name, result) in good_names: bits_dict = self.regex.file_name_match(file_name, as_dict=True) print(' o "{}" --> {}'.format(file_name, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('name', 'frame', 'ext'))) self.assertEqual(self.regex.file_name_match(file_name), result_tuple) print('\n BAD SEQUENCES\n -------------') for file_name in bad_names: print(' o "{}"'.format(file_name)) self.assertIsNone(self.regex.file_name_match(file_name)) print()<|docstring|>SeqparseRegexMixin: Test the file_name_match method.<|endoftext|>
cbd14c1e68371be2e18ef10e16ff540a808e6727959604e7a86d5614ed0246d9
def test_file_seq_match(self): 'SeqparseRegexMixin: Test the file_seq_match method.' good_names = [('0001-0011.exr', dict(name=None, frames='0001-0011', ext='exr')), ('kitty.1,3,9.jpg', dict(name='kitty', frames='1,3,9', ext='jpg')), ('/i/like/cats/kitty.11,22-33.tif'.replace('/', os.sep), dict(name='/i/like/cats/kitty'.replace('/', os.sep), frames='11,22-33', ext='tif'))] bad_names = ['kitty.0001-0011', '1,3,9', '.111', '111.', '.22.tif'] bad_names.extend(self._singletons) print('\n\n GOOD NAMES\n ----------') for (frame_seq, result) in good_names: bits_dict = self.regex.file_seq_match(frame_seq, as_dict=True) print(' o "{}" --> {}'.format(frame_seq, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('name', 'frames', 'ext'))) self.assertEqual(self.regex.file_seq_match(frame_seq), result_tuple) print('\n BAD SEQUENCES\n -------------') for frame_seq in bad_names: print(' o "{}"'.format(frame_seq)) bits_dict = self.regex.bits_match(frame_seq, as_dict=True) self.assertIsNone(self.regex.file_seq_match(frame_seq)) print('')
SeqparseRegexMixin: Test the file_seq_match method.
seqparse/test/test_regex.py
test_file_seq_match
hoafaloaf/seqparse
1
python
def test_file_seq_match(self): good_names = [('0001-0011.exr', dict(name=None, frames='0001-0011', ext='exr')), ('kitty.1,3,9.jpg', dict(name='kitty', frames='1,3,9', ext='jpg')), ('/i/like/cats/kitty.11,22-33.tif'.replace('/', os.sep), dict(name='/i/like/cats/kitty'.replace('/', os.sep), frames='11,22-33', ext='tif'))] bad_names = ['kitty.0001-0011', '1,3,9', '.111', '111.', '.22.tif'] bad_names.extend(self._singletons) print('\n\n GOOD NAMES\n ----------') for (frame_seq, result) in good_names: bits_dict = self.regex.file_seq_match(frame_seq, as_dict=True) print(' o "{}" --> {}'.format(frame_seq, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('name', 'frames', 'ext'))) self.assertEqual(self.regex.file_seq_match(frame_seq), result_tuple) print('\n BAD SEQUENCES\n -------------') for frame_seq in bad_names: print(' o "{}"'.format(frame_seq)) bits_dict = self.regex.bits_match(frame_seq, as_dict=True) self.assertIsNone(self.regex.file_seq_match(frame_seq)) print()
def test_file_seq_match(self): good_names = [('0001-0011.exr', dict(name=None, frames='0001-0011', ext='exr')), ('kitty.1,3,9.jpg', dict(name='kitty', frames='1,3,9', ext='jpg')), ('/i/like/cats/kitty.11,22-33.tif'.replace('/', os.sep), dict(name='/i/like/cats/kitty'.replace('/', os.sep), frames='11,22-33', ext='tif'))] bad_names = ['kitty.0001-0011', '1,3,9', '.111', '111.', '.22.tif'] bad_names.extend(self._singletons) print('\n\n GOOD NAMES\n ----------') for (frame_seq, result) in good_names: bits_dict = self.regex.file_seq_match(frame_seq, as_dict=True) print(' o "{}" --> {}'.format(frame_seq, bits_dict)) self.assertEqual(bits_dict, result) result_tuple = tuple((bits_dict[x] for x in ('name', 'frames', 'ext'))) self.assertEqual(self.regex.file_seq_match(frame_seq), result_tuple) print('\n BAD SEQUENCES\n -------------') for frame_seq in bad_names: print(' o "{}"'.format(frame_seq)) bits_dict = self.regex.bits_match(frame_seq, as_dict=True) self.assertIsNone(self.regex.file_seq_match(frame_seq)) print()<|docstring|>SeqparseRegexMixin: Test the file_seq_match method.<|endoftext|>
0bb9d55df05e8f059f1a4af69a3d0a65636da0e907623dd17c3b21b64782f0d6
def test_is_frame_sequence(self): 'SeqparseRegexMixin: Test the is_file_sequence method.' good_frame_seqs = ['0001', ',0001', '0001,', '0001-0001', '0001-0001x0', '0001-0003x3', '0001,0003', '0001,,0003', '0001-0010', '0001-0010x0', '0001-0011x2', '0001-0012x2', '0001-0005,0007-0010', '0001-0005x2,0007-0010', '0001-0005,0007-0011x2', '0001-0005,0006,0008-0012x2', '0001,0003-0007,0009-0015x2'] bad_frame_seqs = ['-0001', '0001-', '0001x2', 'x2', '0001,0003x2', '0001-0005x', 'x', ',', ',,', ''] print('\n\n GOOD SEQUENCES\n --------------') for frame_seq in good_frame_seqs: print(' o "{}"'.format(frame_seq)) self.assertTrue(self.regex.is_frame_sequence(frame_seq)) print('\n BAD SEQUENCES\n -------------') for frame_seq in bad_frame_seqs: print(' o "{}"'.format(frame_seq)) self.assertFalse(self.regex.is_frame_sequence(frame_seq)) print('')
SeqparseRegexMixin: Test the is_file_sequence method.
seqparse/test/test_regex.py
test_is_frame_sequence
hoafaloaf/seqparse
1
python
def test_is_frame_sequence(self): good_frame_seqs = ['0001', ',0001', '0001,', '0001-0001', '0001-0001x0', '0001-0003x3', '0001,0003', '0001,,0003', '0001-0010', '0001-0010x0', '0001-0011x2', '0001-0012x2', '0001-0005,0007-0010', '0001-0005x2,0007-0010', '0001-0005,0007-0011x2', '0001-0005,0006,0008-0012x2', '0001,0003-0007,0009-0015x2'] bad_frame_seqs = ['-0001', '0001-', '0001x2', 'x2', '0001,0003x2', '0001-0005x', 'x', ',', ',,', ] print('\n\n GOOD SEQUENCES\n --------------') for frame_seq in good_frame_seqs: print(' o "{}"'.format(frame_seq)) self.assertTrue(self.regex.is_frame_sequence(frame_seq)) print('\n BAD SEQUENCES\n -------------') for frame_seq in bad_frame_seqs: print(' o "{}"'.format(frame_seq)) self.assertFalse(self.regex.is_frame_sequence(frame_seq)) print()
def test_is_frame_sequence(self): good_frame_seqs = ['0001', ',0001', '0001,', '0001-0001', '0001-0001x0', '0001-0003x3', '0001,0003', '0001,,0003', '0001-0010', '0001-0010x0', '0001-0011x2', '0001-0012x2', '0001-0005,0007-0010', '0001-0005x2,0007-0010', '0001-0005,0007-0011x2', '0001-0005,0006,0008-0012x2', '0001,0003-0007,0009-0015x2'] bad_frame_seqs = ['-0001', '0001-', '0001x2', 'x2', '0001,0003x2', '0001-0005x', 'x', ',', ',,', ] print('\n\n GOOD SEQUENCES\n --------------') for frame_seq in good_frame_seqs: print(' o "{}"'.format(frame_seq)) self.assertTrue(self.regex.is_frame_sequence(frame_seq)) print('\n BAD SEQUENCES\n -------------') for frame_seq in bad_frame_seqs: print(' o "{}"'.format(frame_seq)) self.assertFalse(self.regex.is_frame_sequence(frame_seq)) print()<|docstring|>SeqparseRegexMixin: Test the is_file_sequence method.<|endoftext|>
74869559f9303564fe353192a596564375520e2998d4672008037f8d81cec693
def kats_Prophet_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n Calls Kats' Prophet forecasting model, but ignores t if supplied.\n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = ProphetParams(seasonality_mode='multiplicative') m = ProphetModel(train_data, params) m.fit() fcst = m.predict(steps=k, freq='H') x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)
Calls Kats' Prophet forecasting model, but ignores t if supplied.
timemachines/skaters/kts/ktswrappers.py
kats_Prophet_iskater
iklasky/timemachines
0
python
def kats_Prophet_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n \n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = ProphetParams(seasonality_mode='multiplicative') m = ProphetModel(train_data, params) m.fit() fcst = m.predict(steps=k, freq='H') x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)
def kats_Prophet_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n \n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = ProphetParams(seasonality_mode='multiplicative') m = ProphetModel(train_data, params) m.fit() fcst = m.predict(steps=k, freq='H') x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)<|docstring|>Calls Kats' Prophet forecasting model, but ignores t if supplied.<|endoftext|>
379ee867ee8eb63234e1af534515d34fd67a9708119c95bfef23b268aa8c3593
def kats_HoltWinters_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n Calls Kats' Holt-Winters forecasting model, but ignores t if supplied.\n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = HoltWintersParams(trend='add') m = HoltWintersModel(data=train_data, params=params) m.fit() fcst = m.predict(steps=k, alpha=0.5) x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)
Calls Kats' Holt-Winters forecasting model, but ignores t if supplied.
timemachines/skaters/kts/ktswrappers.py
kats_HoltWinters_iskater
iklasky/timemachines
0
python
def kats_HoltWinters_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n \n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = HoltWintersParams(trend='add') m = HoltWintersModel(data=train_data, params=params) m.fit() fcst = m.predict(steps=k, alpha=0.5) x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)
def kats_HoltWinters_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n \n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = HoltWintersParams(trend='add') m = HoltWintersModel(data=train_data, params=params) m.fit() fcst = m.predict(steps=k, alpha=0.5) x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)<|docstring|>Calls Kats' Holt-Winters forecasting model, but ignores t if supplied.<|endoftext|>
d0a6d7ecf8ac658d49e509c860039ff3559ef56ab626de5a97c0e6c812c53f9b
def kats_quadratic_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n Calls Kats' quadratic regressions forecasting model, but ignores t if supplied.\n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = QuadraticModelParams() m = QuadraticModel(train_data, params) m.fit() fcst = m.predict(steps=k) x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)
Calls Kats' quadratic regressions forecasting model, but ignores t if supplied.
timemachines/skaters/kts/ktswrappers.py
kats_quadratic_iskater
iklasky/timemachines
0
python
def kats_quadratic_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n \n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = QuadraticModelParams() m = QuadraticModel(train_data, params) m.fit() fcst = m.predict(steps=k) x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)
def kats_quadratic_iskater(y: [[float]], k: int, a: List=None, t: List=None, e=None, deseasonalize=False): "\n \n " if a: assert (len(a) == (len(y) + k)) if np.isscalar(y[0]): y0s = [yt for yt in y] else: y0s = [yt[0] for yt in y] idx = pd.date_range(end='01/01/2000', periods=len(y0s), freq='H') df = pd.DataFrame(y0s, index=idx).rename(columns={0: 'y'}).reset_index() df.columns = ['time', 'value'] train_data = TimeSeriesData(df.head(df.shape[0])) params = QuadraticModelParams() m = QuadraticModel(train_data, params) m.fit() fcst = m.predict(steps=k) x = list(fcst.fcst.values) x_std = ([1] * k) return (x, x_std)<|docstring|>Calls Kats' quadratic regressions forecasting model, but ignores t if supplied.<|endoftext|>
d2ea532b59d2a062dbea15f60509e3ab46a0467a3342671422055d8ba144dafb
def test_post(self): 'Testing for what the user posts to see if it meets the standards' response = self.client.post('/api/v1/parcels', data=json.dumps(self.data), content_type='application/json') assert (response.status_code == 201)
Testing for what the user posts to see if it meets the standards
app/Tests/test_sendit.py
test_post
kiruidavid/Sendit254
0
python
def test_post(self): response = self.client.post('/api/v1/parcels', data=json.dumps(self.data), content_type='application/json') assert (response.status_code == 201)
def test_post(self): response = self.client.post('/api/v1/parcels', data=json.dumps(self.data), content_type='application/json') assert (response.status_code == 201)<|docstring|>Testing for what the user posts to see if it meets the standards<|endoftext|>
7385098b46229999448f40104a2f75a4dbd7c53a99141b0427370abf4964b2d5
def test_blank_user_id(self): 'Testing for if the wrong data if the validations work' response = self.client.post('/api/v1/parcels', data=json.dumps(self.wrong_data), content_type='application/json') assert (response.status_code == 400)
Testing for if the wrong data if the validations work
app/Tests/test_sendit.py
test_blank_user_id
kiruidavid/Sendit254
0
python
def test_blank_user_id(self): response = self.client.post('/api/v1/parcels', data=json.dumps(self.wrong_data), content_type='application/json') assert (response.status_code == 400)
def test_blank_user_id(self): response = self.client.post('/api/v1/parcels', data=json.dumps(self.wrong_data), content_type='application/json') assert (response.status_code == 400)<|docstring|>Testing for if the wrong data if the validations work<|endoftext|>
fa1997d44aa86cf54e25e8d9fb85a3a075d3ad6cb1f458e76ea3d5136e575d35
def test_get(self): 'Testing for the get methods' response = self.client.get('/api/v1/parcels') assert (response.status_code == 200)
Testing for the get methods
app/Tests/test_sendit.py
test_get
kiruidavid/Sendit254
0
python
def test_get(self): response = self.client.get('/api/v1/parcels') assert (response.status_code == 200)
def test_get(self): response = self.client.get('/api/v1/parcels') assert (response.status_code == 200)<|docstring|>Testing for the get methods<|endoftext|>
ac2576f0ee00033906fa0be48fbede7951d323afb531e1aab2f5416a322d73b2
def test_getparcel(self): 'Testing if getting a single delivery url works with the right delivery_id' response = self.client.get('/api/v1/parcels/1') assert (response.status_code == 200)
Testing if getting a single delivery url works with the right delivery_id
app/Tests/test_sendit.py
test_getparcel
kiruidavid/Sendit254
0
python
def test_getparcel(self): response = self.client.get('/api/v1/parcels/1') assert (response.status_code == 200)
def test_getparcel(self): response = self.client.get('/api/v1/parcels/1') assert (response.status_code == 200)<|docstring|>Testing if getting a single delivery url works with the right delivery_id<|endoftext|>
4523725a0df163d6fff3f8d60dc7911ecbcbb6b18e7093f005e414f87731593e
def test_wrong_url(self): 'Testing if tusing a string instead of an int and if the error response works' response = self.client.get('/api/v1/parcels/z') assert (response.status_code == 404)
Testing if tusing a string instead of an int and if the error response works
app/Tests/test_sendit.py
test_wrong_url
kiruidavid/Sendit254
0
python
def test_wrong_url(self): response = self.client.get('/api/v1/parcels/z') assert (response.status_code == 404)
def test_wrong_url(self): response = self.client.get('/api/v1/parcels/z') assert (response.status_code == 404)<|docstring|>Testing if tusing a string instead of an int and if the error response works<|endoftext|>
c9bf86bd66de1a693750ec45dd1a04c3b475523697bee33eff893a1454aca2a3
def test_get_excess(self): 'Testing for getting an excess delivery_id and if the error response works' response = self.client.get('/api/v1/parcels/3') assert (response.status_code == 400)
Testing for getting an excess delivery_id and if the error response works
app/Tests/test_sendit.py
test_get_excess
kiruidavid/Sendit254
0
python
def test_get_excess(self): response = self.client.get('/api/v1/parcels/3') assert (response.status_code == 400)
def test_get_excess(self): response = self.client.get('/api/v1/parcels/3') assert (response.status_code == 400)<|docstring|>Testing for getting an excess delivery_id and if the error response works<|endoftext|>
ccc5775bd4a1fc3b1479be2d094d8b70f2e42cf24be01208c623e3266e962ca7
def test_get_user(self): 'Testing if geting parcel using the delivery_id works' response = self.client.get('/api/v1/users/5/parcels') assert (response.status_code == 200)
Testing if geting parcel using the delivery_id works
app/Tests/test_sendit.py
test_get_user
kiruidavid/Sendit254
0
python
def test_get_user(self): response = self.client.get('/api/v1/users/5/parcels') assert (response.status_code == 200)
def test_get_user(self): response = self.client.get('/api/v1/users/5/parcels') assert (response.status_code == 200)<|docstring|>Testing if geting parcel using the delivery_id works<|endoftext|>
937bcaffb87312e634632019c6a327eea225eafeda6442a3d625fccf394d0101
def test_url_entry(self): 'Testing if using the wrong url works and it returns the expected error response' response = self.client.get('/api/v1/users/e/parcels') assert (response.status_code == 404)
Testing if using the wrong url works and it returns the expected error response
app/Tests/test_sendit.py
test_url_entry
kiruidavid/Sendit254
0
python
def test_url_entry(self): response = self.client.get('/api/v1/users/e/parcels') assert (response.status_code == 404)
def test_url_entry(self): response = self.client.get('/api/v1/users/e/parcels') assert (response.status_code == 404)<|docstring|>Testing if using the wrong url works and it returns the expected error response<|endoftext|>
39976fc571213c8d264792dcab94b9bbf86526165917022ee9f365cfa66a8642
def test_wrong_user(self): 'Testing if using the wrong user_id works and the expected error response' response = self.client.get('/api/v1/users/3/parcels') assert (response.status_code == 400)
Testing if using the wrong user_id works and the expected error response
app/Tests/test_sendit.py
test_wrong_user
kiruidavid/Sendit254
0
python
def test_wrong_user(self): response = self.client.get('/api/v1/users/3/parcels') assert (response.status_code == 400)
def test_wrong_user(self): response = self.client.get('/api/v1/users/3/parcels') assert (response.status_code == 400)<|docstring|>Testing if using the wrong user_id works and the expected error response<|endoftext|>
ae1e04f47455a2f26ca55eab1c8cf683e76cb01f7da14d782e35fdc21731869e
def test_cancel(self): 'Testing if using the right url to update the status works' response = self.client.put('/api/v1/parcels/1/cancel/') assert (response.status_code == 200)
Testing if using the right url to update the status works
app/Tests/test_sendit.py
test_cancel
kiruidavid/Sendit254
0
python
def test_cancel(self): response = self.client.put('/api/v1/parcels/1/cancel/') assert (response.status_code == 200)
def test_cancel(self): response = self.client.put('/api/v1/parcels/1/cancel/') assert (response.status_code == 200)<|docstring|>Testing if using the right url to update the status works<|endoftext|>
09704bbf700045a3c69f9125db787bdc5f3578ad2ba6f2e0e68e007efc6cdf91
@idxDecorator(as_ind=False) def _indices_equality_match_on_catalog(catalog: _TBL_TYPE, other: _TBL_TYPE, fields: _FIELDS_TYPE) -> _IDX_TYPE: 'Indices of catalog data field(s) to match against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n Note that this only matches `other` against `catalog`, meaning\n `catalog` can still have values which do not appear in `other`\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : recarray\n the source catalog against which the `other` catalog is matched.\n other : recarray\n match this against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idx : ndarray\n indices into `other` such that only has values in `fields` that\n are in `catalog`.\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' uns: T.Tuple[np.array] uns = (np.unique(np.array(catalog[n])) for n in fields) idxs = ((other[n] == un[(:, None)]) for (n, un) in zip(fields, uns)) idx: _IDX_TYPE idx = np.sum(functools.reduce(np.logical_and, idxs), axis=0, dtype=bool) return idx
Indices of catalog data field(s) to match against a source catalog. This function is for discrete-valued data, such as tags. Note that this only matches `other` against `catalog`, meaning `catalog` can still have values which do not appear in `other` For coordinates, see `~indices_xmatch_coords`. This match is done on all the fields simultaneously, so in terms or a 2D array, two rows are considered a match only if all the values in the columns `fields` match. Parameters ---------- catalog : recarray the source catalog against which the `other` catalog is matched. other : recarray match this against `catalog` fields : list List of fields on which to match. ex, ["color", "location"] where both `catalog` and `other` have those columns, hopefully with some matching values. Returns ------- idx : ndarray indices into `other` such that only has values in `fields` that are in `catalog`. Notes ----- .. todo:: try more axes tricks to avoid loops.
utilipy/data_utils/crossmatch.py
_indices_equality_match_on_catalog
nstarman/utilipy
2
python
@idxDecorator(as_ind=False) def _indices_equality_match_on_catalog(catalog: _TBL_TYPE, other: _TBL_TYPE, fields: _FIELDS_TYPE) -> _IDX_TYPE: 'Indices of catalog data field(s) to match against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n Note that this only matches `other` against `catalog`, meaning\n `catalog` can still have values which do not appear in `other`\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : recarray\n the source catalog against which the `other` catalog is matched.\n other : recarray\n match this against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idx : ndarray\n indices into `other` such that only has values in `fields` that\n are in `catalog`.\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' uns: T.Tuple[np.array] uns = (np.unique(np.array(catalog[n])) for n in fields) idxs = ((other[n] == un[(:, None)]) for (n, un) in zip(fields, uns)) idx: _IDX_TYPE idx = np.sum(functools.reduce(np.logical_and, idxs), axis=0, dtype=bool) return idx
@idxDecorator(as_ind=False) def _indices_equality_match_on_catalog(catalog: _TBL_TYPE, other: _TBL_TYPE, fields: _FIELDS_TYPE) -> _IDX_TYPE: 'Indices of catalog data field(s) to match against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n Note that this only matches `other` against `catalog`, meaning\n `catalog` can still have values which do not appear in `other`\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : recarray\n the source catalog against which the `other` catalog is matched.\n other : recarray\n match this against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idx : ndarray\n indices into `other` such that only has values in `fields` that\n are in `catalog`.\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' uns: T.Tuple[np.array] uns = (np.unique(np.array(catalog[n])) for n in fields) idxs = ((other[n] == un[(:, None)]) for (n, un) in zip(fields, uns)) idx: _IDX_TYPE idx = np.sum(functools.reduce(np.logical_and, idxs), axis=0, dtype=bool) return idx<|docstring|>Indices of catalog data field(s) to match against a source catalog. This function is for discrete-valued data, such as tags. Note that this only matches `other` against `catalog`, meaning `catalog` can still have values which do not appear in `other` For coordinates, see `~indices_xmatch_coords`. This match is done on all the fields simultaneously, so in terms or a 2D array, two rows are considered a match only if all the values in the columns `fields` match. Parameters ---------- catalog : recarray the source catalog against which the `other` catalog is matched. other : recarray match this against `catalog` fields : list List of fields on which to match. ex, ["color", "location"] where both `catalog` and `other` have those columns, hopefully with some matching values. Returns ------- idx : ndarray indices into `other` such that only has values in `fields` that are in `catalog`. Notes ----- .. todo:: try more axes tricks to avoid loops.<|endoftext|>
0f7dd77547927a9dc3bcd9598abb7a7c5edab1c5f713b9a66c9e600a2d787c67
def indices_xmatch_fields(catalog: _TBL_TYPE, *others: _TBL_TYPE, fields: _FIELDS_TYPE) -> T.Tuple[(_IDXS_TYPE, _INFO_TYPE)]: 'Indices of xmatch of catalogs\' data field(s) against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : Table or recarray\n The source catalog against which the `others` catalogs are matched.\n *others : Table or recarray\n match these against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idxs : list of ndarrays\n each element of list is the x-match indices into the ith catalog,\n starting with `catalog`. So the i=0 index list is for `catalog` and\n the i=1 index list is the x-match indices for the first table\n in `others`.\n info : dict\n Useful information. Nothing yet.\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' idxs: _IDXS_TYPE = [_indices_equality_match_on_catalog(catalog, c, fields=fields) for c in others] catalog_idx: _IDX_TYPE = _indices_equality_match_on_catalog(others[1][idxs[0]], catalog, fields) idxs.insert(0, catalog_idx) info: _INFO_TYPE = {} return (idxs, info)
Indices of xmatch of catalogs' data field(s) against a source catalog. This function is for discrete-valued data, such as tags. For coordinates, see `~indices_xmatch_coords`. This match is done on all the fields simultaneously, so in terms or a 2D array, two rows are considered a match only if all the values in the columns `fields` match. Parameters ---------- catalog : Table or recarray The source catalog against which the `others` catalogs are matched. *others : Table or recarray match these against `catalog` fields : list List of fields on which to match. ex, ["color", "location"] where both `catalog` and `other` have those columns, hopefully with some matching values. Returns ------- idxs : list of ndarrays each element of list is the x-match indices into the ith catalog, starting with `catalog`. So the i=0 index list is for `catalog` and the i=1 index list is the x-match indices for the first table in `others`. info : dict Useful information. Nothing yet. Notes ----- .. todo:: try more axes tricks to avoid loops.
utilipy/data_utils/crossmatch.py
indices_xmatch_fields
nstarman/utilipy
2
python
def indices_xmatch_fields(catalog: _TBL_TYPE, *others: _TBL_TYPE, fields: _FIELDS_TYPE) -> T.Tuple[(_IDXS_TYPE, _INFO_TYPE)]: 'Indices of xmatch of catalogs\' data field(s) against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : Table or recarray\n The source catalog against which the `others` catalogs are matched.\n *others : Table or recarray\n match these against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idxs : list of ndarrays\n each element of list is the x-match indices into the ith catalog,\n starting with `catalog`. So the i=0 index list is for `catalog` and\n the i=1 index list is the x-match indices for the first table\n in `others`.\n info : dict\n Useful information. Nothing yet.\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' idxs: _IDXS_TYPE = [_indices_equality_match_on_catalog(catalog, c, fields=fields) for c in others] catalog_idx: _IDX_TYPE = _indices_equality_match_on_catalog(others[1][idxs[0]], catalog, fields) idxs.insert(0, catalog_idx) info: _INFO_TYPE = {} return (idxs, info)
def indices_xmatch_fields(catalog: _TBL_TYPE, *others: _TBL_TYPE, fields: _FIELDS_TYPE) -> T.Tuple[(_IDXS_TYPE, _INFO_TYPE)]: 'Indices of xmatch of catalogs\' data field(s) against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : Table or recarray\n The source catalog against which the `others` catalogs are matched.\n *others : Table or recarray\n match these against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idxs : list of ndarrays\n each element of list is the x-match indices into the ith catalog,\n starting with `catalog`. So the i=0 index list is for `catalog` and\n the i=1 index list is the x-match indices for the first table\n in `others`.\n info : dict\n Useful information. Nothing yet.\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' idxs: _IDXS_TYPE = [_indices_equality_match_on_catalog(catalog, c, fields=fields) for c in others] catalog_idx: _IDX_TYPE = _indices_equality_match_on_catalog(others[1][idxs[0]], catalog, fields) idxs.insert(0, catalog_idx) info: _INFO_TYPE = {} return (idxs, info)<|docstring|>Indices of xmatch of catalogs' data field(s) against a source catalog. This function is for discrete-valued data, such as tags. For coordinates, see `~indices_xmatch_coords`. This match is done on all the fields simultaneously, so in terms or a 2D array, two rows are considered a match only if all the values in the columns `fields` match. Parameters ---------- catalog : Table or recarray The source catalog against which the `others` catalogs are matched. *others : Table or recarray match these against `catalog` fields : list List of fields on which to match. ex, ["color", "location"] where both `catalog` and `other` have those columns, hopefully with some matching values. Returns ------- idxs : list of ndarrays each element of list is the x-match indices into the ith catalog, starting with `catalog`. So the i=0 index list is for `catalog` and the i=1 index list is the x-match indices for the first table in `others`. info : dict Useful information. Nothing yet. Notes ----- .. todo:: try more axes tricks to avoid loops.<|endoftext|>
26778a5a3a4cca82c8af5cd97a67ec5fc00ea1ee6cd3b54ee54cfe15a8867d3a
def xmatch_fields(catalog: _TBL_TYPE, *others: _TBL_TYPE, fields: _FIELDS_TYPE) -> T.Tuple[(T.List[T.Any], _INFO_TYPE)]: 'Cross-match catalogs\' data field(s) against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : Table or recarray\n The source catalog against which the `others` catalogs are matched.\n fields for which there are no matches are also filtered.\n *others : Table or recarray\n match these against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idxs : list of ndarrays\n each element of list is the x-match indices into the ith catalog,\n starting with `catalog`. So the i=0 index list is for `catalog` and\n the i=1 index list is the x-match indices for the first table\n in `others`,\n\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' if (not isinstance(fields, list)): raise TypeError('must be a list') if (len(others) == 0): raise ValueError('Must have at least one catalog against-which to xmatch.') for (i, field) in itertools.product(range((len(others) + 1)), fields): try: if (i == 0): catalog[field] else: others[i][field] except Exception as e: print(f'need to have {field} in catalog {i}') raise e idxs: _IDXS_TYPE info: _INFO_TYPE (idxs, info) = indices_xmatch_fields(catalog, *others, fields=fields) cat_matches = ([catalog[idxs[0]]] + [c[idx] for (c, idx) in zip(others, idxs[1:])]) info.update({'idxs': idxs}) return (cat_matches, info)
Cross-match catalogs' data field(s) against a source catalog. This function is for discrete-valued data, such as tags. For coordinates, see `~indices_xmatch_coords`. This match is done on all the fields simultaneously, so in terms or a 2D array, two rows are considered a match only if all the values in the columns `fields` match. Parameters ---------- catalog : Table or recarray The source catalog against which the `others` catalogs are matched. fields for which there are no matches are also filtered. *others : Table or recarray match these against `catalog` fields : list List of fields on which to match. ex, ["color", "location"] where both `catalog` and `other` have those columns, hopefully with some matching values. Returns ------- idxs : list of ndarrays each element of list is the x-match indices into the ith catalog, starting with `catalog`. So the i=0 index list is for `catalog` and the i=1 index list is the x-match indices for the first table in `others`, Notes ----- .. todo:: try more axes tricks to avoid loops.
utilipy/data_utils/crossmatch.py
xmatch_fields
nstarman/utilipy
2
python
def xmatch_fields(catalog: _TBL_TYPE, *others: _TBL_TYPE, fields: _FIELDS_TYPE) -> T.Tuple[(T.List[T.Any], _INFO_TYPE)]: 'Cross-match catalogs\' data field(s) against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : Table or recarray\n The source catalog against which the `others` catalogs are matched.\n fields for which there are no matches are also filtered.\n *others : Table or recarray\n match these against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idxs : list of ndarrays\n each element of list is the x-match indices into the ith catalog,\n starting with `catalog`. So the i=0 index list is for `catalog` and\n the i=1 index list is the x-match indices for the first table\n in `others`,\n\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' if (not isinstance(fields, list)): raise TypeError('must be a list') if (len(others) == 0): raise ValueError('Must have at least one catalog against-which to xmatch.') for (i, field) in itertools.product(range((len(others) + 1)), fields): try: if (i == 0): catalog[field] else: others[i][field] except Exception as e: print(f'need to have {field} in catalog {i}') raise e idxs: _IDXS_TYPE info: _INFO_TYPE (idxs, info) = indices_xmatch_fields(catalog, *others, fields=fields) cat_matches = ([catalog[idxs[0]]] + [c[idx] for (c, idx) in zip(others, idxs[1:])]) info.update({'idxs': idxs}) return (cat_matches, info)
def xmatch_fields(catalog: _TBL_TYPE, *others: _TBL_TYPE, fields: _FIELDS_TYPE) -> T.Tuple[(T.List[T.Any], _INFO_TYPE)]: 'Cross-match catalogs\' data field(s) against a source catalog.\n\n This function is for discrete-valued data, such as tags.\n For coordinates, see `~indices_xmatch_coords`.\n\n This match is done on all the fields simultaneously, so in terms or\n a 2D array, two rows are considered a match only if all the values\n in the columns `fields` match.\n\n Parameters\n ----------\n catalog : Table or recarray\n The source catalog against which the `others` catalogs are matched.\n fields for which there are no matches are also filtered.\n *others : Table or recarray\n match these against `catalog`\n fields : list\n List of fields on which to match.\n ex, ["color", "location"] where both `catalog` and `other` have\n those columns, hopefully with some matching values.\n\n Returns\n -------\n idxs : list of ndarrays\n each element of list is the x-match indices into the ith catalog,\n starting with `catalog`. So the i=0 index list is for `catalog` and\n the i=1 index list is the x-match indices for the first table\n in `others`,\n\n\n Notes\n -----\n .. todo::\n\n try more axes tricks to avoid loops.\n\n ' if (not isinstance(fields, list)): raise TypeError('must be a list') if (len(others) == 0): raise ValueError('Must have at least one catalog against-which to xmatch.') for (i, field) in itertools.product(range((len(others) + 1)), fields): try: if (i == 0): catalog[field] else: others[i][field] except Exception as e: print(f'need to have {field} in catalog {i}') raise e idxs: _IDXS_TYPE info: _INFO_TYPE (idxs, info) = indices_xmatch_fields(catalog, *others, fields=fields) cat_matches = ([catalog[idxs[0]]] + [c[idx] for (c, idx) in zip(others, idxs[1:])]) info.update({'idxs': idxs}) return (cat_matches, info)<|docstring|>Cross-match catalogs' data field(s) against a source catalog. This function is for discrete-valued data, such as tags. For coordinates, see `~indices_xmatch_coords`. This match is done on all the fields simultaneously, so in terms or a 2D array, two rows are considered a match only if all the values in the columns `fields` match. Parameters ---------- catalog : Table or recarray The source catalog against which the `others` catalogs are matched. fields for which there are no matches are also filtered. *others : Table or recarray match these against `catalog` fields : list List of fields on which to match. ex, ["color", "location"] where both `catalog` and `other` have those columns, hopefully with some matching values. Returns ------- idxs : list of ndarrays each element of list is the x-match indices into the ith catalog, starting with `catalog`. So the i=0 index list is for `catalog` and the i=1 index list is the x-match indices for the first table in `others`, Notes ----- .. todo:: try more axes tricks to avoid loops.<|endoftext|>
77d709a15a07863031df9fecaeb94ac5b3021ea74b735abd621555b1c491a070
def xmatch(*catalogs, match_fields: T.Sequence) -> T.Tuple[(T.List[T.Any], _INFO_TYPE)]: 'Cross-match two catalogs.\n\n .. todo::\n\n - find duplicates before matching ?\n - allow more catalogs to be xmatched\n\n Parameters\n ----------\n cat1, cat2: Any\n the two catalogs to crossmatch\n must be convertible to recarray\n match_fields : str, optional\n data tag on which to additionally cross-match, default None.\n this also works for any discrete-valued data column.\n\n References\n ----------\n https://github.com/jobovy/gaia_tools/\n\n ' (cat_matches, info) = xmatch_fields(*catalogs, fields=match_fields) return (cat_matches, info)
Cross-match two catalogs. .. todo:: - find duplicates before matching ? - allow more catalogs to be xmatched Parameters ---------- cat1, cat2: Any the two catalogs to crossmatch must be convertible to recarray match_fields : str, optional data tag on which to additionally cross-match, default None. this also works for any discrete-valued data column. References ---------- https://github.com/jobovy/gaia_tools/
utilipy/data_utils/crossmatch.py
xmatch
nstarman/utilipy
2
python
def xmatch(*catalogs, match_fields: T.Sequence) -> T.Tuple[(T.List[T.Any], _INFO_TYPE)]: 'Cross-match two catalogs.\n\n .. todo::\n\n - find duplicates before matching ?\n - allow more catalogs to be xmatched\n\n Parameters\n ----------\n cat1, cat2: Any\n the two catalogs to crossmatch\n must be convertible to recarray\n match_fields : str, optional\n data tag on which to additionally cross-match, default None.\n this also works for any discrete-valued data column.\n\n References\n ----------\n https://github.com/jobovy/gaia_tools/\n\n ' (cat_matches, info) = xmatch_fields(*catalogs, fields=match_fields) return (cat_matches, info)
def xmatch(*catalogs, match_fields: T.Sequence) -> T.Tuple[(T.List[T.Any], _INFO_TYPE)]: 'Cross-match two catalogs.\n\n .. todo::\n\n - find duplicates before matching ?\n - allow more catalogs to be xmatched\n\n Parameters\n ----------\n cat1, cat2: Any\n the two catalogs to crossmatch\n must be convertible to recarray\n match_fields : str, optional\n data tag on which to additionally cross-match, default None.\n this also works for any discrete-valued data column.\n\n References\n ----------\n https://github.com/jobovy/gaia_tools/\n\n ' (cat_matches, info) = xmatch_fields(*catalogs, fields=match_fields) return (cat_matches, info)<|docstring|>Cross-match two catalogs. .. todo:: - find duplicates before matching ? - allow more catalogs to be xmatched Parameters ---------- cat1, cat2: Any the two catalogs to crossmatch must be convertible to recarray match_fields : str, optional data tag on which to additionally cross-match, default None. this also works for any discrete-valued data column. References ---------- https://github.com/jobovy/gaia_tools/<|endoftext|>
268b81c1baeaecd52eeeaf6c6f0c4b21d6fdaa9e746bc65c50b863363023bb77
def non_xmatched(catalog1: T.Sequence, catalog2: T.Sequence, indices1: T.Sequence, indices2: T.Sequence): 'Find non cross-matched catalog components.\n\n Parameters\n ----------\n catalog1, catalog2 : Sequence\n the catalogs\n indices1, indices2 : Sequence\n indices into catalogs for the x-match.\n :func:`~starkman_thesis.utils.data.xmatch.xmatch_indices_coords` output\n or in :func:`~starkman_thesis.utils.data.xmatch.xmatch_coords` info\n\n Returns\n -------\n catalog1_matches, catalog2_matches : catalog input types\n the x-matched catalogs\n info : dict\n Useful information.\n\n - nindices1 : indices into `catalog1` not x-matched.\n - nindices1 : indices into `catalog2` not x-matched.\n\n ' c1idx = np.arange(len(catalog1)) c2idx = np.arange(len(catalog2)) nindices1 = np.where((~ np.in1d(c1idx, indices1)))[0] nindices2 = np.where((~ np.in1d(c2idx, indices2)))[0] ninfo = {'nindices1': nindices1, 'nindices2': nindices2} return ((catalog1[nindices1], catalog2[nindices2]), ninfo)
Find non cross-matched catalog components. Parameters ---------- catalog1, catalog2 : Sequence the catalogs indices1, indices2 : Sequence indices into catalogs for the x-match. :func:`~starkman_thesis.utils.data.xmatch.xmatch_indices_coords` output or in :func:`~starkman_thesis.utils.data.xmatch.xmatch_coords` info Returns ------- catalog1_matches, catalog2_matches : catalog input types the x-matched catalogs info : dict Useful information. - nindices1 : indices into `catalog1` not x-matched. - nindices1 : indices into `catalog2` not x-matched.
utilipy/data_utils/crossmatch.py
non_xmatched
nstarman/utilipy
2
python
def non_xmatched(catalog1: T.Sequence, catalog2: T.Sequence, indices1: T.Sequence, indices2: T.Sequence): 'Find non cross-matched catalog components.\n\n Parameters\n ----------\n catalog1, catalog2 : Sequence\n the catalogs\n indices1, indices2 : Sequence\n indices into catalogs for the x-match.\n :func:`~starkman_thesis.utils.data.xmatch.xmatch_indices_coords` output\n or in :func:`~starkman_thesis.utils.data.xmatch.xmatch_coords` info\n\n Returns\n -------\n catalog1_matches, catalog2_matches : catalog input types\n the x-matched catalogs\n info : dict\n Useful information.\n\n - nindices1 : indices into `catalog1` not x-matched.\n - nindices1 : indices into `catalog2` not x-matched.\n\n ' c1idx = np.arange(len(catalog1)) c2idx = np.arange(len(catalog2)) nindices1 = np.where((~ np.in1d(c1idx, indices1)))[0] nindices2 = np.where((~ np.in1d(c2idx, indices2)))[0] ninfo = {'nindices1': nindices1, 'nindices2': nindices2} return ((catalog1[nindices1], catalog2[nindices2]), ninfo)
def non_xmatched(catalog1: T.Sequence, catalog2: T.Sequence, indices1: T.Sequence, indices2: T.Sequence): 'Find non cross-matched catalog components.\n\n Parameters\n ----------\n catalog1, catalog2 : Sequence\n the catalogs\n indices1, indices2 : Sequence\n indices into catalogs for the x-match.\n :func:`~starkman_thesis.utils.data.xmatch.xmatch_indices_coords` output\n or in :func:`~starkman_thesis.utils.data.xmatch.xmatch_coords` info\n\n Returns\n -------\n catalog1_matches, catalog2_matches : catalog input types\n the x-matched catalogs\n info : dict\n Useful information.\n\n - nindices1 : indices into `catalog1` not x-matched.\n - nindices1 : indices into `catalog2` not x-matched.\n\n ' c1idx = np.arange(len(catalog1)) c2idx = np.arange(len(catalog2)) nindices1 = np.where((~ np.in1d(c1idx, indices1)))[0] nindices2 = np.where((~ np.in1d(c2idx, indices2)))[0] ninfo = {'nindices1': nindices1, 'nindices2': nindices2} return ((catalog1[nindices1], catalog2[nindices2]), ninfo)<|docstring|>Find non cross-matched catalog components. Parameters ---------- catalog1, catalog2 : Sequence the catalogs indices1, indices2 : Sequence indices into catalogs for the x-match. :func:`~starkman_thesis.utils.data.xmatch.xmatch_indices_coords` output or in :func:`~starkman_thesis.utils.data.xmatch.xmatch_coords` info Returns ------- catalog1_matches, catalog2_matches : catalog input types the x-matched catalogs info : dict Useful information. - nindices1 : indices into `catalog1` not x-matched. - nindices1 : indices into `catalog2` not x-matched.<|endoftext|>
9fcd250f0a0e6999566a79ba038df81804cb34e46127b0269114933c3d598216
def air_validate_parser(instance): '\n @brief Semantic validation of an AIR instance\n @param instance The AIR instance map\n @returns Boolean, True if instance is valid.\n\n The instance is assumed to be a syntactically valid instance.\n This routine checks:\n\n The Parser:\n Each edge connects two declared states\n\n In so doing, the validator generates additional structures\n and binds them to the IR. These inc\n ' pass
@brief Semantic validation of an AIR instance @param instance The AIR instance map @returns Boolean, True if instance is valid. The instance is assumed to be a syntactically valid instance. This routine checks: The Parser: Each edge connects two declared states In so doing, the validator generates additional structures and binds them to the IR. These inc
air/air_validate.py
air_validate_parser
dtalayco/air_iri
0
python
def air_validate_parser(instance): '\n @brief Semantic validation of an AIR instance\n @param instance The AIR instance map\n @returns Boolean, True if instance is valid.\n\n The instance is assumed to be a syntactically valid instance.\n This routine checks:\n\n The Parser:\n Each edge connects two declared states\n\n In so doing, the validator generates additional structures\n and binds them to the IR. These inc\n ' pass
def air_validate_parser(instance): '\n @brief Semantic validation of an AIR instance\n @param instance The AIR instance map\n @returns Boolean, True if instance is valid.\n\n The instance is assumed to be a syntactically valid instance.\n This routine checks:\n\n The Parser:\n Each edge connects two declared states\n\n In so doing, the validator generates additional structures\n and binds them to the IR. These inc\n ' pass<|docstring|>@brief Semantic validation of an AIR instance @param instance The AIR instance map @returns Boolean, True if instance is valid. The instance is assumed to be a syntactically valid instance. This routine checks: The Parser: Each edge connects two declared states In so doing, the validator generates additional structures and binds them to the IR. These inc<|endoftext|>
81b73bb863098e7414ac8d8e5255098129737c6c4478f583bb41e3ac62137110
def air_validate_instance(instance): '\n @brief Semantic validation of an AIR instance\n @param instance The AIR instance map\n @returns Boolean, True if instance is valid.\n\n The instance is assumed to be a syntactically valid instance.\n This routine calls the object specific validators:\n parser\n tables\n\n The Parser:\n Each edge connects two declared states\n\n In so doing, the validator generates additional structures\n and binds them to the IR. These inc\n ' pass
@brief Semantic validation of an AIR instance @param instance The AIR instance map @returns Boolean, True if instance is valid. The instance is assumed to be a syntactically valid instance. This routine calls the object specific validators: parser tables The Parser: Each edge connects two declared states In so doing, the validator generates additional structures and binds them to the IR. These inc
air/air_validate.py
air_validate_instance
dtalayco/air_iri
0
python
def air_validate_instance(instance): '\n @brief Semantic validation of an AIR instance\n @param instance The AIR instance map\n @returns Boolean, True if instance is valid.\n\n The instance is assumed to be a syntactically valid instance.\n This routine calls the object specific validators:\n parser\n tables\n\n The Parser:\n Each edge connects two declared states\n\n In so doing, the validator generates additional structures\n and binds them to the IR. These inc\n ' pass
def air_validate_instance(instance): '\n @brief Semantic validation of an AIR instance\n @param instance The AIR instance map\n @returns Boolean, True if instance is valid.\n\n The instance is assumed to be a syntactically valid instance.\n This routine calls the object specific validators:\n parser\n tables\n\n The Parser:\n Each edge connects two declared states\n\n In so doing, the validator generates additional structures\n and binds them to the IR. These inc\n ' pass<|docstring|>@brief Semantic validation of an AIR instance @param instance The AIR instance map @returns Boolean, True if instance is valid. The instance is assumed to be a syntactically valid instance. This routine calls the object specific validators: parser tables The Parser: Each edge connects two declared states In so doing, the validator generates additional structures and binds them to the IR. These inc<|endoftext|>
5ce26aa6a7cd5b1cdf70588845616d188e46b03b48f4590111795f147bb2ba93
def air_check_object(air_instance, obj_type_name, name, type, implementation_type=None): '\n @brief Check basic AIR characteristics for an object reference\n @param air_instance The top level mapping for the IR\n @param obj_type_name The name of the object to report on error\n @param name The name of the top level object\n @param type The expected AIR type for the object\n @param implementation_type If not None, check impl is present and has type\n\n TODO Support a set for implementation type\n ' air_assert((name in air_instance.keys()), ('%s: %s is not in top level for type %s' % (obj_type_name, name, type))) air_assert(('type' in air_instance[name].keys()), ('%s: %s is not an AIR object' % (obj_type_name, name))) air_assert((air_instance[name]['type'] == type), ('%s: %s is not the expected type. Got %s, expected %s' % (obj_type_name, name, air_instance[name]['type'], type))) if (implementation_type is not None): air_assert(('format' in air_instance[name].keys()), ('%s: Expected format indication for %s' % (obj_type_name, name))) air_assert((air_instance[name]['format'] == implementation_type), ('%s: implementation format for %s is %s, expected %s' % (obj_type_name, name, air_instance[name]['format'], implementation_type))) air_assert(('implementation' in air_instance[name].keys()), ('%s: Expected implemenation for %s' % (obj_type_name, name))) air_assert(('implementation' in air_instance[name].keys()), ('%s: Expected implemenation for %s' % (obj_type_name, name)))
@brief Check basic AIR characteristics for an object reference @param air_instance The top level mapping for the IR @param obj_type_name The name of the object to report on error @param name The name of the top level object @param type The expected AIR type for the object @param implementation_type If not None, check impl is present and has type TODO Support a set for implementation type
air/air_validate.py
air_check_object
dtalayco/air_iri
0
python
def air_check_object(air_instance, obj_type_name, name, type, implementation_type=None): '\n @brief Check basic AIR characteristics for an object reference\n @param air_instance The top level mapping for the IR\n @param obj_type_name The name of the object to report on error\n @param name The name of the top level object\n @param type The expected AIR type for the object\n @param implementation_type If not None, check impl is present and has type\n\n TODO Support a set for implementation type\n ' air_assert((name in air_instance.keys()), ('%s: %s is not in top level for type %s' % (obj_type_name, name, type))) air_assert(('type' in air_instance[name].keys()), ('%s: %s is not an AIR object' % (obj_type_name, name))) air_assert((air_instance[name]['type'] == type), ('%s: %s is not the expected type. Got %s, expected %s' % (obj_type_name, name, air_instance[name]['type'], type))) if (implementation_type is not None): air_assert(('format' in air_instance[name].keys()), ('%s: Expected format indication for %s' % (obj_type_name, name))) air_assert((air_instance[name]['format'] == implementation_type), ('%s: implementation format for %s is %s, expected %s' % (obj_type_name, name, air_instance[name]['format'], implementation_type))) air_assert(('implementation' in air_instance[name].keys()), ('%s: Expected implemenation for %s' % (obj_type_name, name))) air_assert(('implementation' in air_instance[name].keys()), ('%s: Expected implemenation for %s' % (obj_type_name, name)))
def air_check_object(air_instance, obj_type_name, name, type, implementation_type=None): '\n @brief Check basic AIR characteristics for an object reference\n @param air_instance The top level mapping for the IR\n @param obj_type_name The name of the object to report on error\n @param name The name of the top level object\n @param type The expected AIR type for the object\n @param implementation_type If not None, check impl is present and has type\n\n TODO Support a set for implementation type\n ' air_assert((name in air_instance.keys()), ('%s: %s is not in top level for type %s' % (obj_type_name, name, type))) air_assert(('type' in air_instance[name].keys()), ('%s: %s is not an AIR object' % (obj_type_name, name))) air_assert((air_instance[name]['type'] == type), ('%s: %s is not the expected type. Got %s, expected %s' % (obj_type_name, name, air_instance[name]['type'], type))) if (implementation_type is not None): air_assert(('format' in air_instance[name].keys()), ('%s: Expected format indication for %s' % (obj_type_name, name))) air_assert((air_instance[name]['format'] == implementation_type), ('%s: implementation format for %s is %s, expected %s' % (obj_type_name, name, air_instance[name]['format'], implementation_type))) air_assert(('implementation' in air_instance[name].keys()), ('%s: Expected implemenation for %s' % (obj_type_name, name))) air_assert(('implementation' in air_instance[name].keys()), ('%s: Expected implemenation for %s' % (obj_type_name, name)))<|docstring|>@brief Check basic AIR characteristics for an object reference @param air_instance The top level mapping for the IR @param obj_type_name The name of the object to report on error @param name The name of the top level object @param type The expected AIR type for the object @param implementation_type If not None, check impl is present and has type TODO Support a set for implementation type<|endoftext|>
3fdd1c667f0e75c377f0191829a2308a235dde508b7d002f57904387f8ccc49b
def air_check_header(air_instance, name): '\n @brief Validate a reference to an AIR header\n @param air_instance The top level AIR instance map\n @param name The name of the header\n @returns Boolean, True if a valid reference\n ' if (name not in air_instance.keys()): return False if ('type' not in air_instance[name].keys()): return False if (air_instance[name]['type'] != 'header'): return False return True
@brief Validate a reference to an AIR header @param air_instance The top level AIR instance map @param name The name of the header @returns Boolean, True if a valid reference
air/air_validate.py
air_check_header
dtalayco/air_iri
0
python
def air_check_header(air_instance, name): '\n @brief Validate a reference to an AIR header\n @param air_instance The top level AIR instance map\n @param name The name of the header\n @returns Boolean, True if a valid reference\n ' if (name not in air_instance.keys()): return False if ('type' not in air_instance[name].keys()): return False if (air_instance[name]['type'] != 'header'): return False return True
def air_check_header(air_instance, name): '\n @brief Validate a reference to an AIR header\n @param air_instance The top level AIR instance map\n @param name The name of the header\n @returns Boolean, True if a valid reference\n ' if (name not in air_instance.keys()): return False if ('type' not in air_instance[name].keys()): return False if (air_instance[name]['type'] != 'header'): return False return True<|docstring|>@brief Validate a reference to an AIR header @param air_instance The top level AIR instance map @param name The name of the header @returns Boolean, True if a valid reference<|endoftext|>
8ef0e0857b854c7503b35a207a3431b89429ceb8e70d3cf87086621837cc1472
def air_validate_data_ref(air_instance, name): '\n @brief Validate a reference to an AIR field\n @param air_instance The top level AIR instance map\n @param name The reference being checked\n @returns Boolean, True if a valid reference\n\n Currently only supports header and header.fld\n ' parts = name.split('.') if (len(parts) == 1): return air_check_header(air_instance, parts[0]) elif (len(parts) == 2): return (air_find_field(air_instance, parts[0], parts[1]) is not None) return False
@brief Validate a reference to an AIR field @param air_instance The top level AIR instance map @param name The reference being checked @returns Boolean, True if a valid reference Currently only supports header and header.fld
air/air_validate.py
air_validate_data_ref
dtalayco/air_iri
0
python
def air_validate_data_ref(air_instance, name): '\n @brief Validate a reference to an AIR field\n @param air_instance The top level AIR instance map\n @param name The reference being checked\n @returns Boolean, True if a valid reference\n\n Currently only supports header and header.fld\n ' parts = name.split('.') if (len(parts) == 1): return air_check_header(air_instance, parts[0]) elif (len(parts) == 2): return (air_find_field(air_instance, parts[0], parts[1]) is not None) return False
def air_validate_data_ref(air_instance, name): '\n @brief Validate a reference to an AIR field\n @param air_instance The top level AIR instance map\n @param name The reference being checked\n @returns Boolean, True if a valid reference\n\n Currently only supports header and header.fld\n ' parts = name.split('.') if (len(parts) == 1): return air_check_header(air_instance, parts[0]) elif (len(parts) == 2): return (air_find_field(air_instance, parts[0], parts[1]) is not None) return False<|docstring|>@brief Validate a reference to an AIR field @param air_instance The top level AIR instance map @param name The reference being checked @returns Boolean, True if a valid reference Currently only supports header and header.fld<|endoftext|>
510078a8d239157b597ff13afae39095b40e382f0647604856d3e2ed5e0937c3
def create_inverse(range_list, diff): 'Creates opposite range for inverse table' range_list = reversed(range_list) value = 1 prev_value = 101 for range_obj in range_list: Range.objects.create(value=value, result=opposites[range_obj.result], difficulty_table=diff) value += (prev_value - range_obj.value) prev_value = range_obj.value
Creates opposite range for inverse table
world/stat_checks/migrations/0004_auto_20210906_1457.py
create_inverse
ApostateCD/arxcode
42
python
def create_inverse(range_list, diff): range_list = reversed(range_list) value = 1 prev_value = 101 for range_obj in range_list: Range.objects.create(value=value, result=opposites[range_obj.result], difficulty_table=diff) value += (prev_value - range_obj.value) prev_value = range_obj.value
def create_inverse(range_list, diff): range_list = reversed(range_list) value = 1 prev_value = 101 for range_obj in range_list: Range.objects.create(value=value, result=opposites[range_obj.result], difficulty_table=diff) value += (prev_value - range_obj.value) prev_value = range_obj.value<|docstring|>Creates opposite range for inverse table<|endoftext|>
f108e3a84ea58ded8834ae29386efae7e96e724e9ad91a074d02b0f688450f80
@pytest.mark.parametrize('code', default_exceptions) def test_error_handler_registration(self, code): 'Check custom error handler is registered for all codes' app = Flask('test') client = app.test_client() @app.route('/') def test(): abort(code) Api(app) with NoLoggingContext(app): response = client.get('/') assert (response.status_code == code) if (code != 412): data = json.loads(response.get_data(as_text=True)) assert (data['status'] == str(default_exceptions[code]()))
Check custom error handler is registered for all codes
tests/test_error_handler.py
test_error_handler_registration
xalioth/flask-rest-api
2
python
@pytest.mark.parametrize('code', default_exceptions) def test_error_handler_registration(self, code): app = Flask('test') client = app.test_client() @app.route('/') def test(): abort(code) Api(app) with NoLoggingContext(app): response = client.get('/') assert (response.status_code == code) if (code != 412): data = json.loads(response.get_data(as_text=True)) assert (data['status'] == str(default_exceptions[code]()))
@pytest.mark.parametrize('code', default_exceptions) def test_error_handler_registration(self, code): app = Flask('test') client = app.test_client() @app.route('/') def test(): abort(code) Api(app) with NoLoggingContext(app): response = client.get('/') assert (response.status_code == code) if (code != 412): data = json.loads(response.get_data(as_text=True)) assert (data['status'] == str(default_exceptions[code]()))<|docstring|>Check custom error handler is registered for all codes<|endoftext|>
8aff9221d29d1d98e3a7eb4d87f6509af65802e3d7e74646f51877fb347ea7fd
def test_error_handler_uncaught_exception(self): 'Test uncaught exceptions result in 500 status code being returned' app = Flask('test') client = app.test_client() @app.route('/') def test(): raise Exception('Oops, something really bad happened.') Api(app) with NoLoggingContext(app): response = client.get('/') assert (response.status_code == 500) data = json.loads(response.get_data(as_text=True)) assert (data['status'] == str(InternalServerError()))
Test uncaught exceptions result in 500 status code being returned
tests/test_error_handler.py
test_error_handler_uncaught_exception
xalioth/flask-rest-api
2
python
def test_error_handler_uncaught_exception(self): app = Flask('test') client = app.test_client() @app.route('/') def test(): raise Exception('Oops, something really bad happened.') Api(app) with NoLoggingContext(app): response = client.get('/') assert (response.status_code == 500) data = json.loads(response.get_data(as_text=True)) assert (data['status'] == str(InternalServerError()))
def test_error_handler_uncaught_exception(self): app = Flask('test') client = app.test_client() @app.route('/') def test(): raise Exception('Oops, something really bad happened.') Api(app) with NoLoggingContext(app): response = client.get('/') assert (response.status_code == 500) data = json.loads(response.get_data(as_text=True)) assert (data['status'] == str(InternalServerError()))<|docstring|>Test uncaught exceptions result in 500 status code being returned<|endoftext|>
3b1e0d49f9039d76f410dc30eff176df3027b374ca7e8c77242bf2faa55cdd34
def setup_method(self, method): ' Reset args/kwargs before each test. ' self.args = [] self.kwargs = {}
Reset args/kwargs before each test.
rhcephpkg/tests/test_build.py
setup_method
red-hat-storage/rhcephpkg
2
python
def setup_method(self, method): ' ' self.args = [] self.kwargs = {}
def setup_method(self, method): ' ' self.args = [] self.kwargs = {}<|docstring|>Reset args/kwargs before each test.<|endoftext|>
bad3ebe535651cb1e2aafaace873e5122733752c1a4b17f2e9d71afbaf57c07a
def fake_build_job(self, *args, **kwargs): ' Store args/kwargs, in order to verify later. ' self.args = args self.kwargs = kwargs return 123
Store args/kwargs, in order to verify later.
rhcephpkg/tests/test_build.py
fake_build_job
red-hat-storage/rhcephpkg
2
python
def fake_build_job(self, *args, **kwargs): ' ' self.args = args self.kwargs = kwargs return 123
def fake_build_job(self, *args, **kwargs): ' ' self.args = args self.kwargs = kwargs return 123<|docstring|>Store args/kwargs, in order to verify later.<|endoftext|>
040553d4815fd147a69616c25ab2441363da8b5b0283c0e8f03bd40597226406
def fake_get_queue_item(self, id_): ' Return fake information about a build ID ' return {'executable': {'number': 456}}
Return fake information about a build ID
rhcephpkg/tests/test_build.py
fake_get_queue_item
red-hat-storage/rhcephpkg
2
python
def fake_get_queue_item(self, id_): ' ' return {'executable': {'number': 456}}
def fake_get_queue_item(self, id_): ' ' return {'executable': {'number': 456}}<|docstring|>Return fake information about a build ID<|endoftext|>
e248202fedd45ce4a721b5a41671cb801560a2d9eea087aeb23eb8502d63518d
def fake_get_build_info(self, build_name, id_): ' Return fake information about a queue ID ' return {'building': False, 'duration': 123456, 'result': 'SUCCESS'}
Return fake information about a queue ID
rhcephpkg/tests/test_build.py
fake_get_build_info
red-hat-storage/rhcephpkg
2
python
def fake_get_build_info(self, build_name, id_): ' ' return {'building': False, 'duration': 123456, 'result': 'SUCCESS'}
def fake_get_build_info(self, build_name, id_): ' ' return {'building': False, 'duration': 123456, 'result': 'SUCCESS'}<|docstring|>Return fake information about a queue ID<|endoftext|>
4ce77f90f8ed9897d27fc2ff32d245bfbe389e3a0aba29a46bf2113536680791
def sam_fetch(sam, chrom, start, end): 'Provide a wrapper for sam-fetch method that could automatically\n handle chrom with or without "chr" prefix.\n @param sam A pysam.AlignmentFile object.\n @param chrom Chromosome name [str]\n @param start 1-based, inclusive [int]\n @param end 1-based, inclusive [int]\n @return Iterator if success, None otherwise. \n ' try: itr = sam.fetch(chrom, (start - 1), end) except: pass else: if itr: return itr chrom = (chrom[3:] if chrom.startswith('chr') else ('chr' + chrom)) try: itr = sam.fetch(chrom, (start - 1), end) except: return None else: return (itr if itr else None)
Provide a wrapper for sam-fetch method that could automatically handle chrom with or without "chr" prefix. @param sam A pysam.AlignmentFile object. @param chrom Chromosome name [str] @param start 1-based, inclusive [int] @param end 1-based, inclusive [int] @return Iterator if success, None otherwise.
xcltk/baf/plp/sam.py
sam_fetch
hxj5/celllib
0
python
def sam_fetch(sam, chrom, start, end): 'Provide a wrapper for sam-fetch method that could automatically\n handle chrom with or without "chr" prefix.\n @param sam A pysam.AlignmentFile object.\n @param chrom Chromosome name [str]\n @param start 1-based, inclusive [int]\n @param end 1-based, inclusive [int]\n @return Iterator if success, None otherwise. \n ' try: itr = sam.fetch(chrom, (start - 1), end) except: pass else: if itr: return itr chrom = (chrom[3:] if chrom.startswith('chr') else ('chr' + chrom)) try: itr = sam.fetch(chrom, (start - 1), end) except: return None else: return (itr if itr else None)
def sam_fetch(sam, chrom, start, end): 'Provide a wrapper for sam-fetch method that could automatically\n handle chrom with or without "chr" prefix.\n @param sam A pysam.AlignmentFile object.\n @param chrom Chromosome name [str]\n @param start 1-based, inclusive [int]\n @param end 1-based, inclusive [int]\n @return Iterator if success, None otherwise. \n ' try: itr = sam.fetch(chrom, (start - 1), end) except: pass else: if itr: return itr chrom = (chrom[3:] if chrom.startswith('chr') else ('chr' + chrom)) try: itr = sam.fetch(chrom, (start - 1), end) except: return None else: return (itr if itr else None)<|docstring|>Provide a wrapper for sam-fetch method that could automatically handle chrom with or without "chr" prefix. @param sam A pysam.AlignmentFile object. @param chrom Chromosome name [str] @param start 1-based, inclusive [int] @param end 1-based, inclusive [int] @return Iterator if success, None otherwise.<|endoftext|>
d08b799d2e5da5340a305932182cc5c87f20e0032bcbf0bb72004d6936f71abe
def chrome(self): 'Chrome with no options\n\n ' opt = SeleniumOptions(self.webdriver) opt.default()
Chrome with no options
automon/integrations/selenium/config.py
chrome
TheShellLand/automonisaur
2
python
def chrome(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default()
def chrome(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default()<|docstring|>Chrome with no options<|endoftext|>
b132907f8fa3795410528cee0e59d7afaa26eaf8a920f7a7c713b2dcc6389dd1
def chrome_maximized(self): 'Chrome with no options\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.maximized()
Chrome with no options
automon/integrations/selenium/config.py
chrome_maximized
TheShellLand/automonisaur
2
python
def chrome_maximized(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.maximized()
def chrome_maximized(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.maximized()<|docstring|>Chrome with no options<|endoftext|>
8923813e42680675ea9a1e3a6920dd4bf260c83fcd26f999b74604e5acdce4a3
def chrome_fullscreen(self): 'Chrome with no options\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.fullscreen()
Chrome with no options
automon/integrations/selenium/config.py
chrome_fullscreen
TheShellLand/automonisaur
2
python
def chrome_fullscreen(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.fullscreen()
def chrome_fullscreen(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.fullscreen()<|docstring|>Chrome with no options<|endoftext|>
7311714ed72d40cc73d1474d5ad66e89e4fc0ac023a4cde1256e8ff7cf6c2bf9
def chrome_for_docker(self): 'Chrome best used with docker\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.nosandbox() opt.headless() opt.noinfobars() opt.noextensions() opt.nonotifications()
Chrome best used with docker
automon/integrations/selenium/config.py
chrome_for_docker
TheShellLand/automonisaur
2
python
def chrome_for_docker(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.nosandbox() opt.headless() opt.noinfobars() opt.noextensions() opt.nonotifications()
def chrome_for_docker(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.nosandbox() opt.headless() opt.noinfobars() opt.noextensions() opt.nonotifications()<|docstring|>Chrome best used with docker<|endoftext|>
1f2cc582d016dfe75ae8bf0c40e675119a4c703e212daa30c2a1d5e78c51abe5
def chrome_sandboxed(self): 'Chrome with sandbox enabled\n\n ' warnings.warn('Docker does not support sandbox option') warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default()
Chrome with sandbox enabled
automon/integrations/selenium/config.py
chrome_sandboxed
TheShellLand/automonisaur
2
python
def chrome_sandboxed(self): '\n\n ' warnings.warn('Docker does not support sandbox option') warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default()
def chrome_sandboxed(self): '\n\n ' warnings.warn('Docker does not support sandbox option') warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default()<|docstring|>Chrome with sandbox enabled<|endoftext|>
26948878f8cab4e15ba50ddba12c12dcc59941f3c0deb8c51402a7bb56356523
def chrome_nosandbox(self): 'Chrome with sandbox disabled\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.nosandbox()
Chrome with sandbox disabled
automon/integrations/selenium/config.py
chrome_nosandbox
TheShellLand/automonisaur
2
python
def chrome_nosandbox(self): '\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.nosandbox()
def chrome_nosandbox(self): '\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.nosandbox()<|docstring|>Chrome with sandbox disabled<|endoftext|>
e7cdb24b058a69f53cbc10d14a2eb8e3f6da0c5ffb32b4e9ee015ccc49249ccf
def chrome_headless_sandboxed(self): 'Headless Chrome with sandbox enabled\n\n ' warnings.warn('Docker does not support sandbox option') warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless()
Headless Chrome with sandbox enabled
automon/integrations/selenium/config.py
chrome_headless_sandboxed
TheShellLand/automonisaur
2
python
def chrome_headless_sandboxed(self): '\n\n ' warnings.warn('Docker does not support sandbox option') warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless()
def chrome_headless_sandboxed(self): '\n\n ' warnings.warn('Docker does not support sandbox option') warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless()<|docstring|>Headless Chrome with sandbox enabled<|endoftext|>
cdc3ef56d3da4b2a7b08a9593a5b41d71b6923a482bf0ef87f41e8d5d79bddc0
def chrome_headless_nosandbox(self): 'Headless Chrome with sandbox disabled\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox()
Headless Chrome with sandbox disabled
automon/integrations/selenium/config.py
chrome_headless_nosandbox
TheShellLand/automonisaur
2
python
def chrome_headless_nosandbox(self): '\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox()
def chrome_headless_nosandbox(self): '\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox()<|docstring|>Headless Chrome with sandbox disabled<|endoftext|>
5916682252281e941dc50fb537a618656c935d2a3df0e32af2b623f465613fbe
def chrome_headless_nosandbox_unsafe(self): 'Headless Chrome with sandbox disabled with not certificate verification\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.unsafe()
Headless Chrome with sandbox disabled with not certificate verification
automon/integrations/selenium/config.py
chrome_headless_nosandbox_unsafe
TheShellLand/automonisaur
2
python
def chrome_headless_nosandbox_unsafe(self): '\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.unsafe()
def chrome_headless_nosandbox_unsafe(self): '\n\n ' warnings.warn('Default shm size is 64m, which will cause chrome driver to crash.', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.unsafe()<|docstring|>Headless Chrome with sandbox disabled with not certificate verification<|endoftext|>
61f652d69eaac4bdab02445d7ab3351c5c1942c83cff864419cfa0b800b4bc52
def chrome_headless_nosandbox_noshm(self): 'Headless Chrome with sandbox disabled\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.noshm()
Headless Chrome with sandbox disabled
automon/integrations/selenium/config.py
chrome_headless_nosandbox_noshm
TheShellLand/automonisaur
2
python
def chrome_headless_nosandbox_noshm(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.noshm()
def chrome_headless_nosandbox_noshm(self): '\n\n ' opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.noshm()<|docstring|>Headless Chrome with sandbox disabled<|endoftext|>
664cab55dcb013356b8508c64af913459e00f043e76ce321de048378d291a273
def chrome_headless_nosandbox_bigshm(self): 'Headless Chrome with sandbox disabled\n\n ' warnings.warn('Larger shm option is not implemented', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.bigshm()
Headless Chrome with sandbox disabled
automon/integrations/selenium/config.py
chrome_headless_nosandbox_bigshm
TheShellLand/automonisaur
2
python
def chrome_headless_nosandbox_bigshm(self): '\n\n ' warnings.warn('Larger shm option is not implemented', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.bigshm()
def chrome_headless_nosandbox_bigshm(self): '\n\n ' warnings.warn('Larger shm option is not implemented', Warning) opt = SeleniumOptions(self.webdriver) opt.default() opt.headless() opt.nosandbox() opt.bigshm()<|docstring|>Headless Chrome with sandbox disabled<|endoftext|>
4c0d4bd6aaf55271fa859c4fd316570d3f7235e94c74c3dd5ef52f440abdadc5
def chrome_remote(self, host: str='127.0.0.1', port: str='4444', executor_path: str='/wd/hub'): 'Remote Selenium\n\n ' log.info(f'Remote WebDriver Hub URL: http://{host}:{port}{executor_path}/static/resource/hub.html') self.webdriver.Remote(command_executor=f'http://{host}:{port}{executor_path}', desired_capabilities=DesiredCapabilities.CHROME)
Remote Selenium
automon/integrations/selenium/config.py
chrome_remote
TheShellLand/automonisaur
2
python
def chrome_remote(self, host: str='127.0.0.1', port: str='4444', executor_path: str='/wd/hub'): '\n\n ' log.info(f'Remote WebDriver Hub URL: http://{host}:{port}{executor_path}/static/resource/hub.html') self.webdriver.Remote(command_executor=f'http://{host}:{port}{executor_path}', desired_capabilities=DesiredCapabilities.CHROME)
def chrome_remote(self, host: str='127.0.0.1', port: str='4444', executor_path: str='/wd/hub'): '\n\n ' log.info(f'Remote WebDriver Hub URL: http://{host}:{port}{executor_path}/static/resource/hub.html') self.webdriver.Remote(command_executor=f'http://{host}:{port}{executor_path}', desired_capabilities=DesiredCapabilities.CHROME)<|docstring|>Remote Selenium<|endoftext|>
8a6a130c6835f0e05acd673bb3a465f0c5b0f0acd5793e1d9c35665ff9c06a4b
def __init__(self, symbol_map: Dict, expr): 'Create a new :class:`ParameterExpression`.\n\n Not intended to be called directly, but to be instantiated via operations\n on other :class:`Parameter` or :class:`ParameterExpression` objects.\n\n Args:\n symbol_map (Dict[Parameter, [ParameterExpression, float, or int]]):\n Mapping of :class:`Parameter` instances to the :class:`sympy.Symbol`\n serving as their placeholder in expr.\n expr (sympy.Expr): Expression of :class:`sympy.Symbol` s.\n ' self._parameter_symbols = symbol_map self._parameters = set(self._parameter_symbols) self._symbol_expr = expr self._names = None
Create a new :class:`ParameterExpression`. Not intended to be called directly, but to be instantiated via operations on other :class:`Parameter` or :class:`ParameterExpression` objects. Args: symbol_map (Dict[Parameter, [ParameterExpression, float, or int]]): Mapping of :class:`Parameter` instances to the :class:`sympy.Symbol` serving as their placeholder in expr. expr (sympy.Expr): Expression of :class:`sympy.Symbol` s.
venv/lib/python3.8/site-packages/qiskit/circuit/parameterexpression.py
__init__
OscarJHernandez/qc_portfolio_optimization
15
python
def __init__(self, symbol_map: Dict, expr): 'Create a new :class:`ParameterExpression`.\n\n Not intended to be called directly, but to be instantiated via operations\n on other :class:`Parameter` or :class:`ParameterExpression` objects.\n\n Args:\n symbol_map (Dict[Parameter, [ParameterExpression, float, or int]]):\n Mapping of :class:`Parameter` instances to the :class:`sympy.Symbol`\n serving as their placeholder in expr.\n expr (sympy.Expr): Expression of :class:`sympy.Symbol` s.\n ' self._parameter_symbols = symbol_map self._parameters = set(self._parameter_symbols) self._symbol_expr = expr self._names = None
def __init__(self, symbol_map: Dict, expr): 'Create a new :class:`ParameterExpression`.\n\n Not intended to be called directly, but to be instantiated via operations\n on other :class:`Parameter` or :class:`ParameterExpression` objects.\n\n Args:\n symbol_map (Dict[Parameter, [ParameterExpression, float, or int]]):\n Mapping of :class:`Parameter` instances to the :class:`sympy.Symbol`\n serving as their placeholder in expr.\n expr (sympy.Expr): Expression of :class:`sympy.Symbol` s.\n ' self._parameter_symbols = symbol_map self._parameters = set(self._parameter_symbols) self._symbol_expr = expr self._names = None<|docstring|>Create a new :class:`ParameterExpression`. Not intended to be called directly, but to be instantiated via operations on other :class:`Parameter` or :class:`ParameterExpression` objects. Args: symbol_map (Dict[Parameter, [ParameterExpression, float, or int]]): Mapping of :class:`Parameter` instances to the :class:`sympy.Symbol` serving as their placeholder in expr. expr (sympy.Expr): Expression of :class:`sympy.Symbol` s.<|endoftext|>
08a1f82e3fbcf49346fd6998960c7295dd4baa80ac0d7c04eafdb4714f9a3cfc
@property def parameters(self) -> Set: 'Returns a set of the unbound Parameters in the expression.' return self._parameters
Returns a set of the unbound Parameters in the expression.
venv/lib/python3.8/site-packages/qiskit/circuit/parameterexpression.py
parameters
OscarJHernandez/qc_portfolio_optimization
15
python
@property def parameters(self) -> Set: return self._parameters
@property def parameters(self) -> Set: return self._parameters<|docstring|>Returns a set of the unbound Parameters in the expression.<|endoftext|>
014e50baa7b82f0e406a6f8ec6678863fd90bb1af67c78f1325cc1ce284cd052
def conjugate(self) -> 'ParameterExpression': 'Return the conjugate, which is the ParameterExpression itself, since it is real.' return self
Return the conjugate, which is the ParameterExpression itself, since it is real.
venv/lib/python3.8/site-packages/qiskit/circuit/parameterexpression.py
conjugate
OscarJHernandez/qc_portfolio_optimization
15
python
def conjugate(self) -> 'ParameterExpression': return self
def conjugate(self) -> 'ParameterExpression': return self<|docstring|>Return the conjugate, which is the ParameterExpression itself, since it is real.<|endoftext|>
61fc77ad6ae45fcdbba748e2098754c417df0de860957ec095682717eada8011
def assign(self, parameter, value: ParameterValueType) -> 'ParameterExpression': '\n Assign one parameter to a value, which can either be numeric or another parameter\n expression.\n\n Args:\n parameter (Parameter): A parameter in this expression whose value will be updated.\n value: The new value to bind to.\n\n Returns:\n A new expression parameterized by any parameters which were not bound by assignment.\n ' if isinstance(value, ParameterExpression): return self.subs({parameter: value}) return self.bind({parameter: value})
Assign one parameter to a value, which can either be numeric or another parameter expression. Args: parameter (Parameter): A parameter in this expression whose value will be updated. value: The new value to bind to. Returns: A new expression parameterized by any parameters which were not bound by assignment.
venv/lib/python3.8/site-packages/qiskit/circuit/parameterexpression.py
assign
OscarJHernandez/qc_portfolio_optimization
15
python
def assign(self, parameter, value: ParameterValueType) -> 'ParameterExpression': '\n Assign one parameter to a value, which can either be numeric or another parameter\n expression.\n\n Args:\n parameter (Parameter): A parameter in this expression whose value will be updated.\n value: The new value to bind to.\n\n Returns:\n A new expression parameterized by any parameters which were not bound by assignment.\n ' if isinstance(value, ParameterExpression): return self.subs({parameter: value}) return self.bind({parameter: value})
def assign(self, parameter, value: ParameterValueType) -> 'ParameterExpression': '\n Assign one parameter to a value, which can either be numeric or another parameter\n expression.\n\n Args:\n parameter (Parameter): A parameter in this expression whose value will be updated.\n value: The new value to bind to.\n\n Returns:\n A new expression parameterized by any parameters which were not bound by assignment.\n ' if isinstance(value, ParameterExpression): return self.subs({parameter: value}) return self.bind({parameter: value})<|docstring|>Assign one parameter to a value, which can either be numeric or another parameter expression. Args: parameter (Parameter): A parameter in this expression whose value will be updated. value: The new value to bind to. Returns: A new expression parameterized by any parameters which were not bound by assignment.<|endoftext|>
5b620c16ab187e45dc8275467d78ce7f9d0c47728a87dfd838e3d917e965ae26
def bind(self, parameter_values: Dict) -> 'ParameterExpression': 'Binds the provided set of parameters to their corresponding values.\n\n Args:\n parameter_values: Mapping of Parameter instances to the numeric value to which\n they will be bound.\n\n Raises:\n CircuitError:\n - If parameter_values contains Parameters outside those in self.\n - If a non-numeric value is passed in parameter_values.\n ZeroDivisionError:\n - If binding the provided values requires division by zero.\n\n Returns:\n A new expression parameterized by any parameters which were not bound by\n parameter_values.\n ' self._raise_if_passed_unknown_parameters(parameter_values.keys()) self._raise_if_passed_non_real_value(parameter_values) symbol_values = {self._parameter_symbols[parameter]: value for (parameter, value) in parameter_values.items()} bound_symbol_expr = self._symbol_expr.subs(symbol_values) free_parameters = (self.parameters - parameter_values.keys()) free_parameter_symbols = {p: s for (p, s) in self._parameter_symbols.items() if (p in free_parameters)} if bound_symbol_expr.is_infinite: raise ZeroDivisionError('Binding provided for expression results in division by zero (Expression: {}, Bindings: {}).'.format(self, parameter_values)) return ParameterExpression(free_parameter_symbols, bound_symbol_expr)
Binds the provided set of parameters to their corresponding values. Args: parameter_values: Mapping of Parameter instances to the numeric value to which they will be bound. Raises: CircuitError: - If parameter_values contains Parameters outside those in self. - If a non-numeric value is passed in parameter_values. ZeroDivisionError: - If binding the provided values requires division by zero. Returns: A new expression parameterized by any parameters which were not bound by parameter_values.
venv/lib/python3.8/site-packages/qiskit/circuit/parameterexpression.py
bind
OscarJHernandez/qc_portfolio_optimization
15
python
def bind(self, parameter_values: Dict) -> 'ParameterExpression': 'Binds the provided set of parameters to their corresponding values.\n\n Args:\n parameter_values: Mapping of Parameter instances to the numeric value to which\n they will be bound.\n\n Raises:\n CircuitError:\n - If parameter_values contains Parameters outside those in self.\n - If a non-numeric value is passed in parameter_values.\n ZeroDivisionError:\n - If binding the provided values requires division by zero.\n\n Returns:\n A new expression parameterized by any parameters which were not bound by\n parameter_values.\n ' self._raise_if_passed_unknown_parameters(parameter_values.keys()) self._raise_if_passed_non_real_value(parameter_values) symbol_values = {self._parameter_symbols[parameter]: value for (parameter, value) in parameter_values.items()} bound_symbol_expr = self._symbol_expr.subs(symbol_values) free_parameters = (self.parameters - parameter_values.keys()) free_parameter_symbols = {p: s for (p, s) in self._parameter_symbols.items() if (p in free_parameters)} if bound_symbol_expr.is_infinite: raise ZeroDivisionError('Binding provided for expression results in division by zero (Expression: {}, Bindings: {}).'.format(self, parameter_values)) return ParameterExpression(free_parameter_symbols, bound_symbol_expr)
def bind(self, parameter_values: Dict) -> 'ParameterExpression': 'Binds the provided set of parameters to their corresponding values.\n\n Args:\n parameter_values: Mapping of Parameter instances to the numeric value to which\n they will be bound.\n\n Raises:\n CircuitError:\n - If parameter_values contains Parameters outside those in self.\n - If a non-numeric value is passed in parameter_values.\n ZeroDivisionError:\n - If binding the provided values requires division by zero.\n\n Returns:\n A new expression parameterized by any parameters which were not bound by\n parameter_values.\n ' self._raise_if_passed_unknown_parameters(parameter_values.keys()) self._raise_if_passed_non_real_value(parameter_values) symbol_values = {self._parameter_symbols[parameter]: value for (parameter, value) in parameter_values.items()} bound_symbol_expr = self._symbol_expr.subs(symbol_values) free_parameters = (self.parameters - parameter_values.keys()) free_parameter_symbols = {p: s for (p, s) in self._parameter_symbols.items() if (p in free_parameters)} if bound_symbol_expr.is_infinite: raise ZeroDivisionError('Binding provided for expression results in division by zero (Expression: {}, Bindings: {}).'.format(self, parameter_values)) return ParameterExpression(free_parameter_symbols, bound_symbol_expr)<|docstring|>Binds the provided set of parameters to their corresponding values. Args: parameter_values: Mapping of Parameter instances to the numeric value to which they will be bound. Raises: CircuitError: - If parameter_values contains Parameters outside those in self. - If a non-numeric value is passed in parameter_values. ZeroDivisionError: - If binding the provided values requires division by zero. Returns: A new expression parameterized by any parameters which were not bound by parameter_values.<|endoftext|>
d03d7d73fddc84504cbf53acfbbba4671babdbb62abe2caf0bf2c8962ab2716a
def subs(self, parameter_map: Dict) -> 'ParameterExpression': 'Returns a new Expression with replacement Parameters.\n\n Args:\n parameter_map: Mapping from Parameters in self to the ParameterExpression\n instances with which they should be replaced.\n\n Raises:\n CircuitError:\n - If parameter_map contains Parameters outside those in self.\n - If the replacement Parameters in parameter_map would result in\n a name conflict in the generated expression.\n\n Returns:\n A new expression with the specified parameters replaced.\n ' inbound_parameters = {p for replacement_expr in parameter_map.values() for p in replacement_expr.parameters} self._raise_if_passed_unknown_parameters(parameter_map.keys()) self._raise_if_parameter_names_conflict(inbound_parameters, parameter_map.keys()) from sympy import Symbol new_parameter_symbols = {p: Symbol(p.name) for p in inbound_parameters} new_parameter_symbols.update({p: s for (p, s) in self._parameter_symbols.items() if (p not in parameter_map)}) symbol_map = {self._parameter_symbols[old_param]: new_param._symbol_expr for (old_param, new_param) in parameter_map.items()} substituted_symbol_expr = self._symbol_expr.subs(symbol_map) return ParameterExpression(new_parameter_symbols, substituted_symbol_expr)
Returns a new Expression with replacement Parameters. Args: parameter_map: Mapping from Parameters in self to the ParameterExpression instances with which they should be replaced. Raises: CircuitError: - If parameter_map contains Parameters outside those in self. - If the replacement Parameters in parameter_map would result in a name conflict in the generated expression. Returns: A new expression with the specified parameters replaced.
venv/lib/python3.8/site-packages/qiskit/circuit/parameterexpression.py
subs
OscarJHernandez/qc_portfolio_optimization
15
python
def subs(self, parameter_map: Dict) -> 'ParameterExpression': 'Returns a new Expression with replacement Parameters.\n\n Args:\n parameter_map: Mapping from Parameters in self to the ParameterExpression\n instances with which they should be replaced.\n\n Raises:\n CircuitError:\n - If parameter_map contains Parameters outside those in self.\n - If the replacement Parameters in parameter_map would result in\n a name conflict in the generated expression.\n\n Returns:\n A new expression with the specified parameters replaced.\n ' inbound_parameters = {p for replacement_expr in parameter_map.values() for p in replacement_expr.parameters} self._raise_if_passed_unknown_parameters(parameter_map.keys()) self._raise_if_parameter_names_conflict(inbound_parameters, parameter_map.keys()) from sympy import Symbol new_parameter_symbols = {p: Symbol(p.name) for p in inbound_parameters} new_parameter_symbols.update({p: s for (p, s) in self._parameter_symbols.items() if (p not in parameter_map)}) symbol_map = {self._parameter_symbols[old_param]: new_param._symbol_expr for (old_param, new_param) in parameter_map.items()} substituted_symbol_expr = self._symbol_expr.subs(symbol_map) return ParameterExpression(new_parameter_symbols, substituted_symbol_expr)
def subs(self, parameter_map: Dict) -> 'ParameterExpression': 'Returns a new Expression with replacement Parameters.\n\n Args:\n parameter_map: Mapping from Parameters in self to the ParameterExpression\n instances with which they should be replaced.\n\n Raises:\n CircuitError:\n - If parameter_map contains Parameters outside those in self.\n - If the replacement Parameters in parameter_map would result in\n a name conflict in the generated expression.\n\n Returns:\n A new expression with the specified parameters replaced.\n ' inbound_parameters = {p for replacement_expr in parameter_map.values() for p in replacement_expr.parameters} self._raise_if_passed_unknown_parameters(parameter_map.keys()) self._raise_if_parameter_names_conflict(inbound_parameters, parameter_map.keys()) from sympy import Symbol new_parameter_symbols = {p: Symbol(p.name) for p in inbound_parameters} new_parameter_symbols.update({p: s for (p, s) in self._parameter_symbols.items() if (p not in parameter_map)}) symbol_map = {self._parameter_symbols[old_param]: new_param._symbol_expr for (old_param, new_param) in parameter_map.items()} substituted_symbol_expr = self._symbol_expr.subs(symbol_map) return ParameterExpression(new_parameter_symbols, substituted_symbol_expr)<|docstring|>Returns a new Expression with replacement Parameters. Args: parameter_map: Mapping from Parameters in self to the ParameterExpression instances with which they should be replaced. Raises: CircuitError: - If parameter_map contains Parameters outside those in self. - If the replacement Parameters in parameter_map would result in a name conflict in the generated expression. Returns: A new expression with the specified parameters replaced.<|endoftext|>
9790711a57090a8dc8d997d5e420356359433e0ce8eab6b495df70005964e464
def _apply_operation(self, operation: Callable, other: ParameterValueType, reflected: bool=False) -> 'ParameterExpression': 'Base method implementing math operations between Parameters and\n either a constant or a second ParameterExpression.\n\n Args:\n operation: One of operator.{add,sub,mul,truediv}.\n other: The second argument to be used with self in operation.\n reflected: Optional - The default ordering is "self operator other".\n If reflected is True, this is switched to "other operator self".\n For use in e.g. __radd__, ...\n\n Raises:\n CircuitError:\n - If parameter_map contains Parameters outside those in self.\n - If the replacement Parameters in parameter_map would result in\n a name conflict in the generated expression.\n\n Returns:\n A new expression describing the result of the operation.\n ' self_expr = self._symbol_expr if isinstance(other, ParameterExpression): self._raise_if_parameter_names_conflict(other._parameter_symbols.keys()) parameter_symbols = {**self._parameter_symbols, **other._parameter_symbols} other_expr = other._symbol_expr elif (isinstance(other, numbers.Real) and numpy.isfinite(other)): parameter_symbols = self._parameter_symbols.copy() other_expr = other else: return NotImplemented if reflected: expr = operation(other_expr, self_expr) else: expr = operation(self_expr, other_expr) return ParameterExpression(parameter_symbols, expr)
Base method implementing math operations between Parameters and either a constant or a second ParameterExpression. Args: operation: One of operator.{add,sub,mul,truediv}. other: The second argument to be used with self in operation. reflected: Optional - The default ordering is "self operator other". If reflected is True, this is switched to "other operator self". For use in e.g. __radd__, ... Raises: CircuitError: - If parameter_map contains Parameters outside those in self. - If the replacement Parameters in parameter_map would result in a name conflict in the generated expression. Returns: A new expression describing the result of the operation.
venv/lib/python3.8/site-packages/qiskit/circuit/parameterexpression.py
_apply_operation
OscarJHernandez/qc_portfolio_optimization
15
python
def _apply_operation(self, operation: Callable, other: ParameterValueType, reflected: bool=False) -> 'ParameterExpression': 'Base method implementing math operations between Parameters and\n either a constant or a second ParameterExpression.\n\n Args:\n operation: One of operator.{add,sub,mul,truediv}.\n other: The second argument to be used with self in operation.\n reflected: Optional - The default ordering is "self operator other".\n If reflected is True, this is switched to "other operator self".\n For use in e.g. __radd__, ...\n\n Raises:\n CircuitError:\n - If parameter_map contains Parameters outside those in self.\n - If the replacement Parameters in parameter_map would result in\n a name conflict in the generated expression.\n\n Returns:\n A new expression describing the result of the operation.\n ' self_expr = self._symbol_expr if isinstance(other, ParameterExpression): self._raise_if_parameter_names_conflict(other._parameter_symbols.keys()) parameter_symbols = {**self._parameter_symbols, **other._parameter_symbols} other_expr = other._symbol_expr elif (isinstance(other, numbers.Real) and numpy.isfinite(other)): parameter_symbols = self._parameter_symbols.copy() other_expr = other else: return NotImplemented if reflected: expr = operation(other_expr, self_expr) else: expr = operation(self_expr, other_expr) return ParameterExpression(parameter_symbols, expr)
def _apply_operation(self, operation: Callable, other: ParameterValueType, reflected: bool=False) -> 'ParameterExpression': 'Base method implementing math operations between Parameters and\n either a constant or a second ParameterExpression.\n\n Args:\n operation: One of operator.{add,sub,mul,truediv}.\n other: The second argument to be used with self in operation.\n reflected: Optional - The default ordering is "self operator other".\n If reflected is True, this is switched to "other operator self".\n For use in e.g. __radd__, ...\n\n Raises:\n CircuitError:\n - If parameter_map contains Parameters outside those in self.\n - If the replacement Parameters in parameter_map would result in\n a name conflict in the generated expression.\n\n Returns:\n A new expression describing the result of the operation.\n ' self_expr = self._symbol_expr if isinstance(other, ParameterExpression): self._raise_if_parameter_names_conflict(other._parameter_symbols.keys()) parameter_symbols = {**self._parameter_symbols, **other._parameter_symbols} other_expr = other._symbol_expr elif (isinstance(other, numbers.Real) and numpy.isfinite(other)): parameter_symbols = self._parameter_symbols.copy() other_expr = other else: return NotImplemented if reflected: expr = operation(other_expr, self_expr) else: expr = operation(self_expr, other_expr) return ParameterExpression(parameter_symbols, expr)<|docstring|>Base method implementing math operations between Parameters and either a constant or a second ParameterExpression. Args: operation: One of operator.{add,sub,mul,truediv}. other: The second argument to be used with self in operation. reflected: Optional - The default ordering is "self operator other". If reflected is True, this is switched to "other operator self". For use in e.g. __radd__, ... Raises: CircuitError: - If parameter_map contains Parameters outside those in self. - If the replacement Parameters in parameter_map would result in a name conflict in the generated expression. Returns: A new expression describing the result of the operation.<|endoftext|>
e73cf89fbdfd10dabafc96323e8b6e1e721be8b619e241fdaf0b85cc0b06c692
def cb_status(self, msg): '\n :type msg: Status\n ' now = self._node.get_clock().now() feedback = Feedback() feedback.set_rumble = True feedback.rumble_small = abs(msg.axis_left_y) feedback.rumble_big = abs(msg.axis_right_y) touch = msg.touch0 if (touch.active and msg.button_circle): feedback.set_led = True self._led['r'] = touch.x if (touch.active and msg.button_triangle): feedback.set_led = True self._led['g'] = touch.x if (touch.active and msg.button_cross): feedback.set_led = True self._led['b'] = touch.x feedback.led_r = float(self._led['r']) feedback.led_g = float(self._led['g']) feedback.led_b = float(self._led['b']) if ((not self._prev.button_ps) and msg.button_ps): feedback.set_led_flash = True if self._led['flashing']: feedback.led_flash_off = 0.0 else: feedback.led_flash_on = 0.2 feedback.led_flash_off = 0.2 self._led['flashing'] = (not self._led['flashing']) self._pub_feedback.publish(feedback) self._prev = msg self._last_pub_time = now
:type msg: Status
nodes/demo.py
cb_status
Aposhian/ds4_driver
0
python
def cb_status(self, msg): '\n \n ' now = self._node.get_clock().now() feedback = Feedback() feedback.set_rumble = True feedback.rumble_small = abs(msg.axis_left_y) feedback.rumble_big = abs(msg.axis_right_y) touch = msg.touch0 if (touch.active and msg.button_circle): feedback.set_led = True self._led['r'] = touch.x if (touch.active and msg.button_triangle): feedback.set_led = True self._led['g'] = touch.x if (touch.active and msg.button_cross): feedback.set_led = True self._led['b'] = touch.x feedback.led_r = float(self._led['r']) feedback.led_g = float(self._led['g']) feedback.led_b = float(self._led['b']) if ((not self._prev.button_ps) and msg.button_ps): feedback.set_led_flash = True if self._led['flashing']: feedback.led_flash_off = 0.0 else: feedback.led_flash_on = 0.2 feedback.led_flash_off = 0.2 self._led['flashing'] = (not self._led['flashing']) self._pub_feedback.publish(feedback) self._prev = msg self._last_pub_time = now
def cb_status(self, msg): '\n \n ' now = self._node.get_clock().now() feedback = Feedback() feedback.set_rumble = True feedback.rumble_small = abs(msg.axis_left_y) feedback.rumble_big = abs(msg.axis_right_y) touch = msg.touch0 if (touch.active and msg.button_circle): feedback.set_led = True self._led['r'] = touch.x if (touch.active and msg.button_triangle): feedback.set_led = True self._led['g'] = touch.x if (touch.active and msg.button_cross): feedback.set_led = True self._led['b'] = touch.x feedback.led_r = float(self._led['r']) feedback.led_g = float(self._led['g']) feedback.led_b = float(self._led['b']) if ((not self._prev.button_ps) and msg.button_ps): feedback.set_led_flash = True if self._led['flashing']: feedback.led_flash_off = 0.0 else: feedback.led_flash_on = 0.2 feedback.led_flash_off = 0.2 self._led['flashing'] = (not self._led['flashing']) self._pub_feedback.publish(feedback) self._prev = msg self._last_pub_time = now<|docstring|>:type msg: Status<|endoftext|>
231652daf4700ba5881e77e18b73bcb296ab7d1ad3a3cef4b596e81ebe0a24be
def find_best_k_value(rows, category): ' 获取最优k值\n\n :param rows:\n :param category:\n :return:\n ' k = 4 if (len(rows) <= 15): k = 1 elif (15 < len(rows) < 30): k = 2 return k
获取最优k值 :param rows: :param category: :return:
utils.py
find_best_k_value
guoweikuang/weibo_project
4
python
def find_best_k_value(rows, category): ' 获取最优k值\n\n :param rows:\n :param category:\n :return:\n ' k = 4 if (len(rows) <= 15): k = 1 elif (15 < len(rows) < 30): k = 2 return k
def find_best_k_value(rows, category): ' 获取最优k值\n\n :param rows:\n :param category:\n :return:\n ' k = 4 if (len(rows) <= 15): k = 1 elif (15 < len(rows) < 30): k = 2 return k<|docstring|>获取最优k值 :param rows: :param category: :return:<|endoftext|>
af43d392e018a64093a8b75572c19be2c6005ddc711108412c5c6588c2b2f640
def run_first_cluster(start_time, end_time, k=1): ' 一次聚类并存入数据库.\n\n :param start_time:\n :param end_time:\n :param k:\n :return:\n ' categories = os.listdir(os.path.join(abs_path, 'classify_text/data')) for category in categories: rows = get_text_from_file(category[:(- 4)], cate='category') rows = [row.decode('utf-8').strip().split('\t') for row in rows] tf_idf = TFIDF(rows) tf_idf_dict = tf_idf.tf_idf() texts = tf_idf.get_filter_text() vsm = BuildVSM(tf_idf_dict, tf_idf.seg_list, texts, vsm_name=category[:(- 4)]) vsm.build_vsm() rows = vsm.filter_text() data_set = numpy.mat(load_data_set(vsm_name=category[:(- 4)])) k = find_optimal_k_value(data_set) print(category, k) k = find_best_k_value(rows, category) print('k:', k) if (k == 1): labels = ([0] * len(data_set)) else: labels = run_kmeans_by_scikit(k=k, vsm_name=category[:(- 4)]) save_k_cluster_to_redis(labels=labels, texts=rows, category=category[:(- 4)]) classify_k_cluster_from_category(labels=labels, texts=rows, vsm_name=category[:(- 4)], category=category[:(- 4)])
一次聚类并存入数据库. :param start_time: :param end_time: :param k: :return:
utils.py
run_first_cluster
guoweikuang/weibo_project
4
python
def run_first_cluster(start_time, end_time, k=1): ' 一次聚类并存入数据库.\n\n :param start_time:\n :param end_time:\n :param k:\n :return:\n ' categories = os.listdir(os.path.join(abs_path, 'classify_text/data')) for category in categories: rows = get_text_from_file(category[:(- 4)], cate='category') rows = [row.decode('utf-8').strip().split('\t') for row in rows] tf_idf = TFIDF(rows) tf_idf_dict = tf_idf.tf_idf() texts = tf_idf.get_filter_text() vsm = BuildVSM(tf_idf_dict, tf_idf.seg_list, texts, vsm_name=category[:(- 4)]) vsm.build_vsm() rows = vsm.filter_text() data_set = numpy.mat(load_data_set(vsm_name=category[:(- 4)])) k = find_optimal_k_value(data_set) print(category, k) k = find_best_k_value(rows, category) print('k:', k) if (k == 1): labels = ([0] * len(data_set)) else: labels = run_kmeans_by_scikit(k=k, vsm_name=category[:(- 4)]) save_k_cluster_to_redis(labels=labels, texts=rows, category=category[:(- 4)]) classify_k_cluster_from_category(labels=labels, texts=rows, vsm_name=category[:(- 4)], category=category[:(- 4)])
def run_first_cluster(start_time, end_time, k=1): ' 一次聚类并存入数据库.\n\n :param start_time:\n :param end_time:\n :param k:\n :return:\n ' categories = os.listdir(os.path.join(abs_path, 'classify_text/data')) for category in categories: rows = get_text_from_file(category[:(- 4)], cate='category') rows = [row.decode('utf-8').strip().split('\t') for row in rows] tf_idf = TFIDF(rows) tf_idf_dict = tf_idf.tf_idf() texts = tf_idf.get_filter_text() vsm = BuildVSM(tf_idf_dict, tf_idf.seg_list, texts, vsm_name=category[:(- 4)]) vsm.build_vsm() rows = vsm.filter_text() data_set = numpy.mat(load_data_set(vsm_name=category[:(- 4)])) k = find_optimal_k_value(data_set) print(category, k) k = find_best_k_value(rows, category) print('k:', k) if (k == 1): labels = ([0] * len(data_set)) else: labels = run_kmeans_by_scikit(k=k, vsm_name=category[:(- 4)]) save_k_cluster_to_redis(labels=labels, texts=rows, category=category[:(- 4)]) classify_k_cluster_from_category(labels=labels, texts=rows, vsm_name=category[:(- 4)], category=category[:(- 4)])<|docstring|>一次聚类并存入数据库. :param start_time: :param end_time: :param k: :return:<|endoftext|>
8ed0b0adb745ebe3a92f35f860b9dc25f2a19730b631ac058f88c460af42c3e2
def get_max_text_from_redis(category): ' 获取一次聚类后的最大数量的类.\n\n :param category:\n :return:\n ' max_num = 0 read_client = redis_client() max_key = (K_CLUSTER % (category, 1)) for i in range(1, 15): key_name = (K_CLUSTER % (category, i)) if (read_client.llen(key_name) > max_num): max_num = read_client.llen(key_name) max_key = key_name rows = read_client.lrange(max_key, 0, (- 1)) return rows[::(- 1)]
获取一次聚类后的最大数量的类. :param category: :return:
utils.py
get_max_text_from_redis
guoweikuang/weibo_project
4
python
def get_max_text_from_redis(category): ' 获取一次聚类后的最大数量的类.\n\n :param category:\n :return:\n ' max_num = 0 read_client = redis_client() max_key = (K_CLUSTER % (category, 1)) for i in range(1, 15): key_name = (K_CLUSTER % (category, i)) if (read_client.llen(key_name) > max_num): max_num = read_client.llen(key_name) max_key = key_name rows = read_client.lrange(max_key, 0, (- 1)) return rows[::(- 1)]
def get_max_text_from_redis(category): ' 获取一次聚类后的最大数量的类.\n\n :param category:\n :return:\n ' max_num = 0 read_client = redis_client() max_key = (K_CLUSTER % (category, 1)) for i in range(1, 15): key_name = (K_CLUSTER % (category, i)) if (read_client.llen(key_name) > max_num): max_num = read_client.llen(key_name) max_key = key_name rows = read_client.lrange(max_key, 0, (- 1)) return rows[::(- 1)]<|docstring|>获取一次聚类后的最大数量的类. :param category: :return:<|endoftext|>
1e99de84fc36c27f7d6e87f299f6344f1a7617d98b06babba42b5c08a88306eb
def run_second_cluster(): ' 二次聚类\n\n :param key_name:\n :return:\n ' categories = get_categorys() for category in categories: results = get_max_text_from_redis(category[:(- 4)]) if (not results): continue results = [row.decode('utf-8').split('\t') for row in results] if (len(results) <= 30): k = 2 else: k = 4 vsm_name = (category[:(- 4)] + ':second') texts = run_build_vsm_by_texts(results, vsm_name=vsm_name) labels = run_kmeans_by_scikit(k=k, vsm_name=vsm_name) classify_k_cluster_to_redis(labels=labels, texts=texts, category=category[:(- 4)], db=1)
二次聚类 :param key_name: :return:
utils.py
run_second_cluster
guoweikuang/weibo_project
4
python
def run_second_cluster(): ' 二次聚类\n\n :param key_name:\n :return:\n ' categories = get_categorys() for category in categories: results = get_max_text_from_redis(category[:(- 4)]) if (not results): continue results = [row.decode('utf-8').split('\t') for row in results] if (len(results) <= 30): k = 2 else: k = 4 vsm_name = (category[:(- 4)] + ':second') texts = run_build_vsm_by_texts(results, vsm_name=vsm_name) labels = run_kmeans_by_scikit(k=k, vsm_name=vsm_name) classify_k_cluster_to_redis(labels=labels, texts=texts, category=category[:(- 4)], db=1)
def run_second_cluster(): ' 二次聚类\n\n :param key_name:\n :return:\n ' categories = get_categorys() for category in categories: results = get_max_text_from_redis(category[:(- 4)]) if (not results): continue results = [row.decode('utf-8').split('\t') for row in results] if (len(results) <= 30): k = 2 else: k = 4 vsm_name = (category[:(- 4)] + ':second') texts = run_build_vsm_by_texts(results, vsm_name=vsm_name) labels = run_kmeans_by_scikit(k=k, vsm_name=vsm_name) classify_k_cluster_to_redis(labels=labels, texts=texts, category=category[:(- 4)], db=1)<|docstring|>二次聚类 :param key_name: :return:<|endoftext|>
65dcd3f0cb365827025dee6fdf3df15171d6afbc2acf51744875f72c1023b103
def run_hot_topic(db=1, hot_db=2, hot_type='first'): ' 获取各分类热点话题热度值.\n\n :return:\n ' categorys = get_categorys() for category in categorys: topic = HotTopic(db=db, hot_db=hot_db) category = category[:(- 4)] if (hot_type == 'first'): topic.get_first_cluster_hot(category) else: topic.get_second_cluster_hot(category)
获取各分类热点话题热度值. :return:
utils.py
run_hot_topic
guoweikuang/weibo_project
4
python
def run_hot_topic(db=1, hot_db=2, hot_type='first'): ' 获取各分类热点话题热度值.\n\n :return:\n ' categorys = get_categorys() for category in categorys: topic = HotTopic(db=db, hot_db=hot_db) category = category[:(- 4)] if (hot_type == 'first'): topic.get_first_cluster_hot(category) else: topic.get_second_cluster_hot(category)
def run_hot_topic(db=1, hot_db=2, hot_type='first'): ' 获取各分类热点话题热度值.\n\n :return:\n ' categorys = get_categorys() for category in categorys: topic = HotTopic(db=db, hot_db=hot_db) category = category[:(- 4)] if (hot_type == 'first'): topic.get_first_cluster_hot(category) else: topic.get_second_cluster_hot(category)<|docstring|>获取各分类热点话题热度值. :return:<|endoftext|>
f4c9c66e1a030021a7041067d829f24cd86f47d97b6b7bde9c189bf1a015f811
def run_first_cluster_hot_topic(): ' 整个聚类过程包括热度计算等.\n\n :return:\n ' run_hot_topic(db=0, hot_db=1)
整个聚类过程包括热度计算等. :return:
utils.py
run_first_cluster_hot_topic
guoweikuang/weibo_project
4
python
def run_first_cluster_hot_topic(): ' 整个聚类过程包括热度计算等.\n\n :return:\n ' run_hot_topic(db=0, hot_db=1)
def run_first_cluster_hot_topic(): ' 整个聚类过程包括热度计算等.\n\n :return:\n ' run_hot_topic(db=0, hot_db=1)<|docstring|>整个聚类过程包括热度计算等. :return:<|endoftext|>
15923ef0c1c89770450f446b55373ced6095707e9643a4c4626341062c28dbe1
def run_second_cluster_hot_topic(db=1, hot_db=2): '\n\n :param db:\n :param hot_db:\n :return:\n ' run_hot_topic(db=db, hot_db=hot_db, hot_type='second')
:param db: :param hot_db: :return:
utils.py
run_second_cluster_hot_topic
guoweikuang/weibo_project
4
python
def run_second_cluster_hot_topic(db=1, hot_db=2): '\n\n :param db:\n :param hot_db:\n :return:\n ' run_hot_topic(db=db, hot_db=hot_db, hot_type='second')
def run_second_cluster_hot_topic(db=1, hot_db=2): '\n\n :param db:\n :param hot_db:\n :return:\n ' run_hot_topic(db=db, hot_db=hot_db, hot_type='second')<|docstring|>:param db: :param hot_db: :return:<|endoftext|>
b029705234d79c410c3c40a55bc3689ca4461c1a9c658fe4628cefbb4f5f5b2f
def run_cluster(start, end, k=7): ' 旧数据库数据全套热点话题流程, test.\n\n :param start:\n :param end:\n :param k:\n :return:\n ' end_time = arrow.get('2016-10-30') rows = read_text_old_mysql(end_time, days=20, database='weibo') rows = run_build_vsm_by_texts(texts=rows, vsm_name='total') data_set = numpy.mat(load_data_set(vsm_name='total')) k = find_optimal_k_value(data_set) print(k) labels = run_kmeans_by_scikit(k=k, vsm_name='total') classify_k_cluster_to_file(labels=labels, texts=rows) classify_k_cluster_to_redis(labels=labels, texts=rows) topic = HotTopic(db=0, hot_db=1) topic.get_cluster_hot(k) run_draw_cluster_chart(db=1) run_keywrod_barh(db=1)
旧数据库数据全套热点话题流程, test. :param start: :param end: :param k: :return:
utils.py
run_cluster
guoweikuang/weibo_project
4
python
def run_cluster(start, end, k=7): ' 旧数据库数据全套热点话题流程, test.\n\n :param start:\n :param end:\n :param k:\n :return:\n ' end_time = arrow.get('2016-10-30') rows = read_text_old_mysql(end_time, days=20, database='weibo') rows = run_build_vsm_by_texts(texts=rows, vsm_name='total') data_set = numpy.mat(load_data_set(vsm_name='total')) k = find_optimal_k_value(data_set) print(k) labels = run_kmeans_by_scikit(k=k, vsm_name='total') classify_k_cluster_to_file(labels=labels, texts=rows) classify_k_cluster_to_redis(labels=labels, texts=rows) topic = HotTopic(db=0, hot_db=1) topic.get_cluster_hot(k) run_draw_cluster_chart(db=1) run_keywrod_barh(db=1)
def run_cluster(start, end, k=7): ' 旧数据库数据全套热点话题流程, test.\n\n :param start:\n :param end:\n :param k:\n :return:\n ' end_time = arrow.get('2016-10-30') rows = read_text_old_mysql(end_time, days=20, database='weibo') rows = run_build_vsm_by_texts(texts=rows, vsm_name='total') data_set = numpy.mat(load_data_set(vsm_name='total')) k = find_optimal_k_value(data_set) print(k) labels = run_kmeans_by_scikit(k=k, vsm_name='total') classify_k_cluster_to_file(labels=labels, texts=rows) classify_k_cluster_to_redis(labels=labels, texts=rows) topic = HotTopic(db=0, hot_db=1) topic.get_cluster_hot(k) run_draw_cluster_chart(db=1) run_keywrod_barh(db=1)<|docstring|>旧数据库数据全套热点话题流程, test. :param start: :param end: :param k: :return:<|endoftext|>
1a45e21fdf59ebd4bd2d19fa638a1473f136455b660b79a2726a4ad806d21fe0
def run_all_process(start_time, end_time): '\n\n :param start_time:\n :param end_time:\n :return:\n ' start = arrow.get(start_time, 'YYYY-MM-DD').date() end = arrow.get(end_time, 'YYYY-MM-DD').date() rows = get_text_from_mysql('content', start_time=start, end_time=end) run_classify_text(rows) run_first_cluster('1', '1')
:param start_time: :param end_time: :return:
utils.py
run_all_process
guoweikuang/weibo_project
4
python
def run_all_process(start_time, end_time): '\n\n :param start_time:\n :param end_time:\n :return:\n ' start = arrow.get(start_time, 'YYYY-MM-DD').date() end = arrow.get(end_time, 'YYYY-MM-DD').date() rows = get_text_from_mysql('content', start_time=start, end_time=end) run_classify_text(rows) run_first_cluster('1', '1')
def run_all_process(start_time, end_time): '\n\n :param start_time:\n :param end_time:\n :return:\n ' start = arrow.get(start_time, 'YYYY-MM-DD').date() end = arrow.get(end_time, 'YYYY-MM-DD').date() rows = get_text_from_mysql('content', start_time=start, end_time=end) run_classify_text(rows) run_first_cluster('1', '1')<|docstring|>:param start_time: :param end_time: :return:<|endoftext|>
0d771e78b5cd14fee65a9c87b2b69fc51054869d576fdabce3e271755265c94f
def run_new_all_process(start_time, end_time, k): ' 新数据库热点话题发现流程. (一次聚类)\n\n :param start_time:\n :param end_time:\n :param k:\n :return:\n ' if isinstance(start_time, date): start = start_time else: start = arrow.get(start_time, 'YYYY-MM-DD').date() if isinstance(end_time, date): end = end_time else: end = arrow.get(end_time, 'YYYY-MM-DD').date() rows = get_text_from_mysql('content', start_time=start, end_time=end) run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_first_cluster_hot_topic() run_draw_chart(db=1) run_draw_top_keyword_barh(db=1)
新数据库热点话题发现流程. (一次聚类) :param start_time: :param end_time: :param k: :return:
utils.py
run_new_all_process
guoweikuang/weibo_project
4
python
def run_new_all_process(start_time, end_time, k): ' 新数据库热点话题发现流程. (一次聚类)\n\n :param start_time:\n :param end_time:\n :param k:\n :return:\n ' if isinstance(start_time, date): start = start_time else: start = arrow.get(start_time, 'YYYY-MM-DD').date() if isinstance(end_time, date): end = end_time else: end = arrow.get(end_time, 'YYYY-MM-DD').date() rows = get_text_from_mysql('content', start_time=start, end_time=end) run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_first_cluster_hot_topic() run_draw_chart(db=1) run_draw_top_keyword_barh(db=1)
def run_new_all_process(start_time, end_time, k): ' 新数据库热点话题发现流程. (一次聚类)\n\n :param start_time:\n :param end_time:\n :param k:\n :return:\n ' if isinstance(start_time, date): start = start_time else: start = arrow.get(start_time, 'YYYY-MM-DD').date() if isinstance(end_time, date): end = end_time else: end = arrow.get(end_time, 'YYYY-MM-DD').date() rows = get_text_from_mysql('content', start_time=start, end_time=end) run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_first_cluster_hot_topic() run_draw_chart(db=1) run_draw_top_keyword_barh(db=1)<|docstring|>新数据库热点话题发现流程. (一次聚类) :param start_time: :param end_time: :param k: :return:<|endoftext|>
c04d9fa153f52a6089437533d37fd89de6ee4eb60fd1ac4146bba265152cc269
def run_old_second_all_process(start_time, end_time): '\n 所有流程汇总. test 使用\n :param start_time:\n :param end_time:\n :return:\n ' rows = read_text_old_mysql(end_time, days=30, database='weibo') run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_second_cluster() run_second_cluster_hot_topic(db=1, hot_db=2) run_draw_chart(db=2) run_draw_top_keyword_barh(db=2, draw_type='second')
所有流程汇总. test 使用 :param start_time: :param end_time: :return:
utils.py
run_old_second_all_process
guoweikuang/weibo_project
4
python
def run_old_second_all_process(start_time, end_time): '\n 所有流程汇总. test 使用\n :param start_time:\n :param end_time:\n :return:\n ' rows = read_text_old_mysql(end_time, days=30, database='weibo') run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_second_cluster() run_second_cluster_hot_topic(db=1, hot_db=2) run_draw_chart(db=2) run_draw_top_keyword_barh(db=2, draw_type='second')
def run_old_second_all_process(start_time, end_time): '\n 所有流程汇总. test 使用\n :param start_time:\n :param end_time:\n :return:\n ' rows = read_text_old_mysql(end_time, days=30, database='weibo') run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_second_cluster() run_second_cluster_hot_topic(db=1, hot_db=2) run_draw_chart(db=2) run_draw_top_keyword_barh(db=2, draw_type='second')<|docstring|>所有流程汇总. test 使用 :param start_time: :param end_time: :return:<|endoftext|>
f1bb611f1dfdd12f835fde076ca52e6ed903449011e5b43e12d68a513973c45a
def run_old_all_process(end_time): '\n\n :param end_time:\n :return:\n ' rows = read_text_old_mysql(end_time, days=30, database='weibo') save_to_file('old_mysql', rows) run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_hot_topic(db=0, hot_db=1) run_draw_chart(db=1) run_draw_top_keyword_barh(db=1)
:param end_time: :return:
utils.py
run_old_all_process
guoweikuang/weibo_project
4
python
def run_old_all_process(end_time): '\n\n :param end_time:\n :return:\n ' rows = read_text_old_mysql(end_time, days=30, database='weibo') save_to_file('old_mysql', rows) run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_hot_topic(db=0, hot_db=1) run_draw_chart(db=1) run_draw_top_keyword_barh(db=1)
def run_old_all_process(end_time): '\n\n :param end_time:\n :return:\n ' rows = read_text_old_mysql(end_time, days=30, database='weibo') save_to_file('old_mysql', rows) run_classify_text(rows) run_classify(corpus_path, seg_path, bag_path, test_bag_path, test_corpus_path, test_seg_path) run_first_cluster('1', '1') run_hot_topic(db=0, hot_db=1) run_draw_chart(db=1) run_draw_top_keyword_barh(db=1)<|docstring|>:param end_time: :return:<|endoftext|>
91805efe6c8c1419fec74b31961451070aa4e03b3184ec4ba82376dbf56055e0
def create_multi_density(data, fields, name): '\n create plot which compare the density of the input fields\n :param data: pandas dataframe\n :param fields: dataframe fields name to plot thier density\n :param name: plot name and filename for the output\n ' if (type(fields) == type('')): fields = [fields] plt.figure(figsize=(8, 4)) for f in range(len(fields)): clm = list(data[fields[f]]) sns.kdeplot(clm, color=COLORS[(f % len(COLORS))], label=fields[f]) plt.title(name) plt.xlabel(('values of: ' + ', '.join(fields))) plt.ylabel('density') plt.legend(loc='upper left') plt.savefig((name + '.png')) plt.show()
create plot which compare the density of the input fields :param data: pandas dataframe :param fields: dataframe fields name to plot thier density :param name: plot name and filename for the output
multi_density.py
create_multi_density
EtzionR/create-multi-smooth-density-plot
1
python
def create_multi_density(data, fields, name): '\n create plot which compare the density of the input fields\n :param data: pandas dataframe\n :param fields: dataframe fields name to plot thier density\n :param name: plot name and filename for the output\n ' if (type(fields) == type()): fields = [fields] plt.figure(figsize=(8, 4)) for f in range(len(fields)): clm = list(data[fields[f]]) sns.kdeplot(clm, color=COLORS[(f % len(COLORS))], label=fields[f]) plt.title(name) plt.xlabel(('values of: ' + ', '.join(fields))) plt.ylabel('density') plt.legend(loc='upper left') plt.savefig((name + '.png')) plt.show()
def create_multi_density(data, fields, name): '\n create plot which compare the density of the input fields\n :param data: pandas dataframe\n :param fields: dataframe fields name to plot thier density\n :param name: plot name and filename for the output\n ' if (type(fields) == type()): fields = [fields] plt.figure(figsize=(8, 4)) for f in range(len(fields)): clm = list(data[fields[f]]) sns.kdeplot(clm, color=COLORS[(f % len(COLORS))], label=fields[f]) plt.title(name) plt.xlabel(('values of: ' + ', '.join(fields))) plt.ylabel('density') plt.legend(loc='upper left') plt.savefig((name + '.png')) plt.show()<|docstring|>create plot which compare the density of the input fields :param data: pandas dataframe :param fields: dataframe fields name to plot thier density :param name: plot name and filename for the output<|endoftext|>
95e075c71f95bed57151108d9f087eea0657508fdb0fd9672e615a1b040b7b57
def __init__(self, env: Environment, name: str, configuration: Dict[(str, Any)]): 'Initialization' super().__init__(env, name, configuration, self.execute()) self._efficiency = configuration.get('efficiency', 0.95) self._refractive_index = configuration.get('refractive_index', 1.47) self.env.process(self.run())
Initialization
source/astroNS/nodes/network/fiber_terminal.py
__init__
pyastroNS/astroNS
0
python
def __init__(self, env: Environment, name: str, configuration: Dict[(str, Any)]): super().__init__(env, name, configuration, self.execute()) self._efficiency = configuration.get('efficiency', 0.95) self._refractive_index = configuration.get('refractive_index', 1.47) self.env.process(self.run())
def __init__(self, env: Environment, name: str, configuration: Dict[(str, Any)]): super().__init__(env, name, configuration, self.execute()) self._efficiency = configuration.get('efficiency', 0.95) self._refractive_index = configuration.get('refractive_index', 1.47) self.env.process(self.run())<|docstring|>Initialization<|endoftext|>
2871061dc67f02205a5af62ca51d88ac16b8db44ae00433d66012883a5ec6709
@property def efficiency(self): 'Efficiency of cabling between two nodes, used to artifically inflate\n the actual distance the fiber optic cable\n :param efficiency: Cabling efficiency, a value of 1 would mean that the\n cable flows directly between the two nodes with no deviations\n\n :return: float\n ' return float(self._efficiency)
Efficiency of cabling between two nodes, used to artifically inflate the actual distance the fiber optic cable :param efficiency: Cabling efficiency, a value of 1 would mean that the cable flows directly between the two nodes with no deviations :return: float
source/astroNS/nodes/network/fiber_terminal.py
efficiency
pyastroNS/astroNS
0
python
@property def efficiency(self): 'Efficiency of cabling between two nodes, used to artifically inflate\n the actual distance the fiber optic cable\n :param efficiency: Cabling efficiency, a value of 1 would mean that the\n cable flows directly between the two nodes with no deviations\n\n :return: float\n ' return float(self._efficiency)
@property def efficiency(self): 'Efficiency of cabling between two nodes, used to artifically inflate\n the actual distance the fiber optic cable\n :param efficiency: Cabling efficiency, a value of 1 would mean that the\n cable flows directly between the two nodes with no deviations\n\n :return: float\n ' return float(self._efficiency)<|docstring|>Efficiency of cabling between two nodes, used to artifically inflate the actual distance the fiber optic cable :param efficiency: Cabling efficiency, a value of 1 would mean that the cable flows directly between the two nodes with no deviations :return: float<|endoftext|>
e1a981da6fcb75f785be696034a30bf788fa934e82bbe69c9f15ea0254981b7e
@property def refractive_index(self): 'Refractive index is the slowdown of the speed of light through the\n fiber material compared to free space\n :param refractive_index: Refractive index of fiber material to slow\n down speed of light\n :return: float\n ' return float(self._refractive_index)
Refractive index is the slowdown of the speed of light through the fiber material compared to free space :param refractive_index: Refractive index of fiber material to slow down speed of light :return: float
source/astroNS/nodes/network/fiber_terminal.py
refractive_index
pyastroNS/astroNS
0
python
@property def refractive_index(self): 'Refractive index is the slowdown of the speed of light through the\n fiber material compared to free space\n :param refractive_index: Refractive index of fiber material to slow\n down speed of light\n :return: float\n ' return float(self._refractive_index)
@property def refractive_index(self): 'Refractive index is the slowdown of the speed of light through the\n fiber material compared to free space\n :param refractive_index: Refractive index of fiber material to slow\n down speed of light\n :return: float\n ' return float(self._refractive_index)<|docstring|>Refractive index is the slowdown of the speed of light through the fiber material compared to free space :param refractive_index: Refractive index of fiber material to slow down speed of light :return: float<|endoftext|>
b968a22ab52a763e141d1223a88bfdc3405e50e205bd1e860743182f49c865f4
def execute(self): 'Execute function, part of simpy functionality' delay: float = 0.0 processing_time: float = delay data_out_list: List[Tuple] = [] while True: data_in = (yield (delay, processing_time, data_out_list)) if data_in: msg = data_in.copy() if ('fiber_transmit_location' in msg): try: rcvr_position = self.get_location(self.env.now)[0][:2] except AttributeError: raise AttributeError('No Propagator was attached.') trans_position = msg['fiber_transmit_location'][0][:2] d = geodesic(rcvr_position, trans_position).km v = (c.to((u.km / u.s)).value / self._refractive_index) t = ((d / self._efficiency) / v) print((self.log_prefix(id) + 'Receiving at fiber location -- Message delay was {}'.format(t))) msg.pop('fiber_transmit_location') delay = t processing_time = t data_out_list = [msg] else: msg['fiber_transmit_location'] = self.get_location(self.env.now) print((self.log_prefix(id) + 'Transmitting from Fiber Location -- {}'.format(msg['fiber_transmit_location']))) delay = 0 processing_time = 0 data_out_list = [msg]
Execute function, part of simpy functionality
source/astroNS/nodes/network/fiber_terminal.py
execute
pyastroNS/astroNS
0
python
def execute(self): delay: float = 0.0 processing_time: float = delay data_out_list: List[Tuple] = [] while True: data_in = (yield (delay, processing_time, data_out_list)) if data_in: msg = data_in.copy() if ('fiber_transmit_location' in msg): try: rcvr_position = self.get_location(self.env.now)[0][:2] except AttributeError: raise AttributeError('No Propagator was attached.') trans_position = msg['fiber_transmit_location'][0][:2] d = geodesic(rcvr_position, trans_position).km v = (c.to((u.km / u.s)).value / self._refractive_index) t = ((d / self._efficiency) / v) print((self.log_prefix(id) + 'Receiving at fiber location -- Message delay was {}'.format(t))) msg.pop('fiber_transmit_location') delay = t processing_time = t data_out_list = [msg] else: msg['fiber_transmit_location'] = self.get_location(self.env.now) print((self.log_prefix(id) + 'Transmitting from Fiber Location -- {}'.format(msg['fiber_transmit_location']))) delay = 0 processing_time = 0 data_out_list = [msg]
def execute(self): delay: float = 0.0 processing_time: float = delay data_out_list: List[Tuple] = [] while True: data_in = (yield (delay, processing_time, data_out_list)) if data_in: msg = data_in.copy() if ('fiber_transmit_location' in msg): try: rcvr_position = self.get_location(self.env.now)[0][:2] except AttributeError: raise AttributeError('No Propagator was attached.') trans_position = msg['fiber_transmit_location'][0][:2] d = geodesic(rcvr_position, trans_position).km v = (c.to((u.km / u.s)).value / self._refractive_index) t = ((d / self._efficiency) / v) print((self.log_prefix(id) + 'Receiving at fiber location -- Message delay was {}'.format(t))) msg.pop('fiber_transmit_location') delay = t processing_time = t data_out_list = [msg] else: msg['fiber_transmit_location'] = self.get_location(self.env.now) print((self.log_prefix(id) + 'Transmitting from Fiber Location -- {}'.format(msg['fiber_transmit_location']))) delay = 0 processing_time = 0 data_out_list = [msg]<|docstring|>Execute function, part of simpy functionality<|endoftext|>