id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
2,700
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.HabitsChange
class HabitsChange(TasksChange): # pylint: disable=missing-class-docstring,abstract-method domain = 'habits' ids_can_overlap = True def domain_print(self): Habits.invoke(config_filename=self.config_filename)
class HabitsChange(TasksChange): def domain_print(self): pass
2
0
2
0
2
0
1
0.2
1
1
1
3
1
0
1
8
5
0
5
4
3
1
5
4
3
1
4
0
1
2,701
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.HabitsAdd
class HabitsAdd(ApplicationWithApi): # pylint: disable=missing-class-docstring DESCRIPTION = _("Add a habit <habit>") # noqa: Q000 priority = cli.SwitchAttr( ['-p', '--priority'], cli.Set('0.1', '1', '1.5', '2'), default='1', help=_("Priority (complexity) of a habit")) # noqa: Q000 direction = cli.SwitchAttr( ['-d', '--direction'], cli.Set('positive', 'negative', 'both'), default='both', help=_("positive/negative/both")) # noqa: Q000 def main(self, *habit: str): habit_str = ' '.join(habit) if not habit_str: self.log.error(_("Empty habit text!")) # noqa: Q000 return 1 super().main() self.api.tasks.user.post( type='habit', text=habit_str, priority=self.priority, up=(self.direction != 'negative'), down=self.direction != 'positive') res = _("Added habit '{}' with priority {} and direction {}").format( # noqa: Q000 habit_str, self.priority, self.direction) print(prettify(res)) Habits.invoke(config_filename=self.config_filename) return None
class HabitsAdd(ApplicationWithApi): def main(self, *habit: str): pass
2
0
16
1
15
2
2
0.24
1
3
1
0
1
0
1
3
27
2
25
7
23
6
15
7
13
2
3
1
2
2,702
ASMfreaK/habitipy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ASMfreaK_habitipy/tests/test_habitipy.py
tests.test_habitipy.TestHabitipy
class TestHabitipy(unittest.TestCase): def test_python_keyword_escape(self): api = Habitipy(None) self.assertEqual(api.user.class_._current, [ 'api', 'v3', 'user', 'class']) self.assertEqual(api['user']['class']._current, api.user.class_._current) self.assertEqual(api['user']['buy-armoire']._current, api.user.buy_armoire._current) self.assertEqual(api['user', 'buy-armoire']._current, api.user.buy_armoire._current) self.assertIn('tasks', dir(api)) self.assertIn('user', dir(api.tasks)) self.assertIn('user', dir(api)) self.assertIn('class_', dir(api.user)) self.assertNotIn('class', dir(api.user)) def test_integration(self): api = Habitipy(None) with self.assertRaises(IndexError): api.abracadabra with self.assertRaises(IndexError): api['abracadabra'] def test_init_typing(self): with self.assertRaises(TypeError): api = Habitipy(None, apis='abracadabra') with self.assertRaises(TypeError): api = Habitipy(None, current='abracadabra') # @unittest.skipIf( # os.environ.get('CI', '') != 'true', # 'network-heavy (not in CI env(CI="{}"))'.format(os.environ.get('CI', ''))) def test_download_api(self): with patch('habitipy.api.local') as mock: with responses.RequestsMock() as rsps: rsps.add( responses.GET, 'https://api.github.com/repos/HabitRPG/habitica/releases/latest', json=dict(tag_name='TEST_TAG')) m = hapi.download_api() self.assertEqual( mock.__getitem__.call_args_list, [call('curl'), call('tar'), call('grep'), call('sed')]) self.assertEqual( mock.__getitem__.return_value.__getitem__.call_count, 4) for actual, expected in zip(mock.__getitem__.return_value.__getitem__.call_args_list, [ call( ('-sL', 'https://api.github.com/repos/HabitRPG/habitica/tarball/TEST_TAG')), call(( 'axzf', '-', '--wildcards', '*/website/server/controllers/api-v3/*', '--to-stdout')), call(('@api')), call(('-e', 's/^[ */]*//g', '-e', 's/ / /g', '-'))]): self.assertEqual(actual, expected) @patch('habitipy.api.download_api') def test_github(self, mock): with open(pkg_resources.resource_filename('habitipy', 'apidoc.txt')) as f: mock.return_value = f.read() import builtins lp = local.path(APIDOC_LOCAL_FILE) Habitipy(None, from_github=True, branch='develop') self.assertTrue(mock.called) self.assertTrue(lp.exists()) with patch('builtins.open', MagicMock(wraps=builtins.open)) as mock: Habitipy(None) mock.assert_called_with(lp, encoding='utf-8') os.remove(lp) Habitipy(None, from_github=True) self.assertTrue(mock.called) self.assertTrue(lp.exists()) with patch('builtins.open', MagicMock(wraps=builtins.open)) as mock: Habitipy(None) mock.assert_called_with(lp, encoding='utf-8') os.remove(lp)
class TestHabitipy(unittest.TestCase): def test_python_keyword_escape(self): pass def test_integration(self): pass def test_init_typing(self): pass def test_download_api(self): pass @patch('habitipy.api.download_api') def test_github(self, mock): pass
7
0
12
0
12
0
1
0.05
1
6
1
0
5
0
5
77
72
6
63
17
55
3
51
13
44
2
2
2
6
2,703
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.HabitsDown
class HabitsDown(HabitsChange): # pylint: disable=missing-class-docstring DESCRIPTION = _("Down (-) a habit with task_id") # noqa: Q000 def op(self, tid): self.tasks[tid].score['down'].post() def validate(self, task): return task['down'] def log_op(self, tid): """show a message to user on successful change of `tid`""" return _("Decremented habit {text}").format(**self.changing_tasks[tid])
class HabitsDown(HabitsChange): def op(self, tid): pass def validate(self, task): pass def log_op(self, tid): '''show a message to user on successful change of `tid`''' pass
4
1
2
0
2
1
1
0.5
1
0
0
0
3
0
3
11
11
2
8
5
4
4
8
5
4
1
5
0
3
2,704
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.HabitsUp
class HabitsUp(HabitsChange): # pylint: disable=missing-class-docstring DESCRIPTION = _("Up (+) a habit with task_id") # noqa: Q000 def op(self, tid): self.tasks[tid].score['up'].post() def validate(self, task): return task['up'] def log_op(self, tid): return _("Incremented habit {text}").format(**self.changing_tasks[tid])
class HabitsUp(HabitsChange): def op(self, tid): pass def validate(self, task): pass def log_op(self, tid): pass
4
0
2
0
2
0
1
0.38
1
0
0
0
3
0
3
11
10
2
8
5
4
3
8
5
4
1
5
0
3
2,705
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.DailysUp
class DailysUp(DailysChange): # pylint: disable=missing-class-docstring DESCRIPTION = _("Check a dayly with task_id") # noqa: Q000 def op(self, tid): self.tasks[tid].score['up'].post() def log_op(self, tid): return _("Completed daily {text}").format(**self.changing_tasks[tid])
class DailysUp(DailysChange): def op(self, tid): pass def log_op(self, tid): pass
3
0
2
0
2
1
1
0.5
1
0
0
0
2
0
2
10
7
1
6
4
3
3
6
4
3
1
5
0
2
2,706
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.HatchPet
class HatchPet(Pets): """Hatches pets with eggs when possible.""" sleep_time = cli.SwitchAttr( ['-S', '--sleep-time'], argtype=int, default=1, help=_('Time to wait between feeding each pet to avoid overloading the server')) # pylint: disable=line-too-long maximum_food = cli.SwitchAttr( ['-M', '--maxmimum-food'], argtype=int, default=10, help=_('Maximum amount of food to feed a pet') ) def main(self): super().main() user = self.api.user.get() pets = user['items']['pets'] color_specifier = self.color_specifier if color_specifier: color_specifier = color_specifier[0].capitalize() + color_specifier[1:] pet_specifier = self.pet_specifier if pet_specifier: pet_specifier = pet_specifier[0].capitalize() + pet_specifier[1:] for pet in pets: (pettype, color) = pet.split('-') if pet_specifier and pettype != pet_specifier: continue if color_specifier and color != color_specifier: continue if self.is_hatchable(user, pettype, color): print(_(f'hatching {color} {pettype}')) self.api.user.hatch[pettype][color].post() time.sleep(self.sleep_time) else: print(_(f'NOT hatching {color} {pettype}'))
class HatchPet(Pets): '''Hatches pets with eggs when possible.''' def main(self): pass
2
1
26
4
22
0
7
0.07
1
1
0
0
1
0
1
6
36
5
30
10
28
2
24
10
22
7
4
2
7
2,707
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Habits
class Habits(TasksPrint): # pylint: disable=missing-docstring DESCRIPTION = _("List, up and down habit tasks") # noqa: Q000 domain = 'habits' def domain_format(self, habit): # pylint: disable=arguments-renamed score = ScoreInfo(self.config['show_style'], habit['value']) return _("{0} {text}").format(score, **habit)
class Habits(TasksPrint): def domain_format(self, habit): pass
2
0
3
0
3
2
1
0.67
1
1
1
0
1
0
1
5
6
0
6
5
4
4
6
5
4
1
4
0
1
2,708
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.DailysChange
class DailysChange(TasksChange): # pylint: disable=missing-class-docstring,abstract-method domain = 'dailys' def domain_print(self): Dailys.invoke(config_filename=self.config_filename)
class DailysChange(TasksChange): def domain_print(self): pass
2
0
2
0
2
0
1
0.25
1
1
1
2
1
0
1
8
4
0
4
3
2
1
4
3
2
1
4
0
1
2,709
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/api.py
habitipy.api.WrongData
class WrongData(ValueError): """Custom error type"""
class WrongData(ValueError): '''Custom error type''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
2,710
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.DailyDown
class DailyDown(DailysChange): # pylint: disable=missing-class-docstring DESCRIPTION = _("Uncheck a daily with task_id") # noqa: Q000 def op(self, tid): self.tasks[tid].score['down'].post() def log_op(self, tid): return _("Unchecked daily {text}").format(**self.changing_tasks[tid])
class DailyDown(DailysChange): def op(self, tid): pass def log_op(self, tid): pass
3
0
2
0
2
1
1
0.5
1
0
0
0
2
0
2
10
7
1
6
4
3
3
6
4
3
1
5
0
2
2,711
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Content
class Content(Mapping): """Caching class for Habitica content data""" _cache = None def __init__(self, api, rebuild_cache=False, path=None): self._api = api self._path = [] self._rebuild_cache = rebuild_cache self._path = path self._obj = None self._resolve_path() def __getitem__(self, i): try: ret = self._obj[i] if isinstance(ret, (list, dict)): return Content(self._api, self._rebuild_cache, [*self._path, i]) return ret except (KeyError, IndexError): if self._rebuild_cache: raise self._rebuild_cache = True self._resolve_path() return self.__getitem__(i) def __iter__(self): if self._obj: yield from iter(self._obj) def __len__(self): if self._obj: return len(self._obj) return 0 def _resolve_path(self): if self._path is None: self._path = [] self._obj = self._get() for e in self._path: self._obj = self._obj[e] def _get(self): """get content from server or cache""" if Content._cache and not self._rebuild_cache: return Content._cache if not os.path.exists(CONTENT_JSON) or self._rebuild_cache: content_endpoint = self._api.content.get # pylint: disable=protected-access server_lang = content_endpoint._node.params['query']['language'] Content._cache = content_endpoint(**next(( {'language': lang} for lang in chain( Content._lang_from_translation(), Content._lang_from_locale()) if lang in server_lang.possible_values ), {})) # default with open(CONTENT_JSON, 'w', encoding='utf-8') as f: json.dump(Content._cache, f) return Content._cache try: with open(CONTENT_JSON, encoding='utf-8') as f: Content._cache = json.load(f) return Content._cache except JSONDecodeError: self._rebuild_cache = True return self._get() @staticmethod def _lang_from_translation(): try: yield get_translation_for('habitipy').info()['language'] except KeyError: pass @staticmethod def _lang_from_locale(): import locale # pylint: disable=import-outside-toplevel try: loc = locale.getlocale()[0] if loc: # handle something like 'ru_RU' not available - only 'ru' yield loc yield loc[:2] except IndexError: pass
class Content(Mapping): '''Caching class for Habitica content data''' def __init__(self, api, rebuild_cache=False, path=None): pass def __getitem__(self, i): pass def __iter__(self): pass def __len__(self): pass def _resolve_path(self): pass def _get(self): '''get content from server or cache''' pass @staticmethod def _lang_from_translation(): pass @staticmethod def _lang_from_locale(): pass
11
2
9
0
9
1
3
0.08
1
6
0
0
6
4
8
42
85
8
73
23
61
6
65
20
55
4
6
2
21
2,712
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.ConfiguredApplication
class ConfiguredApplication(cli.Application): """Application with config""" config_filename = cli.SwitchAttr( ['-c', '--config'], argtype=local.path, default=DEFAULT_CONF, argname='CONFIG', help=_("Use file CONFIG for config")) # noqa: Q000 verbose = cli.Flag( ['-v', '--verbose'], help=_("Verbose output - log everything."), # noqa: Q000 excludes=['-s', '--silent']) silence_level = cli.CountOf( ['-s', '--silent'], help=_("Make program more silent"), # noqa: Q000 excludes=['-v', '--verbose']) def main(self): self.config = load_conf(self.config_filename) self.log = logging.getLogger(str(self.__class__).split("'")[1]) self.log.addHandler(logging.StreamHandler()) if self.verbose: self.log.setLevel(logging.DEBUG) else: base_level = logging.INFO self.log.setLevel(base_level + 10 * self.silence_level)
class ConfiguredApplication(cli.Application): '''Application with config''' def main(self): pass
2
1
9
0
9
0
2
0.18
1
2
0
3
1
2
1
1
24
1
22
8
20
4
12
8
10
2
1
1
2
2,713
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.ApplicationWithApi
class ApplicationWithApi(ConfiguredApplication): """Application with configured Habitica API""" api = None # type: Habitipy def main(self, *_args): super().main() self.api = Habitipy(self.config)
class ApplicationWithApi(ConfiguredApplication): '''Application with configured Habitica API''' def main(self, *_args): pass
2
1
3
0
3
0
1
0.4
1
2
1
11
1
0
1
2
7
1
5
3
3
2
5
3
3
1
2
0
1
2,714
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/api.py
habitipy.api.WrongReturnCode
class WrongReturnCode(ValueError): """Custom error type"""
class WrongReturnCode(ValueError): '''Custom error type''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
2,715
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/api.py
habitipy.api.WrongPath
class WrongPath(ValueError): """Custom error type"""
class WrongPath(ValueError): '''Custom error type''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
2,716
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/api.py
habitipy.api.ParamAlreadyExist
class ParamAlreadyExist(ValueError): """Custom error type"""
class ParamAlreadyExist(ValueError): '''Custom error type''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
2,717
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/api.py
habitipy.api.Habitipy
class Habitipy: """ Represents Habitica API # Arguments conf : Configuration dictionary for API. Should contain `url`, `login` and `password` fields apis (None, List[ApiEndpoint], ApiNode): Field, representing API endpoints. current : current position in the API from_github : whether it is needed to download apiDoc from habitica's github branch : branch to use to download apiDoc from habitica's github strict : show warnings on inconsistent apiDocs # Example ```python from habitipy import Habitipy conf = { 'url': 'https://habitica.com', 'login': 'your-login-uuid-to-replace', 'password': 'your-password-uuid-here' api = Habitipy(conf) print(api.user.get()) ``` Interactive help: ```python In [1]: from habitipy import Habitipy, load_conf,DEFAULT_CONF In [2]: api = Habitipy(load_conf(DEFAULT_CONF)) In [3]: api.<tab> api.approvals api.debug api.models api.tags api.challenges api.group api.notifications api.tasks api.content api.groups api.reorder-tags api.user api.coupons api.hall api.shops api.cron api.members api.status In [84]: api.user.get? Signature: api.user.get(**kwargs) Type: Habitipy String form: <habitipy.api.Habitipy object at 0x7fa6fd7966d8> File: ~/projects/python/habitica/habitipy/api.py Docstring: {get} /api/v3/user Get the authenticated user's profile responce params: "data" of type "object" ``` From other Python consoles you can just run: ```python >>> dir(api) ['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_apis', '_conf', '_current', '_is_request', '_make_apis_dict', '_make_headers', '_node', 'approvals', 'challenges', 'content', 'coupons', 'cron', 'debug', 'group', 'groups', 'hall', 'members', 'models', 'notifications', 'reorder-tags', 'shops', 'status', 'tags', 'tasks', 'user'] >>> print(api.user.get.__doc__) {get} /api/v3/user Get the authenticated user's profile responce params: "data" of type "object" ``` """ # pylint: disable=too-many-arguments def __init__(self, conf: Dict[str, str], *, apis=None, current: Optional[List[str]] = None, from_github=False, branch=None, strict=False) -> None: self._conf = conf self._strict = strict if isinstance(apis, (type(None), list)): if not apis: fn = local.path(APIDOC_LOCAL_FILE) if not fn.exists(): fn = pkg_resources.resource_filename('habitipy', 'apidoc.txt') fn = branch if from_github else fn with warnings.catch_warnings(): warnings.simplefilter('error' if strict else 'ignore') apis = parse_apidoc(fn, from_github) with warnings.catch_warnings(): warnings.simplefilter('error' if strict else 'ignore') apis = self._make_apis_dict(apis) if isinstance(apis, ApiNode): self._apis = apis else: raise TypeError('Possible apis {} have wrong type({})'.format(apis, type(apis))) current = current or ['api', 'v3'] if not isinstance(current, list): raise TypeError('Wrong current api position {}'.format(current)) _node = self._apis # type: Union[ApiNode, ApiEndpoint] for part in current: if isinstance(_node, ApiNode): _node = _node.into(part) else: raise WrongPath("""Can't enter into {} with part {}""".format(_node, part)) self._node = _node self._current = current if isinstance(self._node, ApiEndpoint): self.__doc__ = self._node.render_docstring() @staticmethod def _make_apis_dict(apis) -> ApiNode: node = ApiNode() for api in apis: cur_node = node prev_part = '' for part in api.parted_uri: if cur_node.can_into(part): _node = cur_node.into(part) else: try: _node = cur_node.place(part, ApiNode()) except ParamAlreadyExist: warnings.warn( 'Ignoring conflicting param. Don\'t use {}'.format( # noqa: Q00 api.uri)) _node = cur_node.param cur_node = _node # type: ignore prev_part += '/' + part cur_node.place(api.method, api) return node def _make_headers(self): headers = { 'x-api-user': self._conf['login'], 'x-api-key': self._conf['password'] } if self._conf else {} headers.update({'content-type': API_CONTENT_TYPE}) return headers def __dir__(self): return super().__dir__() + list(escape_keywords(self._node.keys())) def __getattr__(self, val: str) -> Union[Any, 'Habitipy']: if val in dir(super()): # pylint: disable=no-member return super().__getattr__(val) # type:ignore val = val if not val.endswith('_') else val.rstrip('_') val = val if '_' not in val else val.replace('_', '-') return self.__class__(self._conf, apis=self._apis, current=self._current + [val]) def __getitem__(self, val: Union[str, List[str], Tuple[str, ...]]) -> 'Habitipy': if isinstance(val, str): return self.__class__(self._conf, apis=self._apis, current=self._current + [val]) if isinstance(val, (list, tuple)): current = self._current + list(val) return self.__class__(self._conf, apis=self._apis, current=current) raise IndexError('{} not found in this API!'.format(val)) def _prepare_request(self, backend=requests, **kwargs): uri = '/'.join([self._conf['url']] + self._current[:-1]) if not isinstance(self._node, ApiEndpoint): raise ValueError('{} is not an endpoint!'.format(uri)) method = self._node.method headers = self._make_headers() # allow a caller to force URI parameters when API document is incorrect if 'uri_params' in kwargs: uri += '?' + '&'.join([str(x) + '=' + str(y) for x, y in kwargs['uri_params'].items()]) query = {} if 'query' in self._node.params: for name, param in self._node.params['query'].items(): if name in kwargs: query[name] = kwargs.pop(name) elif not param.is_optional: raise TypeError('Mandatory param {} is missing'.format(name)) request = getattr(backend, method) request_args = (uri,) request_kwargs = {'headers': headers, 'params': query} if method in ['put', 'post', 'delete']: request_kwargs['data'] = json.dumps(kwargs) return request, request_args, request_kwargs def _request(self, request, request_args, request_kwargs): res = request(*request_args, **request_kwargs) if res.status_code != self._node.retcode: res.raise_for_status() msg = _(""" Got return code {res.status_code}, but {node.retcode} was expected for {node.uri}. It may be a typo in Habitica apiDoc. Please file an issue to https://github.com/HabitRPG/habitica/issues""") msg = textwrap.dedent(msg) msg = msg.replace('\n', ' ').format(res=res, node=self._node) if self._strict: raise WrongReturnCode(msg) warnings.warn(msg) return res.json()['data'] def __call__(self, **kwargs) -> Union[Dict, List]: return self._request(*self._prepare_request(**kwargs))
class Habitipy: ''' Represents Habitica API # Arguments conf : Configuration dictionary for API. Should contain `url`, `login` and `password` fields apis (None, List[ApiEndpoint], ApiNode): Field, representing API endpoints. current : current position in the API from_github : whether it is needed to download apiDoc from habitica's github branch : branch to use to download apiDoc from habitica's github strict : show warnings on inconsistent apiDocs # Example ```python from habitipy import Habitipy conf = { 'url': 'https://habitica.com', 'login': 'your-login-uuid-to-replace', 'password': 'your-password-uuid-here' api = Habitipy(conf) print(api.user.get()) ``` Interactive help: ```python In [1]: from habitipy import Habitipy, load_conf,DEFAULT_CONF In [2]: api = Habitipy(load_conf(DEFAULT_CONF)) In [3]: api.<tab> api.approvals api.debug api.models api.tags api.challenges api.group api.notifications api.tasks api.content api.groups api.reorder-tags api.user api.coupons api.hall api.shops api.cron api.members api.status In [84]: api.user.get? Signature: api.user.get(**kwargs) Type: Habitipy String form: <habitipy.api.Habitipy object at 0x7fa6fd7966d8> File: ~/projects/python/habitica/habitipy/api.py Docstring: {get} /api/v3/user Get the authenticated user's profile responce params: "data" of type "object" ``` From other Python consoles you can just run: ```python >>> dir(api) ['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_apis', '_conf', '_current', '_is_request', '_make_apis_dict', '_make_headers', '_node', 'approvals', 'challenges', 'content', 'coupons', 'cron', 'debug', 'group', 'groups', 'hall', 'members', 'models', 'notifications', 'reorder-tags', 'shops', 'status', 'tags', 'tasks', 'user'] >>> print(api.user.get.__doc__) {get} /api/v3/user Get the authenticated user's profile responce params: "data" of type "object" ``` ''' def __init__(self, conf: Dict[str, str], *, apis=None, current: Optional[List[str]] = None, from_github=False, branch=None, strict=False) -> None: pass @staticmethod def _make_apis_dict(apis) -> ApiNode: pass def _make_headers(self): pass def __dir__(self): pass def __getattr__(self, val: str) -> Union[Any, 'Habitipy']: pass def __getitem__(self, val: Union[str, List[str], Tuple[str, ...]]) -> 'Habitipy': pass def _prepare_request(self, backend=requests, **kwargs): pass def _request(self, request, request_args, request_kwargs): pass def __call__(self, **kwargs) -> Union[Dict, List]: pass
11
1
13
0
13
1
4
0.55
0
15
5
1
8
6
9
9
193
17
116
41
102
64
100
37
90
12
0
4
39
2,718
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/api.py
habitipy.api.ApiNode
class ApiNode: """Represents a middle point in API""" def __init__(self, param_name=None, param=None, paths=None): self.param = param self.param_name = param_name self.paths = paths or {} # type: Dict[str, Union[ApiNode,ApiEndpoint]] def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: """Get another leaf node with name `val` if possible""" if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val)) # NOQA: Q000 def can_into(self, val: str) -> bool: """Determine if there is a leaf node with name `val`""" return val in self.paths or (self.param and self.param_name == val) def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): """place a leaf node""" if part.startswith(':'): if self.param and self.param != part: err = """Cannot place param '{}' as '{self.param_name}' exist on node already!""" raise ParamAlreadyExist(err.format(part, self=self)) self.param = val self.param_name = part return val self.paths[part] = val return val def keys(self) -> Iterator[str]: """return all possible paths one can take from this ApiNode""" if self.param: yield self.param_name yield from self.paths.keys() def __repr__(self) -> str: text = '<ApiNode {self.param_name}: {self.param} paths: {self.paths}>' return text.format(self=self) def is_param(self, val): """checks if val is this node's param""" return val == self.param_name
class ApiNode: '''Represents a middle point in API''' def __init__(self, param_name=None, param=None, paths=None): pass def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: '''Get another leaf node with name `val` if possible''' pass def can_into(self, val: str) -> bool: '''Determine if there is a leaf node with name `val`''' pass def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): '''place a leaf node''' pass def keys(self) -> Iterator[str]: '''return all possible paths one can take from this ApiNode''' pass def __repr__(self) -> str: pass def is_param(self, val): '''checks if val is this node's param''' pass
8
6
5
0
4
1
2
0.25
0
4
1
0
7
3
7
7
44
6
32
13
24
8
32
13
24
3
0
2
12
2,719
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/api.py
habitipy.api.ApiEndpoint
class ApiEndpoint: """ Represents a single api endpoint. """ def __init__(self, method, uri, title=''): self.method = method self.uri = uri self.parted_uri = uri[1:].split('/') self.title = title self.params = defaultdict(dict) self.retcode = None def add_param(self, group=None, type_='', field='', description=''): """parse and append a param""" group = group or '(Parameter)' group = group.lower()[1:-1] p = Param(type_, field, description) self.params[group][p.field] = p def add_success(self, group=None, type_='', field='', description=''): """parse and append a success data param""" group = group or '(200)' group = int(group.lower()[1:-1]) self.retcode = self.retcode or group if group != self.retcode: raise ValueError('Two or more retcodes!') type_ = type_ or '{String}' p = Param(type_, field, description) self.params['responce'][p.field] = p def __repr__(self): return '<@api {{{self.method}}} {self.uri} {self.title}>'.format(self=self) def render_docstring(self): """make a nice docstring for ipython""" res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self) if self.params: for group, params in self.params.items(): res += '\n' + group + ' params:\n' for param in params.values(): res += param.render_docstring() return res
class ApiEndpoint: ''' Represents a single api endpoint. ''' def __init__(self, method, uri, title=''): pass def add_param(self, group=None, type_='', field='', description=''): '''parse and append a param''' pass def add_success(self, group=None, type_='', field='', description=''): '''parse and append a success data param''' pass def __repr__(self): pass def render_docstring(self): '''make a nice docstring for ipython''' pass
6
4
7
0
6
1
2
0.19
0
4
1
0
5
6
5
5
42
4
32
17
26
6
32
17
26
4
0
3
9
2,720
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/aio.py
habitipy.aio.HabitipyAsync
class HabitipyAsync(Habitipy): """ Habitipy API using aiohttp as backend for request ```python async def HabitipyAsync.__call__( self, session: aiohttp.ClientSession, **kwargs ) -> Union[Dict, List] ``` # Arguments session (aiohttp.ClientSession): aiohttp session used to make request. # Example ```python import asyncio from aiohttp import ClientSession from habitipy import Habitipy, load_conf,DEFAULT_CONF from habitipy.aio import HabitipyAsync loop = asyncio.new_event_loop() api = HabitipyAsync(load_conf(DEFAULT_CONF)) async def main(api): async with ClientSession() as session: u = await api.user.get(session) return u loop.run_until_complete(main(api)) ``` """ def __call__( # type: ignore self, session: aiohttp.ClientSession, **kwargs) -> Union[Dict, List]: return self._request(*self._prepare_request(backend=session, **kwargs)) async def _request(self, request, request_args, request_kwargs): # pylint: disable=invalid-overridden-method async with request(*request_args, **request_kwargs) as resp: if resp.status != self._node.retcode: resp.raise_for_status() msg = _(""" Got return code {res.status}, but {node.retcode} was expected for {node.uri}. It may be a typo in Habitica apiDoc. Please file an issue to https://github.com/HabitRPG/habitica/issues""") msg = textwrap.dedent(msg) msg = msg.replace('\n', ' ').format(res=resp, node=self._node) if self._strict: raise WrongReturnCode(msg) warnings.warn(msg) return (await resp.json())['data']
class HabitipyAsync(Habitipy): ''' Habitipy API using aiohttp as backend for request ```python async def HabitipyAsync.__call__( self, session: aiohttp.ClientSession, **kwargs ) -> Union[Dict, List] ``` # Arguments session (aiohttp.ClientSession): aiohttp session used to make request. # Example ```python import asyncio from aiohttp import ClientSession from habitipy import Habitipy, load_conf,DEFAULT_CONF from habitipy.aio import HabitipyAsync loop = asyncio.new_event_loop() api = HabitipyAsync(load_conf(DEFAULT_CONF)) async def main(api): async with ClientSession() as session: u = await api.user.get(session) return u loop.run_until_complete(main(api)) ``` ''' def __call__( # type: ignore self, session: aiohttp.ClientSession, **kwargs) -> Union[Dict, List]: pass async def _request(self, request, request_args, request_kwargs): pass
3
1
10
0
10
1
2
1.4
1
2
1
0
2
0
2
11
53
7
20
8
14
28
14
4
11
3
1
3
4
2,721
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Home
class Home(ConfiguredApplication): # pylint: disable=missing-class-docstring DESCRIPTION = _("Open habitica site in browser") # noqa: Q000 def main(self): super().main() from webbrowser import open_new_tab # pylint: disable=import-outside-toplevel HABITICA_TASKS_PAGE = '/#/tasks' home_url = '{}{}'.format(self.config['url'], HABITICA_TASKS_PAGE) print(_("Opening {}").format(home_url)) # noqa: Q000 open_new_tab(home_url)
class Home(ConfiguredApplication): def main(self): pass
2
0
7
0
7
3
1
0.56
1
1
0
0
1
0
1
2
9
0
9
6
6
5
9
6
6
1
2
0
1
2,722
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Dailys
class Dailys(TasksPrint): # pylint: disable=missing-class-docstring DESCRIPTION = _("List, check, uncheck daily tasks") # noqa: Q000 domain = 'dailys' def domain_format(self, daily): # pylint: disable=arguments-renamed score = ScoreInfo(self.config['show_style'], daily['value']) check = CHECK if daily['completed'] else UNCHECK check = check[self.config['show_style']] checklist_done = len(list(filter(lambda x: x['completed'], daily['checklist']))) checklist = \ ' {}/{}'.format( checklist_done, len(daily['checklist']) ) if daily['checklist'] else '' res = _("{0}{1}{text}{2}").format(check, score, checklist, **daily) # noqa: Q000 if not daily['isDue']: res = colors.strikeout + colors.dark_gray | res return res
class Dailys(TasksPrint): def domain_format(self, daily): pass
2
0
14
0
14
2
4
0.24
1
3
1
0
1
0
1
5
17
0
17
9
15
4
13
9
11
4
4
1
4
2,723
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.ListPets
class ListPets(Pets): """Lists all pets from the inventory.""" def main(self): # pylint: disable=too-many-branches super().main() user = self.api.user.get() print(_('Pets:')) color_specifier = self.color_specifier if color_specifier: color_specifier = color_specifier[0].capitalize() + color_specifier[1:] pet_specifier = self.pet_specifier if pet_specifier: pet_specifier = pet_specifier[0].capitalize() + pet_specifier[1:] # split pets into type and color pet_summaries = defaultdict(dict) for pet in user['items']['pets']: (pettype, color) = pet.split('-') pet_summaries[pettype][color] = user['items']['pets'][pet] for pet in pet_summaries: if pet_specifier and pet != pet_specifier: continue pet_printed = False for color in pet_summaries[pet]: if color_specifier and color != color_specifier: continue if not pet_printed: print(f' {pet}:') pet_printed = True pet_full_level = pet_summaries[pet][color] if pet_full_level == -1: full_percentage = colors.red | _('No Pet') if self.is_hatchable(user, pet, color): full_percentage += ' ' + (colors.green | _('(hatchable)')) elif pet + '-' + color in user['items']['mounts']: full_percentage = colors.green | '100%' else: full_percentage = self.get_full_percent(pet_full_level) + '%' if full_percentage == '100%': full_percentage = colors.green | full_percentage else: full_percentage = colors.yellow | full_percentage print(f' {color:<30} {full_percentage}')
class ListPets(Pets): '''Lists all pets from the inventory.''' def main(self): pass
2
1
44
5
38
2
13
0.08
1
2
0
0
1
0
1
6
46
5
39
11
37
3
36
11
34
13
4
4
13
2,724
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.HabitsDelete
class HabitsDelete(HabitsChange): # pylint: disable=missing-class-docstring DESCRIPTION = _("Delete a habit with task_id") # noqa: Q000 def op(self, tid): self.tasks[tid].delete() def log_op(self, tid): return _("Deleted habit {text}").format(**self.changing_tasks[tid])
class HabitsDelete(HabitsChange): def op(self, tid): pass def log_op(self, tid): pass
3
0
2
0
2
1
1
0.5
1
0
0
0
2
0
2
10
7
1
6
4
3
3
6
4
3
1
5
0
2
2,725
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Rewards
class Rewards(TasksPrint): # pylint: disable=missing-class-docstring DESCRIPTION = _("List, buy and add rewards") # noqa: Q000 domain = 'rewards' def main(self): if self.nested_command: return ApplicationWithApi.main(self) self.more_tasks = get_additional_rewards(self.api) super().main() def domain_format(self, reward): # pylint: disable=arguments-renamed score = colors.yellow | _("{value} gp").format(**reward) # noqa: Q000 return _("{} {text}").format(score, **reward)
class Rewards(TasksPrint): def main(self): pass def domain_format(self, reward): pass
3
0
5
0
5
2
2
0.42
1
1
0
0
2
1
2
6
14
2
12
7
9
5
12
7
9
2
4
1
3
2,726
ASMfreaK/habitipy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ASMfreaK_habitipy/tests/test_cli.py
tests.test_cli.TestCli.test_tasks_change.TestDomain
class TestDomain(cli.TasksChange): domain = 'testdomain' more_tasks = _more_tasks ids_can_overlap = can_overlap def op(tself, tid): op(tid) self.assertIn(tid, tself.changing_tasks) def log_op(tself, tid): log_op(tid) self.assertIn(tid, tself.changing_tasks) def domain_print(tself): domain_print()
class TestDomain(cli.TasksChange): def op(tself, tid): pass def log_op(tself, tid): pass def domain_print(tself): pass
4
0
3
0
3
0
1
0
1
1
1
0
3
0
3
10
14
2
12
7
8
0
12
7
8
1
4
0
3
2,727
ASMfreaK/habitipy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ASMfreaK_habitipy/tests/test_cli.py
tests.test_cli.TestCli
class TestCli(unittest.TestCase): def setUp(self): self.file = tempfile.NamedTemporaryFile(delete=False) with self.file: self.file.write(dedent(""" [habitipy] url = https://habitica.com login = this-is-a-sample-login password = this-is-a-sample-password """).encode('utf-8')) def tearDown(self): if os.path.exists(self.file.name): os.remove(self.file.name) def test_content_cache(self): rsps = responses.RequestsMock() context = [ patch_file_name('habitipy.cli.CONTENT_JSON'), rsps, to_devnull() ] data = {} def content_callback(req): return (200, {}, json.dumps({'data': data})) with ExitStack() as stack: for cm in context: stack.enter_context(cm) rsps.add_callback( responses.GET, url=re.compile( r'https://habitica.com/api/v3/content\?language=.{2,5}'), content_type='application/json', match_querystring=True, callback=content_callback) api = Habitipy(load_conf(self.file.name)) content = cli.Content(api) self.assertTrue( rsps.calls[0].request.url.startswith( 'https://habitica.com/api/v3/content')) data = {'this_key_do_not_exist_on_first_run': { 'dict': {'a': 'b'}, 'empty_list': [], 'objs': [{'name': 'data'}] }} content['this_key_do_not_exist_on_first_run'] self.assertTrue( rsps.calls[1].request.url.startswith( 'https://habitica.com/api/v3/content')) with self.assertRaises(KeyError): content['this_key_do_not_exist_on_first_run']['dict']['tionary'] with self.assertRaises(IndexError): content['this_key_do_not_exist_on_first_run']['empty_list'][0] self.assertEqual( content['this_key_do_not_exist_on_first_run']['dict']['a'], 'b' ) def test_task_print(self): data = [{'first': 1}, {'second': 2}] more = [{'third': 3}] context = [ patch.object(cli.TasksPrint, 'domain', 'testdomain'), patch.object( cli.TasksPrint, 'domain_format', mock.Mock(wraps=cli.TasksPrint.domain_format, return_value='')), patch('habitipy.cli.prettify', mock.Mock(wraps=cli.prettify)), patch.object(cli.TasksPrint, 'more_tasks', more)] rsps = responses.RequestsMock() context.extend([rsps, to_devnull()]) with ExitStack() as stack: for cm in context: stack.enter_context(cm) rsps.add( responses.GET, url='https://habitica.com/api/v3/tasks/user?type=testdomain', content_type='application/json', match_querystring=True, json=dict(data=data)) instance, retcode = cli.TasksPrint.invoke( config_filename=self.file.name) self.assertIsNotNone(instance) self.assertIsNone(retcode) self.assertTrue(cli.TasksPrint.domain_format.called) all_data = [] all_data.extend(data) all_data.extend(more) data_calls = [call(x) for x in all_data] cli.TasksPrint.domain_format.assert_has_calls(data_calls) self.assertTrue(cli.prettify.called) @settings(suppress_health_check=[HealthCheck.too_slow]) @given(test_data()) def test_tasks_change(self, arg): can_overlap, user_tasks, _more_tasks, all_tasks, arguments_strings, task_ids, args = arg op = mock.Mock() log_op = mock.Mock() domain_print = mock.Mock() class TestDomain(cli.TasksChange): domain = 'testdomain' more_tasks = _more_tasks ids_can_overlap = can_overlap def op(tself, tid): op(tid) self.assertIn(tid, tself.changing_tasks) def log_op(tself, tid): log_op(tid) self.assertIn(tid, tself.changing_tasks) def domain_print(tself): domain_print() context = [ patch.object(cli.ConfiguredApplication, 'main', cfg_main), patch('habitipy.cli.prettify', mock.Mock(wraps=cli.prettify, return_value=''))] rsps = responses.RequestsMock() context.extend([rsps, to_devnull()]) with ExitStack() as stack: for cm in context: stack.enter_context(cm) rsps.add( responses.GET, url='https://habitica.com/api/v3/tasks/user?type=testdomain', content_type='application/json', match_querystring=True, json=dict(data=user_tasks)) instance, retcode = TestDomain.invoke( *arguments_strings, config_filename=self.file.name) self.assertIsNotNone(instance) self.assertIsNone(retcode) self.assertTrue(op.called) self.assertTrue(log_op.called) task_id_calls = [call(x) for x in task_ids] op.assert_has_calls(task_id_calls) log_op.assert_has_calls(task_id_calls) self.assertTrue(domain_print.called) domain_print.assert_has_calls([call()]) self.assertTrue(cli.prettify.called)
class TestCli(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_content_cache(self): pass def content_callback(req): pass def test_task_print(self): pass @settings(suppress_health_check=[HealthCheck.too_slow]) @given(test_data()) def test_tasks_change(self, arg): pass class TestDomain(cli.TasksChange): def op(tself, tid): pass def log_op(tself, tid): pass def domain_print(tself): pass
13
0
16
0
15
0
1
0
1
10
5
0
5
1
5
77
138
7
131
42
118
0
84
38
73
2
2
2
13
2,728
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Pets
class Pets(ApplicationWithApi): """Core inheritable class for dealing with actions on pets.""" DESCRIPTION = _('List pets and their status') pet_specifier = cli.SwitchAttr( ['-P', '--pet'], help=_('Only show information about a particular pet')) # noqa: Q000 color_specifier = cli.SwitchAttr( ['-C', '--color'], help=_('Only show information about a particular color')) # noqa: Q000 def get_full_percent(self, amount: int): """Return the percentage of "fullness" for a pet.""" if amount == -1: amount = 100 else: amount *= 2 return str(amount) def get_food_needed(self, pet_fullness: int, amount_per_food: int = 5) -> int: """Return the amount of food needed to feed a pet till full.""" if pet_fullness == -1: return 0 return int((50 - int(pet_fullness)) / amount_per_food) def is_hatchable(self, user: dict, pet: str, color: str) -> bool: """Return true when a pat of a particular type and color can be hatched.""" combined = pet + '-' + color # check if pet exists or name is wrong if user['items']['pets'].get(combined, 100) != -1: return False if color not in user['items']['hatchingPotions'] or pet not in user['items']['eggs']: return False if user['items']['hatchingPotions'][color] > 0 and user['items']['eggs'][pet] > 0: return True return False
class Pets(ApplicationWithApi): '''Core inheritable class for dealing with actions on pets.''' def get_full_percent(self, amount: int): '''Return the percentage of "fullness" for a pet.''' pass def get_food_needed(self, pet_fullness: int, amount_per_food: int = 5) -> int: '''Return the amount of food needed to feed a pet till full.''' pass def is_hatchable(self, user: dict, pet: str, color: str) -> bool: '''Return true when a pat of a particular type and color can be hatched.''' pass
4
4
8
1
6
1
3
0.26
1
4
0
3
3
0
3
5
37
5
27
8
23
7
22
8
18
4
3
1
8
2,729
ASMfreaK/habitipy
ASMfreaK_habitipy/tests/test_utils.py
tests.test_utils.TestFileUtils
class TestFileUtils(unittest.TestCase): def setUp(self): self.filename = 'test.yay' touch(self.filename) def tearDown(self): if os.path.exists(self.filename): os.remove(self.filename) def test_secure_filestore(self): with open(self.filename, 'w') as f: f.write('this is a test') self.assertFalse(is_secure_file(self.filename)) os.remove(self.filename) with secure_filestore(), open(self.filename, 'w') as f: f.write('this is a test') self.assertTrue(is_secure_file(self.filename)) def test_load_conf(self): os.remove(self.filename) with patch('plumbum.cli.terminal.ask', MagicMock(return_value=False)) as m: conf = load_conf(self.filename) self.assertTrue(m.called) self.assertEqual(conf['url'], 'https://habitica.com') self.assertTrue(is_secure_file(self.filename)) os.remove(self.filename) with ExitStack() as s: ask = s.enter_context( patch('plumbum.cli.terminal.ask', MagicMock(return_value=True))) prompt = s.enter_context( patch('plumbum.cli.terminal.prompt', MagicMock(return_value='TEST_DATA'))) conf = load_conf(self.filename) self.assertEqual(ask.call_count, 1) self.assertEqual(prompt.call_count, 2) self.assertEqual(conf['url'], 'https://habitica.com') self.assertEqual(conf['login'], 'TEST_DATA') self.assertEqual(conf['password'], 'TEST_DATA') self.assertTrue(is_secure_file(self.filename)) os.chmod(self.filename, 0o666) with self.assertRaises(SecurityError): conf = load_conf(self.filename)
class TestFileUtils(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_secure_filestore(self): pass def test_load_conf(self): pass
5
0
9
0
9
0
1
0
1
3
1
0
4
1
4
76
41
3
38
12
33
0
36
9
31
2
2
1
5
2,730
ASMfreaK/habitipy
ASMfreaK_habitipy/tests/test_cli.py
tests.test_cli.DevNullLog
class DevNullLog(object): def __getattr__(self, a): if a in dir(super()): return super().__getattr__(a) else: return nop
class DevNullLog(object): def __getattr__(self, a): pass
2
0
5
0
5
0
2
0
1
1
0
0
1
0
1
1
6
0
6
2
4
0
5
2
3
2
1
1
2
2,731
ASMfreaK/habitipy
ASMfreaK_habitipy/tests/test_cli.py
tests.test_cli.DevNull
class DevNull(object): def write(self, what): pass def flush(self): pass
class DevNull(object): def write(self, what): pass def flush(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
2
5
0
5
3
2
0
5
3
2
1
1
0
2
2,732
ASMfreaK/habitipy
ASMfreaK_habitipy/tests/test_api.py
tests.test_api.TestParsedEndpoints
class TestParsedEndpoints(unittest.TestCase): def setUp(self): self.file = tempfile.NamedTemporaryFile(delete=False) self.file.write(test_data.encode('utf-8')) self.file.close() self.ret = parse_apidoc(self.file.name) os.remove(self.file.name) def test_read(self): [self.assertIsInstance(x, ApiEndpoint) for x in self.ret] # pylint: disable=W0106 for expected_values, obj in zip(expected_endpoints, self.ret): for attr, expected in zip(endpoint_attrs, expected_values): self.assertEqual(getattr(obj, attr), expected) def test_retcodes(self): for retcode, obj in zip([201,200,200], self.ret): self.assertEqual(obj.retcode, retcode)
class TestParsedEndpoints(unittest.TestCase): def setUp(self): pass def test_read(self): pass def test_retcodes(self): pass
4
0
5
0
5
0
2
0.07
1
2
1
0
3
2
3
75
17
2
15
9
11
1
15
9
11
3
2
2
6
2,733
ASMfreaK/habitipy
ASMfreaK_habitipy/tests/test_api.py
tests.test_api.TestParse
class TestParse(unittest.TestCase): def setUp(self): self.file = tempfile.NamedTemporaryFile(delete=False) def tearDown(self): os.remove(self.file.name) def test_read(self): self.file.write(test_data.encode('utf-8')) self.file.close() ret = parse_apidoc(self.file.name) self.assertEqual(len(ret), 3) def test_wrong_apidoc0(self): self.file.write(wrong_apidoc_data[0].encode('utf-8')) self.file.close() with self.assertRaises(ValueError): ret = parse_apidoc(self.file.name) def test_wrong_apidoc1(self): self.file.write(wrong_apidoc_data[1].encode('utf-8')) self.file.close() with self.assertRaises(ValueError): ret = parse_apidoc(self.file.name)
class TestParse(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_read(self): pass def test_wrong_apidoc0(self): pass def test_wrong_apidoc1(self): pass
6
0
4
0
4
0
1
0
1
1
0
0
5
1
5
77
24
4
20
10
14
0
20
10
14
1
2
1
5
2,734
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/util.py
habitipy.util.SecurityError
class SecurityError(ValueError): """Error fired when a secure file is stored in an insecure manner"""
class SecurityError(ValueError): '''Error fired when a secure file is stored in an insecure manner''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
2,735
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.TodosUp
class TodosUp(TodosChange): # pylint: disable=missing-class-docstring DESCRIPTION = _("Check a todo with task_id") # noqa: Q000 def op(self, tid): self.tasks[tid].score['up'].post() def log_op(self, tid): return _("Completed todo {text}").format(**self.changing_tasks[tid])
class TodosUp(TodosChange): def op(self, tid): pass def log_op(self, tid): pass
3
0
2
0
2
1
1
0.5
1
0
0
0
2
0
2
10
7
1
6
4
3
3
6
4
3
1
5
0
2
2,736
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.TodosDelete
class TodosDelete(TodosChange): # pylint: disable=missing-class-docstring DESCRIPTION = _("Delete a todo with task_id") # noqa: Q000 def op(self, tid): self.tasks[tid].delete() def log_op(self, tid): return _("Deleted todo {text}").format(**self.changing_tasks[tid])
class TodosDelete(TodosChange): def op(self, tid): pass def log_op(self, tid): pass
3
0
2
0
2
1
1
0.5
1
0
0
0
2
0
2
10
7
1
6
4
3
3
6
4
3
1
5
0
2
2,737
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.TodosChange
class TodosChange(TasksChange): # pylint: disable=missing-class-docstring,abstract-method domain = 'todos' def domain_print(self): ToDos.invoke(config_filename=self.config_filename)
class TodosChange(TasksChange): def domain_print(self): pass
2
0
2
0
2
0
1
0.25
1
1
1
2
1
0
1
8
4
0
4
3
2
1
4
3
2
1
4
0
1
2,738
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.TaskId
class TaskId(List[Union[str, int]]): """ handle task-id formats such as: habitica todos done 3 taskalias_or_uuid habitica todos done 1,2,3,taskalias_or_uuid habitica todos done 2 3 habitica todos done 1-3,4 8 """ def __new__(cls, tids: str): task_ids = [] # type: List[Union[str, int]] for bit in tids.split(','): try: if '-' in bit: start, stop = [int(e) for e in bit.split('-')] task_ids.extend(range(start, stop + 1)) else: task_ids.append(int(bit)) except ValueError: task_ids.append(bit) return [e - 1 if isinstance(e, int) else e for e in task_ids]
class TaskId(List[Union[str, int]]): ''' handle task-id formats such as: habitica todos done 3 taskalias_or_uuid habitica todos done 1,2,3,taskalias_or_uuid habitica todos done 2 3 habitica todos done 1-3,4 8 ''' def __new__(cls, tids: str): pass
2
1
12
0
12
2
5
0.69
1
4
0
0
1
0
1
1
20
0
13
5
11
9
12
5
10
5
1
3
5
2,739
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.ToDos
class ToDos(TasksPrint): # pylint: disable=missing-class-docstring DESCRIPTION = _("List, comlete, add or delete todo tasks") # noqa: Q000 domain = 'todos' def domain_format(self, todo): # pylint: disable=arguments-renamed score = ScoreInfo(self.config['show_style'], todo['value']) check = CHECK if todo['completed'] else UNCHECK check = check[self.config['show_style']] checklist_done = len(list(filter(lambda x: x['completed'], todo['checklist']))) checklist = \ ' {}/{}'.format( checklist_done, len(todo['checklist']) ) if todo['checklist'] else '' res = _("{1}{0}{text}{2}").format(check, score, checklist, **todo) # noqa: Q000 return res
class ToDos(TasksPrint): def domain_format(self, todo): pass
2
0
12
0
12
2
3
0.27
1
3
1
0
1
0
1
5
15
0
15
9
13
4
11
9
9
3
4
0
3
2,740
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Status
class Status(ApplicationWithApi): # pylint: disable=missing-class-docstring DESCRIPTION = _("Show HP, XP, GP, and more") # noqa: Q000 def main(self): super().main() user = self.api.user.get() for key in ['hp', 'mp', 'exp']: user['stats'][key] = round(user['stats'][key]) user['stats']['class'] = _(user['stats']['class']).capitalize() user['food'] = sum(user['items']['food'].values()) content = Content(self.api) user['pet'] = user['items']['currentPet'] if 'currentPet' in user['items'] else None user['pet'] = content['petInfo'][user['pet']]['text'] if user['pet'] else '' user['pet'] = _("Pet: ") + user['pet'] if user['pet'] else _("No pet") # noqa: Q000 user['mount'] = user['items'].get('currentMount', None) user['mount'] = content['mountInfo'][user['mount']]['text'] if user['mount'] else '' if user['mount']: user['mount'] = _("Mount: ") + user['mount'] # noqa: Q000 else: user['mount'] = _("No mount") # noqa: Q000 level = _("\nLevel {stats[lvl]} {stats[class]}\n").format(**user) # noqa: Q000 highlight = '-' * (len(level) - 2) level = highlight + level + highlight result = [ level, colors.red | _("Health: {stats[hp]}/{stats[maxHealth]}"), # noqa: Q000 colors.yellow | _("XP: {stats[exp]}/{stats[toNextLevel]}"), # noqa: Q000 colors.blue | _("Mana: {stats[mp]}/{stats[maxMP]}"), # noqa: Q000 colors.light_yellow | _("GP: {stats[gp]:.2f}"), # noqa: Q000 '{pet} ' + ngettext( "({food} food item)", # noqa: Q000 "({food} food items)", # noqa: Q000 user['food']), '{mount}'] quest = self.quest_info(user) if quest: result.append(quest) print('\n'.join(result).format(**user)) def quest_info(self, user): """Get current quest info or return None""" key = user['party']['quest'].get('key', None) if '_id' not in user['party'] or key is None: return None for refresh in False, True: content = Content(self.api, refresh) quest = content['quests'].get(key, None) if quest: break else: self.log.warning(dedent(_( """Quest {} not found in Habitica's content. Please file an issue to https://github.com/ASMfreaK/habitipy/issues """)).format(key)) return None for quest_type, quest_template in ( ('collect', _(""" Quest: {quest[text]} (collect-type) {user[party][quest][progress][collectedItems]} quest items collected """)), ('boss', _(""" Quest: {quest[text]} (boss) {user[party][quest][progress][up]:.1f} damage will be dealt to {quest[boss][name]} """))): if quest_type in quest: try: return dedent(quest_template.format(quest=quest, user=user))[1:-1] except KeyError: self.log.warning(dedent(_( """Something went wrong when formatting quest {}. Please file an issue to https://github.com/ASMfreaK/habitipy/issues """)).format(key)) return None self.log.warning(dedent(_( """Quest {} isn't neither a collect-type or a boss-type. Please file an issue to https://github.com/ASMfreaK/habitipy/issues """)).format(key))
class Status(ApplicationWithApi): def main(self): pass def quest_info(self, user): '''Get current quest info or return None''' pass
3
1
37
0
36
6
8
0.18
1
3
1
0
2
0
2
4
77
2
74
16
71
13
46
16
43
8
3
3
15
2,741
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Spells
class Spells(ApplicationWithApi): # pylint: disable=missing-class-docstring DESCRIPTION = _("Prints all available spells") # noqa: Q000 def main(self): if self.nested_command: return super().main() user = self.api.user.get() content = Content(self.api) user_level = user['stats']['lvl'] if user_level < 10: print(_("Your level is too low. Come back on level 10 or higher")) # noqa: Q000 user_class = user['stats']['class'] user_spells = [ v for k, v in content['spells'][user_class].items() if user_level > v['lvl'] ] print(_("You are a {} of level {}").format(_(user_class), user_level)) # noqa: Q000 for spell in sorted(user_spells, key=lambda x: x['lvl']): msg = _("[{key}] {text} ({mana}:droplet:) - {notes}").format(**spell) # noqa: Q000 print(msg)
class Spells(ApplicationWithApi): def main(self): pass
2
0
18
0
18
3
4
0.25
1
2
1
0
1
0
1
3
20
0
20
11
18
5
17
10
15
4
3
1
4
2,742
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.Server
class Server(ApplicationWithApi): # pylint: disable=missing-class-docstring DESCRIPTION = _("Check habitica server availability") # noqa: Q000 def main(self): super().main() try: ret = self.api.status.get() if isinstance(ret, dict) and ret['status'] == 'up': print(_("Habitica server {} online").format(self.config['url'])) # noqa: Q000 return 0 except (KeyError, requests.exceptions.ConnectionError): pass msg = _("Habitica server {} offline or there is some issue with it") # noqa: Q000 print(msg.format(self.config['url'])) return -1
class Server(ApplicationWithApi): def main(self): pass
2
0
12
0
12
2
3
0.29
1
3
0
0
1
0
1
3
14
0
14
5
12
4
14
5
12
3
3
2
3
2,743
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.ScoreInfo
class ScoreInfo: """task value/score info: http://habitica.wikia.com/wiki/Task_Value""" scores = { 'wide': ['▁', '▂', '▃', '▄', '▅', '▆', '▇'], 'narrow': ['▁', '▂', '▃', '▄', '▅', '▆', '▇'], 'ascii': ['*', '**', '***', '****', '*****', '******', '*******'] } colors_ = ['Red3', 'Red1', 'DarkOrange', 'Gold3A', 'Green', 'LightCyan3', 'Cyan1'] breakpoints = [-20, -10, -1, 1, 5, 10] def __new__(cls, style, value): index = bisect(cls.breakpoints, value) score = cls.scores[style][index] score_col = colors.fg(cls.colors_[index]) if style == 'ascii': max_scores_len = max(map(len, cls.scores[style])) score = '[' + score.center(max_scores_len) + ']' # score = '⎡' + score.center(cls.max_scores_len) + '⎤' return score_col | score @classmethod def color(cls, value): """task value/score color""" index = bisect(cls.breakpoints, value) return colors.fg(cls.colors_[index])
class ScoreInfo: '''task value/score info: http://habitica.wikia.com/wiki/Task_Value''' def __new__(cls, style, value): pass @classmethod def color(cls, value): '''task value/score color''' pass
4
2
7
0
6
1
2
0.15
0
1
0
0
1
0
2
2
27
4
20
12
16
3
15
11
12
2
0
1
3
2,744
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.TodosAdd
class TodosAdd(ApplicationWithApi): # pylint: disable=missing-class-docstring DESCRIPTION = _("Add a todo <todo>") # noqa: Q000 priority = cli.SwitchAttr( ['-p', '--priority'], cli.Set('0.1', '1', '1.5', '2'), default='1', help=_("Priority (complexity) of a todo")) # noqa: Q000 def main(self, *todo: str): todo_str = ' '.join(todo) if not todo_str: self.log.error(_("Empty todo text!")) # noqa: Q000 return 1 super().main() self.api.tasks.user.post(type='todo', text=todo_str, priority=self.priority) res = _("Added todo '{}' with priority {}").format(todo_str, self.priority) # noqa: Q000 print(prettify(res)) ToDos.invoke(config_filename=self.config_filename) return 0
class TodosAdd(ApplicationWithApi): def main(self, *todo: str): pass
2
0
11
0
11
2
2
0.29
1
3
1
0
1
0
1
3
18
1
17
6
15
5
14
6
12
2
3
1
2
2,745
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.RewardsBuy
class RewardsBuy(TasksChange): # pylint: disable=missing-class-docstring DESCRIPTION = _("Buy a reward with reward_id") # noqa: Q000 domain = 'rewards' ids_can_overlap = True NO_TASK_ID = _("No reward_ids found!") # noqa: Q000 TASK_ID_INVALID = _("Reward id {} is invalid") # noqa: Q000 PARSED_TASK_IDS = _("Parsed reward ids {}") # noqa: Q000 def main(self, *reward_id: RewardId): ApplicationWithApi.main(self) self.more_tasks = get_additional_rewards(self.api) super().main(*reward_id) def op(self, tid): t = self.changing_tasks[tid] if t['type'] != 'rewards': self.api.user.buy[t['key']].post() else: self.tasks[tid].score['up'].post() def log_op(self, tid): return _("Bought reward {text}").format(**self.changing_tasks[tid]) # noqa: Q000 def domain_print(self): Rewards.invoke(config_filename=self.config_filename)
class RewardsBuy(TasksChange): def main(self, *reward_id: RewardId): pass def op(self, tid): pass def log_op(self, tid): pass def domain_print(self): pass
5
0
4
0
4
0
1
0.29
1
2
1
0
4
1
4
11
24
3
21
13
16
6
20
13
15
2
4
1
5
2,746
ASMfreaK/habitipy
ASMfreaK_habitipy/habitipy/cli.py
habitipy.cli.RewardsAdd
class RewardsAdd(ApplicationWithApi): # pylint: disable=missing-class-docstring DESCRIPTION = _("Add a reward <reward>") # noqa: Q000 cost = cli.SwitchAttr( ['--cost'], default='10', help=_("Cost of a reward (gp)")) # noqa: Q000 def main(self, *reward: str): todo_str = ' '.join(reward) if not todo_str: self.log.error(_("Empty reward text!")) # noqa: Q000 return 1 super().main() self.api.tasks.user.post(type='reward', text=todo_str, value=self.cost) res = _("Added reward '{}' with cost {}").format(todo_str, self.cost) # noqa: Q000 print(prettify(res)) Rewards.invoke(config_filename=self.config_filename) return 0
class RewardsAdd(ApplicationWithApi): def main(self, *reward: str): pass
2
0
11
0
11
2
2
0.31
1
3
1
0
1
0
1
3
17
1
16
6
14
5
14
6
12
2
3
1
2
2,747
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.Daytime
class Daytime(Enum): "Время суток" VALUES = ( "d", # светлое время суток "n", # темное время суток )
class Daytime(Enum): '''Время суток''' pass
1
1
0
0
0
0
0
0.6
1
0
0
0
0
0
0
68
6
0
5
2
4
3
2
2
1
0
3
0
0
2,748
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.Condition
class Condition(Enum): "Текущее состояние погоды" VALUES = ( "clear", # ясно "partly-cloudy", # малооблачно "cloudy", # облачно с прояснениями "overcast", # пасмурно "partly-cloudy-and-light-rain", # небольшой дождь "partly-cloudy-and-rain", # дождь "overcast-and-rain", # сильный дождь "overcast-thunderstorms-with-rain", # сильный дождь, гроза "cloudy-and-light-rain", # небольшой дождь "overcast-and-light-rain", # небольшой дождь "cloudy-and-rain", # дождь "overcast-and-wet-snow", # дождь со снегом "partly-cloudy-and-light-snow", # небольшой снег "partly-cloudy-and-snow", # снег "overcast-and-snow", # снегопад "cloudy-and-light-snow", # небольшой снег "overcast-and-light-snow", # небольшой снег "cloudy-and-snow", # снег )
class Condition(Enum): '''Текущее состояние погоды''' pass
1
1
0
0
0
0
0
0.9
1
0
0
0
0
0
0
68
22
0
21
2
20
19
2
2
1
0
3
0
0
2,749
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.BoxWithSchema
class BoxWithSchema(Box): """ Коробка, которая может проверить валидность входных данных на соответсвие схеме SCHEMA, которую должны предоставить потомки """ @classmethod def validate(cls, obj): "Проверяет схему SCHEMA на объекте obj и создаёт коробку" return cls(cls.SCHEMA(obj))
class BoxWithSchema(Box): ''' Коробка, которая может проверить валидность входных данных на соответсвие схеме SCHEMA, которую должны предоставить потомки ''' @classmethod def validate(cls, obj): '''Проверяет схему SCHEMA на объекте obj и создаёт коробку''' pass
3
2
3
0
2
1
1
1.25
1
0
0
7
0
0
1
1
9
0
4
3
1
5
3
2
1
1
1
0
1
2,750
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/__init__.py
yandex_weather_api.Rate
class Rate(Enum): "Тариф доступа. Возможные значения: " VALUES = ( "informers", # тариф «Погода на Вашем сайте» "forecast" # тариф «Тестовый» )
class Rate(Enum): '''Тариф доступа. Возможные значения: ''' pass
1
1
0
0
0
0
0
0.6
1
0
0
0
0
0
0
68
6
0
5
2
4
3
2
2
1
0
3
0
0
2,751
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/cli.py
yandex_weather_api.cli.Weather
class Weather(plumbum.cli.Application): "Интерфейс командной строки для Яндекс.Погоды" def main(self): if not self.nested_command: raise RuntimeError("No command specified")
class Weather(plumbum.cli.Application): '''Интерфейс командной строки для Яндекс.Погоды''' def main(self): pass
2
1
3
0
3
0
2
0.25
1
1
0
0
1
0
1
1
5
0
4
2
2
1
4
2
2
2
1
1
2
2,752
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.Enum
class Enum(str): "Тип-перечисление с валидатором" VALUES = () # type: Tuple[str, ...] @classmethod def validate(cls, cnd): "Проверяет, что переданный объект - один из возможных `VALUES`" if cnd not in cls.VALUES: raise ValueError("Value {} cannot be used in {}".format( cnd, cls )) return cls(cnd) def __repr__(self): return "{}({})".format(self.__class__.__name__, super().__repr__())
class Enum(str): '''Тип-перечисление с валидатором''' @classmethod def validate(cls, cnd): '''Проверяет, что переданный объект - один из возможных `VALUES`''' pass def __repr__(self): pass
4
2
5
0
4
1
2
0.27
1
2
0
8
1
0
2
68
15
2
11
5
7
3
8
4
5
2
2
1
3
2,753
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/__init__.py
yandex_weather_api.Language
class Language(Enum): "Язык ответа" VALUES = ( "ru_RU", # русский язык для домена России "ru_UA", # русский язык для домена Украины "uk_UA", # украинский язык для домена Украины "be_BY", # белорусский язык для домена Беларуси "kk_KZ", # казахский язык для домена Казахстана "tr_TR", # турецкий язык для домена Турции "en_US" # международный английский )
class Language(Enum): '''Язык ответа''' pass
1
1
0
0
0
0
0
0.8
1
0
0
0
0
0
0
68
11
0
10
2
9
8
2
2
1
0
3
0
0
2,754
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/cli.py
yandex_weather_api.cli.WeatherCli
class WeatherCli(plumbum.cli.Application): """ Интерфейс командной строки для Яндекс.Погоды Параметры lat и lon - широта и долгота точки, для которой будет запрошена погода. В среде выполнения должна быть установлена переменная среды YANDEX_API_KEY, содержащая ключ доступа к API. Также можно указать переменную среды YANDEX_WEATHER_RATE=forecast, если вы используете тариф "Тестовый". """ def main(self, lat, lon): # pylint: disable=invalid-name api_key = os.environ.get("YANDEX_API_KEY") rate = os.environ.get("YANDEX_WEATHER_RATE", "informers") w = get(requests, api_key, rate=rate, lat=lat, lon=lon, limit=2) pprint(w) temp = green | (str(w.fact.temp) + '°C') print(dedent(f""" Температура { temp } (ощущается как {w.fact.feels_like}°C) За окном - {w.fact.condition} Ветер {w.fact.wind_dir} {w.fact.wind_speed} м/с Давление {w.fact.pressure_mm} мм.рт.ст. {w.fact.icon.as_url()} {w.info.url} """).strip())
class WeatherCli(plumbum.cli.Application): ''' Интерфейс командной строки для Яндекс.Погоды Параметры lat и lon - широта и долгота точки, для которой будет запрошена погода. В среде выполнения должна быть установлена переменная среды YANDEX_API_KEY, содержащая ключ доступа к API. Также можно указать переменную среды YANDEX_WEATHER_RATE=forecast, если вы используете тариф "Тестовый". ''' def main(self, lat, lon): pass
2
1
15
0
14
1
1
0.67
1
1
0
0
1
0
1
1
26
1
15
6
13
10
8
6
6
1
1
0
1
2,755
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.FacticalWeatherInfo
class FacticalWeatherInfo(BoxWithSchema): """ Объект fact Объект содержит информацию о погоде на данный момент. """ SCHEMA = vol.Schema({ # Температура (°C). Число vol.Required("temp"): number, # Ощущаемая температура (°C). Число vol.Required("feels_like"): number, # Температура воды (°C). # Параметр возвращается для населенных пунктов, # где данная информация актуальна. Число vol.Optional("temp_water"): number, # Код иконки погоды. Иконка доступна по адресу # https://yastatic.net/weather/i/icons/blueye/color/svg/ # <значение из поля icon>.svg. Строка vol.Required("icon"): Icon.validate, # Код расшифровки погодного описания. Возможные значения: vol.Required("condition"): Condition.validate, # Скорость ветра (в м/с). Число vol.Required("wind_speed"): number, # Скорость порывов ветра (в м/с). Число vol.Required("wind_gust"): number, # Направление ветра. Возможные значения: vol.Required("wind_dir"): WindDir.validate, # Давление (в мм рт. ст.). Число vol.Required("pressure_mm"): number, # Давление (в гектопаскалях). Число vol.Required("pressure_pa"): number, # Влажность воздуха (в процентах). Число vol.Required("humidity"): number, # Светлое или темное время суток. Возможные значения: vol.Required("daytime"): Daytime.validate, # Признак полярного дня или ночи. Логический vol.Required("polar"): bool, # Время года в данном населенном пункте. Возможные значения: vol.Required("season"): Season.validate, # Время замера погодных данных в формате Unixtime. Число vol.Required("obs_time"): number, # Тип осадков. Возможные значения: Число # 0 — без осадков. # 1 — дождь. # 2 — дождь со снегом. # 3 — снег. vol.Optional("prec_type"): number, # Сила осадков. Возможные значения: Число # 0 — без осадков. # 0.25 — слабый дождь/слабый снег. # 0.5 — дождь/снег. # 0.75 — сильный дождь/сильный снег. # 1 — сильный ливень/очень сильный снег. vol.Optional("prec_strength"): number, # Облачность. Возможные значения: Число # 0 — ясно. # 0.25 — малооблачно. # 0.5 — облачно с прояснениями. # 0.75 — облачно с прояснениями. # 1 — пасмурно. vol.Optional("cloudness"): number, }, extra=vol.ALLOW_EXTRA)
class FacticalWeatherInfo(BoxWithSchema): ''' Объект fact Объект содержит информацию о погоде на данный момент. ''' pass
1
1
0
0
0
0
0
1.9
1
0
0
0
0
0
0
1
62
1
21
2
20
40
2
2
1
0
2
0
0
2,756
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.Forecast
class Forecast(BoxWithSchema): """ Объект forecast Объект содержит данные прогноза погоды при использовании тарифа "Для сайтов". Переформирует данные в соответсвии с тарифом "Тестовый" """ SCHEMA = BASE_FORECAST_SCHEMA.extend({ # Прогнозы по времени суток. Содержит следующие поля: Объект vol.Required("parts"): [ForecastPart.validate] }) @classmethod def validate(cls, obj): ret = super().validate(obj) parts = {} for part in ret.parts: parts[part.part_name] = part ret.parts = Box(parts) return ret
class Forecast(BoxWithSchema): ''' Объект forecast Объект содержит данные прогноза погоды при использовании тарифа "Для сайтов". Переформирует данные в соответсвии с тарифом "Тестовый" ''' @classmethod def validate(cls, obj): pass
3
1
7
0
7
0
2
0.5
1
1
0
0
0
0
1
2
21
3
12
7
9
6
9
6
7
2
2
1
2
2,757
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.TZInfo
class TZInfo(BoxWithSchema): "Информация о часовом поясе. Содержит поля offset, name, abbr и dst." SCHEMA = vol.Schema({ # Часовой пояс в секундах от UTC. Число vol.Optional("offset"): number, # Название часового пояса. Строка vol.Optional("name"): str, # Сокращенное название часового пояса. Строка vol.Optional("abbr"): str, # Признак летнего времени. Логический vol.Optional("dst"): bool })
class TZInfo(BoxWithSchema): '''Информация о часовом поясе. Содержит поля offset, name, abbr и dst.''' pass
1
1
0
0
0
0
0
0.71
1
0
0
0
0
0
0
1
12
0
7
2
6
5
2
2
1
0
2
0
0
2,758
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.Forecasts
class Forecasts(BoxWithSchema): """ Объект forecast Объект содержит данные прогноза погоды для тарифа "Тестовый" """ SCHEMA = BASE_FORECAST_SCHEMA.extend({ # Прогнозы по времени суток. Содержит следующие поля: Объект vol.Required("parts"): { vol.Required(key): ForecastPart.validate for key in PartName.VALUES }, })
class Forecasts(BoxWithSchema): ''' Объект forecast Объект содержит данные прогноза погоды для тарифа "Тестовый" ''' pass
1
1
0
0
0
0
0
0.83
1
0
0
0
0
0
0
1
12
1
6
2
5
5
2
2
1
0
2
0
0
2,759
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.Icon
class Icon(str): """ Код иконки погоды. Иконка доступна по адресу https://yastatic.net/weather/i/icons/blueye/color/svg/ <значение из поля icon>.svg. Строка """ URL_FORMAT = "https://yastatic.net/weather/i/icons/blueye/color/svg/{}.svg" @classmethod def validate(cls, cnd): "Проверяет правильность данного объекта" return cls(cnd) def as_url(self): "Выдаёт ссылку на значок погоды" return self.URL_FORMAT.format(self)
class Icon(str): ''' Код иконки погоды. Иконка доступна по адресу https://yastatic.net/weather/i/icons/blueye/color/svg/ <значение из поля icon>.svg. Строка ''' @classmethod def validate(cls, cnd): '''Проверяет правильность данного объекта''' pass def as_url(self): '''Выдаёт ссылку на значок погоды''' pass
4
3
3
0
2
1
1
1
1
0
0
0
1
0
2
68
15
1
7
5
3
7
6
4
3
1
2
0
2
2,760
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.Info
class Info(BoxWithSchema): """ Объект info Объект содержит информацию о населенном пункте. """ SCHEMA = vol.Schema({ # Широта (в градусах). Число vol.Required("lat"): number, # Долгота (в градусах). Число vol.Required("lon"): number, # Идентификатор населенного пункта. Число vol.Optional("geoid"): number, # URL-путь на странице https://yandex.TLD/pogoda/. Строка vol.Optional("slug"): str, # Информация о часовом поясе. Содержит поля offset, name, abbr и dst. vol.Optional("tzinfo"): TZInfo.validate, # Норма давления для данной координаты (в мм рт. ст.). Число vol.Optional("def_pressure_mm"): number, # Норма давления для данной координаты (в гектопаскалях). Число vol.Optional("def_pressure_pa"): number, # Страница населенного пункта на сайте Яндекс.Погода. Строка vol.Required("url"): str }, extra=vol.ALLOW_EXTRA)
class Info(BoxWithSchema): ''' Объект info Объект содержит информацию о населенном пункте. ''' pass
1
1
0
0
0
0
0
1.09
1
0
0
0
0
0
0
1
25
2
11
2
10
12
2
2
1
0
2
0
0
2,761
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.MoonText
class MoonText(Enum): "Код фазы Луны. Возможные значения:" VALUES = ( "full-moon", # полнолуние "decreasing-moon", # убывающая Луна "last-quarter", # последняя четверть "new-moon", # новолуние "growing-moon", # растущая Луна "first-quarter", # первая четверть )
class MoonText(Enum): '''Код фазы Луны. Возможные значения:''' pass
1
1
0
0
0
0
0
0.78
1
0
0
0
0
0
0
68
10
0
9
2
8
7
2
2
1
0
3
0
0
2,762
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.PartName
class PartName(Enum): "Название времени суток. Возможные значения:" VALUES = ( "night", # ночь "morning", # утро "day", # день "evening", # вечер )
class PartName(Enum): '''Название времени суток. Возможные значения:''' pass
1
1
0
0
0
0
0
0.71
1
0
0
0
0
0
0
68
8
0
7
2
6
5
2
2
1
0
3
0
0
2,763
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.Season
class Season(Enum): "Время года" VALUES = ( "summer", # лето "autumn", # осень "winter", # зима "spring" # весна )
class Season(Enum): '''Время года''' pass
1
1
0
0
0
0
0
0.71
1
0
0
0
0
0
0
68
8
0
7
2
6
5
2
2
1
0
3
0
0
2,764
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.ForecastPart
class ForecastPart(BoxWithSchema): """ Все прогнозы погоды на время суток имеют одинаковый набор полей. Ответ содержит прогноз на 2 ближайших периода. """ SCHEMA = vol.Schema({ # Название времени суток. Возможные значения: Строка vol.Optional("part_name"): PartName.validate, # Минимальная температура для времени суток (°C). Число vol.Required("temp_min"): number, # Максимальная температура для времени суток (°C). Число vol.Required("temp_max"): number, # Средняя температура для времени суток (°C). Число vol.Required("temp_avg"): number, # Ощущаемая температура (°C). Число vol.Required("feels_like"): number, # Код иконки погоды. Иконка доступна по адресу # https://yastatic.net/weather/i/icons/blueye/color/svg/ # <значение из поля icon>.svg. Строка vol.Required("icon"): Icon.validate, # Код расшифровки погодного описания. Возможные значения: Строка vol.Required("condition"): Condition.validate, # Светлое или темное время суток. Возможные значения: Строка vol.Required("daytime"): Daytime.validate, # Признак полярного дня или ночи. Логический vol.Required("polar"): bool, # Скорость ветра (в м/с). Число vol.Required("wind_speed"): number, # Скорость порывов ветра (в м/с). Число vol.Required("wind_gust"): number, # Направление ветра. Возможные значения: Строка vol.Required("wind_dir"): WindDir.validate, # Давление (в мм рт. ст.). Число vol.Required("pressure_mm"): number, # Давление (в гектопаскалях). Число vol.Required("pressure_pa"): number, # Влажность воздуха (в процентах). Число vol.Required("humidity"): number, # Прогнозируемое количество осадков (в мм). Число vol.Required("prec_mm"): number, # Прогнозируемый период осадков (в минутах). Число vol.Required("prec_period"): number, # Вероятность выпадения осадков. Число vol.Required("prec_prob"): number, }, extra=vol.ALLOW_EXTRA)
class ForecastPart(BoxWithSchema): ''' Все прогнозы погоды на время суток имеют одинаковый набор полей. Ответ содержит прогноз на 2 ближайших периода. ''' pass
1
1
0
0
0
0
0
1.14
1
0
0
0
0
0
0
1
46
1
21
2
20
24
2
2
1
0
2
0
0
2,765
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.WeatherAnswer
class WeatherAnswer(BoxWithSchema): """ Ответ для тарифа «Погода на вашем сайте» Ответ на запрос `Фактическое значение и прогноз погоды` возвращается в формате JSON. Информация в ответе содержит: """ SCHEMA = vol.Schema({ # Время сервера в формате Unixtime. Числ vol.Required("now"): number, # Время сервера в UTC. Строка vol.Optional("now_dt"): str, # Объект информации о населенном пункте. Объект vol.Required("info"): Info.validate, # Объект фактической информации о погоде. Объект vol.Required("fact"): FacticalWeatherInfo.validate, # Объект прогнозной информации о погоде. Объект vol.Exclusive("forecast", "forecast"): ensure_list_of(Forecast.validate), vol.Exclusive("forecasts", "forecast"): [Forecasts.validate] }, extra=vol.ALLOW_EXTRA) @classmethod def validate(cls, obj): ret = super().validate(obj) if "forecasts" in ret: ret.forecast = ret.forecasts else: ret.forecasts = ret.forecast return ret
class WeatherAnswer(BoxWithSchema): ''' Ответ для тарифа «Погода на вашем сайте» Ответ на запрос `Фактическое значение и прогноз погоды` возвращается в формате JSON. Информация в ответе содержит: ''' @classmethod def validate(cls, obj): pass
3
1
7
0
7
0
2
0.56
1
1
0
0
0
0
1
2
30
2
18
5
15
10
8
4
6
2
2
1
2
2,766
ASMfreaK/yandex_weather_api
ASMfreaK_yandex_weather_api/yandex_weather_api/types.py
yandex_weather_api.types.WindDir
class WindDir(Enum): "Направление ветра" VALUES = ( "nw", # северо-западное "n", # северное "ne", # северо-восточное "e", # восточное "se", # юго-восточное "s", # южное "sw", # юго-западное "w", # западное "c" # штиль )
class WindDir(Enum): '''Направление ветра''' pass
1
1
0
0
0
0
0
0.83
1
0
0
0
0
0
0
68
13
0
12
2
11
10
2
2
1
0
3
0
0
2,767
ASMfreaK/yandex_weather_api
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ASMfreaK_yandex_weather_api/yandex_weather_api/cli.py
yandex_weather_api.cli.WeatherWeb
class WeatherWeb(plumbum.cli.Application): """ Интерфейс командной строки для Яндекс.Погоды Запускает asyncio сервер на HTTP порте `port`, предоставляющий json-ответ прогноза по точке lat и lon (широта и долгота). В среде выполнения должна быть установлена переменная YANDEX_API_KEY, содержащая ключ доступа к API. Также можно указать переменную среды YANDEX_WEATHER_RATE=forecast, если вы используете тариф "Тестовый". """ def main(self, lat, lon, port=8000): api_key = os.environ.get("YANDEX_API_KEY") rate = os.environ.get("YANDEX_WEATHER_RATE", "informers") from aiohttp import web routes = web.RouteTableDef() @routes.get('/') async def weather(request): # pylint: disable=unused-variable return web.json_response( await async_get( request.app["client_session"], api_key, rate=rate, lat=lat, lon=lon ) ) app = web.Application() app.add_routes(routes) setup_client(app) web.run_app(app, port=port)
class WeatherWeb(plumbum.cli.Application): ''' Интерфейс командной строки для Яндекс.Погоды Запускает asyncio сервер на HTTP порте `port`, предоставляющий json-ответ прогноза по точке lat и lon (широта и долгота). В среде выполнения должна быть установлена переменная YANDEX_API_KEY, содержащая ключ доступа к API. Также можно указать переменную среды YANDEX_WEATHER_RATE=forecast, если вы используете тариф "Тестовый". ''' def main(self, lat, lon, port=8000): pass @routes.get('/') async def weather(request): pass
4
1
13
1
12
1
1
0.56
1
0
0
0
1
0
1
1
30
3
18
9
13
10
12
8
8
1
1
0
2
2,768
AWegnerGitHub/smokeapi
AWegnerGitHub_smokeapi/smokeapi/smokeapi.py
smokeapi.smokeapi.SmokeAPIError
class SmokeAPIError(Exception): """ The Exception that is thrown when ever there is an API error. :param url: (string) The URL that was called and generated an error :param code: (int) The `error_code` returned by the API :param name: (string) The `error_name` returned by the API and is human friendly :param message: (string) The `error_message` returned by the API """ def __init__(self, url, code, name, message): self.url = url self.error_name = name self.error_code = code self.error_message = message
class SmokeAPIError(Exception): ''' The Exception that is thrown when ever there is an API error. :param url: (string) The URL that was called and generated an error :param code: (int) The `error_code` returned by the API :param name: (string) The `error_name` returned by the API and is human friendly :param message: (string) The `error_message` returned by the API ''' def __init__(self, url, code, name, message): pass
2
1
5
0
5
0
1
1.17
1
0
0
0
1
4
1
11
15
2
6
6
4
7
6
6
4
1
3
0
1
2,769
AWegnerGitHub/smokeapi
AWegnerGitHub_smokeapi/smokeapi/smokeapi.py
smokeapi.smokeapi.SmokeAPI
class SmokeAPI(object): def __init__(self, key=None, **kwargs): """ The object used to interact with the MetaSmoke API :param key: (string) **(Required)** A valid API key. An API key can be received by following the current instructions in the `API Documentation <https://github.com/Charcoal-SE/metasmoke/wiki/API-Documentation>`__. :param token: (string) **(Required for write access/Optional is no write routes are called)** This is a valid write token retreived by following instructions in the `API Documentation <https://github.com/Charcoal-SE/metasmoke/wiki/API-Documentation>`__. If this is not set, calls to `send_data` will fail. :param proxy: (dict) (optional) A dictionary of http and https proxy locations Example: .. code-block:: python {'http': 'http://example.com', 'https': 'https://example.com'} By default, this is ``None``. :param max_pages: (int) (optional) The maximum number of pages to retrieve (Default: ``5``) :param per_page: (int) (optional) The number of elements per page. The API limits this to a maximum of 100 items on all end points (Default: ``100``) """ if not key: raise ValueError('No API Key provided. This is required for all MetaSmoke API routes.') self.proxy = kwargs.get('proxy', None) self.max_pages = kwargs.get('max_pages', 5) self.per_page = kwargs.get('per_page', 100) self._api_key = key self.token = kwargs.get('token', None) self._endpoint = None self._previous_call = None self._base_url = 'https://metasmoke.erwaysoftware.com/api/' def __repr__(self): return "<SmokeAPI> endpoint: {} Last URL: {}".format(self._endpoint, self._previous_call) def fetch(self, endpoint=None, page=1, **kwargs): """Returns the results of an API call. This is the main work horse of the class. It builds the API query string and sends the request to MetaSmoke. If there are multiple pages of results, and we've configured `max_pages` to be greater than 1, it will automatically paginate through the results and return a single object. Returned data will appear in the `items` key of the resulting dictionary. :param endpoint: (string) The API end point being called. Available endpoints are listed on the official `API Documentation <https://github.com/Charcoal-SE/metasmoke/wiki/API-Documentation>`__. This can be as simple as ``fetch('posts/feedback')``, to call feedback end point If calling an end point that takes additional parameter, such as `id`s pass the ids as a list to the `ids` key: .. code-block:: python fetch('posts/{ids}', ids=[1,2,3]) This will attempt to retrieve the posts for the three listed ids. If no end point is passed, a ``ValueError`` will be raised :param page: (int) The page in the results to start at. By default, it will start on the first page and automatically paginate until the result set reaches ``max_pages``. :param kwargs: Parameters accepted by individual endpoints. These parameters **must** be named the same as described in the endpoint documentation :rtype: (dictionary) A dictionary containing wrapper data regarding the API call and the results of the call in the `items` key. If multiple pages were received, all of the results will appear in the ``items`` tag. """ if not endpoint: raise ValueError('No endpoint provided.') self._endpoint = endpoint params = {"per_page": self.per_page, "page": page, "key": self._api_key } # This block will replace {ids} placeholds in end points # converting .fetch('posts/{ids}', ids=[222, 1306, 99999]) to # posts/222;1306;99999 for k, value in kwargs.items(): if "{" + k + "}" in endpoint: endpoint = endpoint.replace("{" + k + "}", ';'.join(str(x) for x in value)) kwargs.pop(k, None) date_time_keys = ['from_date', 'to_date'] for k in date_time_keys: if k in kwargs: if isinstance(kwargs[k], datetime.datetime): kwargs[k] = int(calendar.timegm(kwargs[k].utctimetuple())) # This block will see if there there are ids remaining # This would occur if the developer passed `posts` instead of `posts/{ids}` to `fetch` # If this is the case, then convert to a string and assume this goes at the end of the endpoint if 'ids' in kwargs: ids = ';'.join(str(x) for x in kwargs['ids']) kwargs.pop('ids', None) endpoint += "/{}".format(ids) params.update(kwargs) data = [] run_cnt = 1 while run_cnt <= self.max_pages: run_cnt += 1 base_url = "{}{}/".format(self._base_url, endpoint) try: response = requests.get(base_url, params=params, proxies=self.proxy) except requests.exceptions.ConnectionError as e: raise SmokeAPIError(self._previous_call, str(e), str(e), str(e)) self._previous_call = response.url try: response.encoding = 'utf-8-sig' response = response.json() except ValueError as e: raise SmokeAPIError(self._previous_call, str(e), str(e), str(e)) try: code = response["error_code"] name = response["error_name"] message = response["error_message"] raise SmokeAPIError(self._previous_call, code, name, message) except KeyError: pass # This means there is no error data.append(response) if len(data) < 1: break if 'has_more' in response and response['has_more']: params["page"] += 1 else: break r = [] for d in data: r.extend(d['items']) items = list(chain(r)) has_more = data[-1]['has_more'] if 'has_more' in data[-1] else False result = {'has_more': has_more, 'page': params['page'], 'total': len(items), 'items': items} return result def send_data(self, endpoint=None, **kwargs): """Sends data to the API. This call is similar to ``fetch``, but **sends** data to the API instead of retrieving it. Returned data will appear in the ``items`` key of the resulting dictionary. Sending data **requires** that the ``token`` is set. :param endpoint: (string) **(Required)** The API end point being called. Available endpoints are listed on the official `API Documentation <https://github.com/Charcoal-SE/metasmoke/wiki/API-Documentation>`__. If no end point is passed, a ``ValueError`` will be raised :param kwargs: Parameters accepted by individual endpoints. These parameters **must** be named the same as described in the endpoint documentation :rtype: (dictionary) A dictionary containing wrapper data regarding the API call and the results of the call in the `items` key. If multiple pages were received, all of the results will appear in the ``items`` tag. """ if not endpoint: raise ValueError('No end point provided.') if not self.token: raise ValueError('A write token has not been set. This is required for all MetaSmoke API routes. This can\n' 'be set by setting the "token" parameter of your SmokeAPI object.') self._endpoint = endpoint params = { "key": self._api_key, "token": self.token } if 'ids' in kwargs: ids = ';'.join(str(x) for x in kwargs['ids']) kwargs.pop('ids', None) else: ids = None params.update(kwargs) data = [] base_url = "{}{}/".format(self._base_url, endpoint) response = requests.post(base_url, data=params, proxies=self.proxy) self._previous_call = response.url response = response.json() try: code = response["error_code"] name = response["error_name"] message = response["error_message"] raise SmokeAPIError(self._previous_call, code, name, message) except KeyError: pass # This means there is no error data.append(response) r = [] for d in data: r.extend(d['items']) items = list(chain(r)) result = {'has_more': data[-1]['has_more'], 'page': params['page'], 'total': len(items), 'items': items} return result
class SmokeAPI(object): def __init__(self, key=None, **kwargs): ''' The object used to interact with the MetaSmoke API :param key: (string) **(Required)** A valid API key. An API key can be received by following the current instructions in the `API Documentation <https://github.com/Charcoal-SE/metasmoke/wiki/API-Documentation>`__. :param token: (string) **(Required for write access/Optional is no write routes are called)** This is a valid write token retreived by following instructions in the `API Documentation <https://github.com/Charcoal-SE/metasmoke/wiki/API-Documentation>`__. If this is not set, calls to `send_data` will fail. :param proxy: (dict) (optional) A dictionary of http and https proxy locations Example: .. code-block:: python {'http': 'http://example.com', 'https': 'https://example.com'} By default, this is ``None``. :param max_pages: (int) (optional) The maximum number of pages to retrieve (Default: ``5``) :param per_page: (int) (optional) The number of elements per page. The API limits this to a maximum of 100 items on all end points (Default: ``100``) ''' pass def __repr__(self): pass def fetch(self, endpoint=None, page=1, **kwargs): '''Returns the results of an API call. This is the main work horse of the class. It builds the API query string and sends the request to MetaSmoke. If there are multiple pages of results, and we've configured `max_pages` to be greater than 1, it will automatically paginate through the results and return a single object. Returned data will appear in the `items` key of the resulting dictionary. :param endpoint: (string) The API end point being called. Available endpoints are listed on the official `API Documentation <https://github.com/Charcoal-SE/metasmoke/wiki/API-Documentation>`__. This can be as simple as ``fetch('posts/feedback')``, to call feedback end point If calling an end point that takes additional parameter, such as `id`s pass the ids as a list to the `ids` key: .. code-block:: python fetch('posts/{ids}', ids=[1,2,3]) This will attempt to retrieve the posts for the three listed ids. If no end point is passed, a ``ValueError`` will be raised :param page: (int) The page in the results to start at. By default, it will start on the first page and automatically paginate until the result set reaches ``max_pages``. :param kwargs: Parameters accepted by individual endpoints. These parameters **must** be named the same as described in the endpoint documentation :rtype: (dictionary) A dictionary containing wrapper data regarding the API call and the results of the call in the `items` key. If multiple pages were received, all of the results will appear in the ``items`` tag. ''' pass def send_data(self, endpoint=None, **kwargs): '''Sends data to the API. This call is similar to ``fetch``, but **sends** data to the API instead of retrieving it. Returned data will appear in the ``items`` key of the resulting dictionary. Sending data **requires** that the ``token`` is set. :param endpoint: (string) **(Required)** The API end point being called. Available endpoints are listed on the official `API Documentation <https://github.com/Charcoal-SE/metasmoke/wiki/API-Documentation>`__. If no end point is passed, a ``ValueError`` will be raised :param kwargs: Parameters accepted by individual endpoints. These parameters **must** be named the same as described in the endpoint documentation :rtype: (dictionary) A dictionary containing wrapper data regarding the API call and the results of the call in the `items` key. If multiple pages were received, all of the results will appear in the ``items`` tag. ''' pass
5
3
57
12
28
17
6
0.6
1
8
1
0
4
8
4
4
232
52
114
42
109
68
99
41
94
16
1
3
25
2,770
AWegnerGitHub/stackapi
AWegnerGitHub_stackapi/stackapi/stackapi.py
stackapi.stackapi.StackAPI
class StackAPI(object): def __init__(self, name=None, version="2.3", base_url="https://api.stackexchange.com", **kwargs): """ The object used to interact with the Stack Exchange API :param name: (string) A valid ``api_site_parameter`` or ``None``. (available from http://api.stackexchange.com/docs/sites) which will be used to connect to a particular site on the Stack Exchange Network. :param version: (float) **(Required)** The version of the API you are connecting to. The default of ``2.3`` is the current version :param base_url: (string) (optional) The base URL for the Stack Exchange API. The default is https://api.stackexchange.com :param proxy: (dict) (optional) A dictionary of http and https proxy locations Example: .. code-block:: python {'http': 'http://example.com', 'https': 'https://example.com'} By default, this is ``None``. :param max_pages: (int) (optional) The maximum number of pages to retrieve (Default: ``100``) :param page_size: (int) (optional) The number of elements per page. The API limits this to a maximum of 100 items on all end points except ``site`` :param key: (string) (optional) An API key :param access_token: (string) (optional) An access token associated with an application and a user, to grant more permissions (such as write access) """ self.proxy = kwargs.get("proxy", None) self.max_pages = kwargs.get("max_pages", 5) self.page_size = kwargs.get("page_size", 100) self.key = kwargs.get("key", None) self.access_token = kwargs.get("access_token", None) self._endpoint = None self._api_key = None self._name = None self._version = version self._previous_call = None self._base_url = "{}/{}/".format(base_url, version) sites = self.fetch("sites", filter="!*L1*AY-85YllAr2)", pagesize=1000) for s in sites["items"]: if name == s["api_site_parameter"]: self._name = s["name"] self._api_key = s["api_site_parameter"] break else: # If ``name`` is not a valid ``api_site_parameter`` # or ``None``. if name is not None: raise ValueError("Invalid Site Name provided") def __repr__(self): return "<{}> v:<{}> endpoint: {} Last URL: {}".format( self._name, self._version, self._endpoint, self._previous_call ) def fetch(self, endpoint=None, page=1, key=None, filter="default", **kwargs): """Returns the results of an API call. This is the main work horse of the class. It builds the API query string and sends the request to Stack Exchange. If there are multiple pages of results, and we've configured `max_pages` to be greater than 1, it will automatically paginate through the results and return a single object. Returned data will appear in the `items` key of the resulting dictionary. :param endpoint: (string) The API end point being called. Available endpoints are listed on the official API documentation: http://api.stackexchange.com/docs This can be as simple as ``fetch('answers')``, to call the answers end point If calling an end point that takes additional parameter, such as `id`s pass the ids as a list to the `ids` key: .. code-block:: python fetch('answers/{}', ids=[1,2,3]) This will attempt to retrieve the answers for the three listed ids. If no end point is passed, a ``ValueError`` will be raised :param page: (int) The page in the results to start at. By default, it will start on the first page and automatically paginate until the result set reached ``max_pages``. :param key: (string) The site you are issuing queries to. :param filter: (string) The filter to utilize when calling an endpoint. Different filters will return different keys. The default is ``default`` and this will still vary depending on what the API returns as default for a particular endpoint :param kwargs: Parameters accepted by individual endpoints. These parameters **must** be named the same as described in the endpoint documentation :rtype: (dictionary) A dictionary containing wrapper data regarding the API call and the results of the call in the `items` key. If multiple pages were received, all of the results will appear in the ``items`` tag. """ if not endpoint: raise ValueError("No end point provided.") self._endpoint = endpoint params = {"pagesize": self.page_size, "page": page, "filter": filter} if self.key: params["key"] = self.key if self.access_token: params["access_token"] = self.access_token # This block will replace {ids} placeholds in end points # converting .fetch('badges/{ids}', ids=[222, 1306, 99999]) to # badges/222;1306;99999 for k, value in list(kwargs.items()): if "{" + k + "}" in endpoint: # using six for backwards compatibility if isinstance(value, six.string_types): endpoint = endpoint.replace("{" + k + "}", requests.compat.quote_plus(str(value))) else: # check if value is iterable, based on # https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable # notice that a string is also an iterable, that's why it's checked first try: iterator = iter(value) endpoint = endpoint.replace( "{" + k + "}", ";".join(requests.compat.quote_plus(str(x)) for x in iterator) ) except TypeError: # it's not an iterable, represent as string endpoint = endpoint.replace("{" + k + "}", requests.compat.quote_plus(str(value))) kwargs.pop(k, None) date_time_keys = ["fromdate", "todate", "since", "min", "max"] for k in date_time_keys: if k in kwargs: if isinstance(kwargs[k], datetime.datetime): kwargs[k] = int(calendar.timegm(kwargs[k].utctimetuple())) # This block will see if there there are ids remaining # This would occur if the developer passed `badges` instead of `badges/{ids}` to `fetch` # If this is the case, then convert to a string and assume this goes at the end of the endpoint if "ids" in kwargs: ids = ";".join(str(x) for x in kwargs["ids"]) kwargs.pop("ids", None) endpoint += "/{}".format(ids) params.update(kwargs) if self._api_key: params["site"] = self._api_key data = [] run_cnt = 1 backoff = 0 total = 0 while run_cnt <= self.max_pages: run_cnt += 1 base_url = "{}{}/".format(self._base_url, endpoint) try: response = requests.get(base_url, params=params, proxies=self.proxy) except requests.exceptions.ConnectionError as e: raise StackAPIError(self._previous_call, str(e), str(e), str(e)) self._previous_call = response.url try: response.encoding = "utf-8-sig" response = response.json() except ValueError as e: raise StackAPIError(self._previous_call, str(e), str(e), str(e)) try: error = response["error_id"] code = response["error_name"] message = response["error_message"] raise StackAPIError(self._previous_call, error, code, message) except KeyError: pass # This means there is no error if key: data.append(response[key]) else: data.append(response) if len(data) < 1: break backoff = 0 total = 0 page = 1 if "backoff" in response: backoff = int(response["backoff"]) sleep(backoff + 1) # Sleep an extra second to ensure no timing issues if "total" in response: total = response["total"] if "has_more" in response and response["has_more"] and run_cnt <= self.max_pages: params["page"] += 1 else: break r = [] for d in data: if "items" in d: r.extend(d["items"]) result = { "backoff": backoff, "has_more": False if "has_more" not in data[-1] else data[-1]["has_more"], "page": params["page"], "quota_max": -1 if "quota_max" not in data[-1] else data[-1]["quota_max"], "quota_remaining": -1 if "quota_remaining" not in data[-1] else data[-1]["quota_remaining"], "total": total, "items": list(chain(r)), } return result def send_data(self, endpoint=None, page=1, key=None, filter="default", **kwargs): """Sends data to the API. This call is similar to ``fetch``, but **sends** data to the API instead of retrieving it. Returned data will appear in the ``items`` key of the resulting dictionary. Sending data **requires** that the ``access_token`` is set. This is enforced on the API side, not within this library. :param endpoint: (string) The API end point being called. Available endpoints are listed on the official API documentation: http://api.stackexchange.com/docs This can be as simple as ``fetch('answers')``, to call the answers end point If calling an end point that takes additional parameter, such as `id`s pass the ids as a list to the `ids` key: .. code-block:: python fetch('answers/{}', ids=[1,2,3]) This will attempt to retrieve the answers for the three listed ids. If no end point is passed, a ``ValueError`` will be raised :param page: (int) The page in the results to start at. By default, it will start on the first page and automatically paginate until the result set reached ``max_pages``. :param key: (string) The site you are issuing queries to. :param filter: (string) The filter to utilize when calling an endpoint. Different filters will return different keys. The default is ``default`` and this will still vary depending on what the API returns as default for a particular endpoint :param kwargs: Parameters accepted by individual endpoints. These parameters **must** be named the same as described in the endpoint documentation :rtype: (dictionary) A dictionary containing wrapper data regarding the API call and the results of the call in the `items` key. If multiple pages were received, all of the results will appear in the ``items`` tag. """ if not endpoint: raise ValueError("No end point provided.") self._endpoint = endpoint params = {"pagesize": self.page_size, "page": page, "filter": filter} if self.key: params["key"] = self.key if self.access_token: params["access_token"] = self.access_token if "ids" in kwargs: ids = ";".join(str(x) for x in kwargs["ids"]) kwargs.pop("ids", None) else: ids = None params.update(kwargs) if self._api_key: params["site"] = self._api_key data = [] base_url = "{}{}/".format(self._base_url, endpoint) response = requests.post(base_url, data=params, proxies=self.proxy) self._previous_call = response.url response = response.json() try: error = response["error_id"] code = response["error_name"] message = response["error_message"] raise StackAPIError(self._previous_call, error, code, message) except KeyError: pass # This means there is no error data.append(response) r = [] for d in data: r.extend(d["items"]) result = { "has_more": data[-1]["has_more"], "page": params["page"], "quota_max": data[-1]["quota_max"], "quota_remaining": data[-1]["quota_remaining"], "items": list(chain(r)), } return result
class StackAPI(object): def __init__(self, name=None, version="2.3", base_url="https://api.stackexchange.com", **kwargs): ''' The object used to interact with the Stack Exchange API :param name: (string) A valid ``api_site_parameter`` or ``None``. (available from http://api.stackexchange.com/docs/sites) which will be used to connect to a particular site on the Stack Exchange Network. :param version: (float) **(Required)** The version of the API you are connecting to. The default of ``2.3`` is the current version :param base_url: (string) (optional) The base URL for the Stack Exchange API. The default is https://api.stackexchange.com :param proxy: (dict) (optional) A dictionary of http and https proxy locations Example: .. code-block:: python {'http': 'http://example.com', 'https': 'https://example.com'} By default, this is ``None``. :param max_pages: (int) (optional) The maximum number of pages to retrieve (Default: ``100``) :param page_size: (int) (optional) The number of elements per page. The API limits this to a maximum of 100 items on all end points except ``site`` :param key: (string) (optional) An API key :param access_token: (string) (optional) An access token associated with an application and a user, to grant more permissions (such as write access) ''' pass def __repr__(self): pass def fetch(self, endpoint=None, page=1, key=None, filter="default", **kwargs): '''Returns the results of an API call. This is the main work horse of the class. It builds the API query string and sends the request to Stack Exchange. If there are multiple pages of results, and we've configured `max_pages` to be greater than 1, it will automatically paginate through the results and return a single object. Returned data will appear in the `items` key of the resulting dictionary. :param endpoint: (string) The API end point being called. Available endpoints are listed on the official API documentation: http://api.stackexchange.com/docs This can be as simple as ``fetch('answers')``, to call the answers end point If calling an end point that takes additional parameter, such as `id`s pass the ids as a list to the `ids` key: .. code-block:: python fetch('answers/{}', ids=[1,2,3]) This will attempt to retrieve the answers for the three listed ids. If no end point is passed, a ``ValueError`` will be raised :param page: (int) The page in the results to start at. By default, it will start on the first page and automatically paginate until the result set reached ``max_pages``. :param key: (string) The site you are issuing queries to. :param filter: (string) The filter to utilize when calling an endpoint. Different filters will return different keys. The default is ``default`` and this will still vary depending on what the API returns as default for a particular endpoint :param kwargs: Parameters accepted by individual endpoints. These parameters **must** be named the same as described in the endpoint documentation :rtype: (dictionary) A dictionary containing wrapper data regarding the API call and the results of the call in the `items` key. If multiple pages were received, all of the results will appear in the ``items`` tag. ''' pass def send_data(self, endpoint=None, page=1, key=None, filter="default", **kwargs): '''Sends data to the API. This call is similar to ``fetch``, but **sends** data to the API instead of retrieving it. Returned data will appear in the ``items`` key of the resulting dictionary. Sending data **requires** that the ``access_token`` is set. This is enforced on the API side, not within this library. :param endpoint: (string) The API end point being called. Available endpoints are listed on the official API documentation: http://api.stackexchange.com/docs This can be as simple as ``fetch('answers')``, to call the answers end point If calling an end point that takes additional parameter, such as `id`s pass the ids as a list to the `ids` key: .. code-block:: python fetch('answers/{}', ids=[1,2,3]) This will attempt to retrieve the answers for the three listed ids. If no end point is passed, a ``ValueError`` will be raised :param page: (int) The page in the results to start at. By default, it will start on the first page and automatically paginate until the result set reached ``max_pages``. :param key: (string) The site you are issuing queries to. :param filter: (string) The filter to utilize when calling an endpoint. Different filters will return different keys. The default is ``default`` and this will still vary depending on what the API returns as default for a particular endpoint :param kwargs: Parameters accepted by individual endpoints. These parameters **must** be named the same as described in the endpoint documentation :rtype: (dictionary) A dictionary containing wrapper data regarding the API call and the results of the call in the `items` key. If multiple pages were received, all of the results will appear in the ``items`` tag. ''' pass
5
3
78
14
39
26
10
0.66
1
9
1
0
4
11
4
4
316
58
157
47
152
104
135
46
130
27
1
4
40
2,771
AWegnerGitHub/stackapi
AWegnerGitHub_stackapi/stackapi/stackapi.py
stackapi.stackapi.StackAPIError
class StackAPIError(Exception): """ The Exception that is thrown when ever there is an API error. This utilizes the values returned by the API and described here: http://api.stackexchange.com/docs/types/error :param url: (string) The URL that was called and generated an error :param error: (int) The `error_id` returned by the API (should be an int) :param code: (string) The `description` returned by the API and is human friendly :param message: (string) The `error_name` returned by the API """ def __init__(self, url, error, code, message): self.url = url self.error = error self.code = code self.message = message
class StackAPIError(Exception): ''' The Exception that is thrown when ever there is an API error. This utilizes the values returned by the API and described here: http://api.stackexchange.com/docs/types/error :param url: (string) The URL that was called and generated an error :param error: (int) The `error_id` returned by the API (should be an int) :param code: (string) The `description` returned by the API and is human friendly :param message: (string) The `error_name` returned by the API ''' def __init__(self, url, error, code, message): pass
2
1
5
0
5
0
1
1.5
1
0
0
0
1
4
1
11
18
3
6
6
4
9
6
6
4
1
3
0
1
2,772
AWegnerGitHub/stackapi
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AWegnerGitHub_stackapi/tests/test_stackapi.py
tests.test_stackapi.Test_StackAPI
class Test_StackAPI(unittest.TestCase): def test_no_site_provided(self): """Testing that it excludes the `site` when no site is provided.""" site = StackAPI() self.assertEqual(first=site._base_url, second="https://api.stackexchange.com/2.3/") def test_no_endpoint_provided(self): """Testing that it raises the correct error when no endpoint is provided""" with self.assertRaises(ValueError) as cm: with patch( "stackapi.StackAPI.fetch", fake_stackoverflow_exists ) as mock_site: site = StackAPI("stackoverflow") site.fetch() self.assertEqual("No end point provided.", str(cm.exception)) @patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) def test_stackoverflow_exists(self): """Simply testing the object is created correctly""" self.assertEqual(StackAPI("stackoverflow")._name, "Stack Overflow") @patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) def test_asdfghjkl_not_exist(self): """Testing that it raises the correct error on unknown site""" with self.assertRaises(ValueError) as cm: site = StackAPI("asdfghjkl") self.assertEqual("Invalid Site Name provided", str(cm.exception)) def test_nonsite_parameter(self): """Testing that it can retrieve data on end points that don't want the `site` parameter. Tested using Jeff Atwood's user id""" with patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) as mock_site: site = StackAPI() with patch("stackapi.StackAPI.fetch", fake_users) as mock_users: results = site.fetch("/users/1/associated") self.assertGreaterEqual(len(results["items"]), 1) def test_exceptions_thrown(self): """Testing that a StackAPIError is properly thrown This test hits the real API.""" with self.assertRaises(StackAPIError) as cm: site = StackAPI("stackoverflow") site.fetch("errors/400") self.assertEqual(cm.exception.error, 400) self.assertEqual(cm.exception.code, "bad_parameter") @patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) def test_default_base_url(self): """Testing that the base_url uses the default value""" self.assertEqual( StackAPI( "stackoverflow")._base_url, "https://api.stackexchange.com/2.3/" ) @patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) def test_override_base_url(self): """Testing that the base_url can be overridden""" self.assertEqual( StackAPI( name="stackoverflow", version="2.2", base_url="https://mystacksite.com/api", key="foo", )._base_url, "https://mystacksite.com/api/2.2/", )
class Test_StackAPI(unittest.TestCase): def test_no_site_provided(self): '''Testing that it excludes the `site` when no site is provided.''' pass def test_no_endpoint_provided(self): '''Testing that it raises the correct error when no endpoint is provided''' pass @patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) def test_stackoverflow_exists(self): '''Simply testing the object is created correctly''' pass @patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) def test_asdfghjkl_not_exist(self): '''Testing that it raises the correct error on unknown site''' pass def test_nonsite_parameter(self): '''Testing that it can retrieve data on end points that don't want the `site` parameter. Tested using Jeff Atwood's user id''' pass def test_exceptions_thrown(self): '''Testing that a StackAPIError is properly thrown This test hits the real API.''' pass @patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) def test_default_base_url(self): '''Testing that the base_url uses the default value''' pass @patch("stackapi.StackAPI.fetch", fake_stackoverflow_exists) def test_override_base_url(self): '''Testing that the base_url can be overridden''' pass
13
8
7
0
5
1
1
0.21
1
4
2
0
8
0
8
80
67
9
48
25
35
10
32
15
23
1
2
2
8
2,773
AaronWatters/jp_proxy_widget
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AaronWatters_jp_proxy_widget/tests/test_proxy_widget.py
test_proxy_widget.TestProxyWidget
class TestProxyWidget(unittest.TestCase): def test_path(self): # smoke test L = jp_proxy_widget._jupyter_nbextension_paths() self.assertEqual(type(L[0]), dict) def test_create(self): widget = jp_proxy_widget.JSProxyWidget() self.assertEqual(type(widget), jp_proxy_widget.JSProxyWidget) def test_set_element(self): "is this method used?" name = "name" value = "value" widget = proxy_widget.JSProxyWidget() m = widget.js_init = MagicMock(return_value=3) widget.set_element(name, value) m.assert_called_with( "element[slot_name] = value;", slot_name=name, value=value) def test_get_value_async_smoke_test(self): "real test is in end_to_end_testing" js = "1 + 1" widget = proxy_widget.JSProxyWidget() m = widget.js_init = MagicMock(return_value=3) callback = None # never called in smoke test widget.get_value_async(callback, js, debug=True) assert m.called @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.__call__") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.flush") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.uses_require") def test_js_init_smoke_test(self, mock1, mock2, mock3): for r in (True, False): widget = proxy_widget.JSProxyWidget() widget._needs_requirejs = r def f_callable(x): return x + 3 widget.js_init( "console.log('not really executed')", num=3.14, dicitonary=dict(hello="a greeting", oof="an interjection"), L=[2, 3, 5, 7, 11], f=f_callable ) assert mock1.called assert mock2.called assert mock3.called @patch("jp_proxy_widget.proxy_widget.print") def test_handle_error_msg(self, m): widget = proxy_widget.JSProxyWidget() widget.handle_error_msg("att", "old", "new") assert m.called # @patch("proxy_widget.JSProxyWidget.send_commands") def test_handle_rendered(self): widget = proxy_widget.JSProxyWidget() # widget.commands_awaiting_render = ["bogus"] widget.buffered_commands = ["bogus"] m = widget.send_commands = MagicMock() # widget.handle_rendered("att", "old", "new") widget.rendered = True assert m.called self.assertEqual(widget.status, "Rendered.") # @patch("proxy_widget.JSProxyWidget.send_commands") def test_handle_rendered_error(self): widget = proxy_widget.JSProxyWidget() widget.buffered_commands = ["bogus"] m = widget.send_commands = MagicMock(side_effect=KeyError('foo')) with self.assertRaises(KeyError): # widget.handle_rendered("att", "old", "new") widget.rendered = True assert m.called # self.assertEqual(widget.status, "Rendered.") def test_send_custom_message(self): widget = proxy_widget.JSProxyWidget() m = widget.send = MagicMock() widget.send_custom_message("indicator", "payload") assert m.called def test_handle_custom_message_wrapper(self): widget = proxy_widget.JSProxyWidget() widget.output = None m = widget.handle_custom_message = MagicMock() widget.handle_custom_message_wrapper(None, None, None) assert m.called def test_handle_custom_message_redir(self): widget = proxy_widget.JSProxyWidget() class mgr: def __init__(self): self.entered = self.exitted = False def __enter__(self): self.entered = True def __exit__(self, *args): self.exitted = True c = widget.output = mgr() m = widget.handle_custom_message = MagicMock() widget.handle_custom_message_wrapper(None, None, None) assert m.called assert c.entered assert c.exitted @patch("jp_proxy_widget.proxy_widget.widgets.Output") @patch("jp_proxy_widget.proxy_widget.widgets.Text") @patch("jp_proxy_widget.proxy_widget.widgets.VBox") @patch("jp_proxy_widget.traitlets.directional_link") @patch("jp_proxy_widget.print") def test_debugging_display(self, *mocks): for tagline in ("", "hello"): for border in ("", "1px"): widget = proxy_widget.JSProxyWidget() widget.debugging_display(tagline, border) # for (i, mock) in enumerate(mocks): # assert mock.called, "not called: " + repr(i) @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.handle_results") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.handle_callback_results") def test_handle_custom_message(self, *mocks): i = proxy_widget.INDICATOR p = proxy_widget.PAYLOAD data_list = [ {i: proxy_widget.RESULTS, p: "bogus payload"}, {i: proxy_widget.CALLBACK_RESULTS, p: "bogus payload"}, {i: proxy_widget.JSON_CB_FINAL, p: "[1,2,3]"}, {i: proxy_widget.JSON_CB_FRAGMENT, p: "bogus payload"}, {i: "unknown indicator", p: "bogus payload"}, ] for data in data_list: widget = proxy_widget.JSProxyWidget() widget.handle_custom_message(None, data) def test_handle_custom_message_error(self, *mocks): i = proxy_widget.INDICATOR p = proxy_widget.PAYLOAD data = {i: proxy_widget.RESULTS, p: "bogus payload"} widget = proxy_widget.JSProxyWidget() m = widget.handle_results = MagicMock(side_effect=KeyError('foo')) with self.assertRaises(KeyError): widget.handle_custom_message(None, data) def test_uid(self): widget = proxy_widget.JSProxyWidget() u1 = widget.unique_id() u2 = widget.unique_id() assert u1 != u2 def test_widget_call(self): widget = proxy_widget.JSProxyWidget() m = widget.flush = MagicMock() widget.send_commands = MagicMock() widget.auto_flush = True widget("console.log('not executed')") assert m.called def test_seg_flush(self): widget = proxy_widget.JSProxyWidget() m = widget.flush = MagicMock() widget.seg_flush(None, None, None) assert m.called def test_flush(self): widget = proxy_widget.JSProxyWidget() m = widget.send_commands = MagicMock() widget.flush() assert not m.called widget.rendered = True widget.flush() assert m.called widget.error_on_flush = True with self.assertRaises(ValueError): widget.flush() def test_delay_flush(self): widget = proxy_widget.JSProxyWidget() m = widget.send_commands = MagicMock() widget.rendered = True widget.flush() assert m.called m = widget.send_commands = MagicMock() with widget.delay_flush(): widget.element.do_something_in_javascript() assert not m.called assert len(widget.buffered_commands) > 0 assert m.called assert len(widget.buffered_commands) == 0 @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.__call__") def test_save(self, mc): class dummy_elt: def _set(self, name, ref): setattr(self, name, ref) widget = proxy_widget.JSProxyWidget() widget.send_commands = MagicMock() e = dummy_elt() m = widget.get_element = MagicMock(return_value=e) v = "the value" k = "apples" x = widget.save(k, v) # self.assertEqual(e.apples, v) # self.assertEqual(e.apples, x) assert m.called @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_css") def test_check_jquery(self, *mocks): on_success = MagicMock() widget = proxy_widget.JSProxyWidget() widget.check_jquery(on_success, force=True) assert on_success.called @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_already_loaded(self, *mocks): widget = proxy_widget.JSProxyWidget() e = widget.element = RequireMockElement() e.require_is_loaded = True proxy_widget.JSProxyWidget._require_checked = True action = MagicMock() widget.uses_require(action) assert action.called @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_wont_load(self, *mocks): widget = proxy_widget.JSProxyWidget() e = widget.element = RequireMockElement() e.require_is_loaded = False proxy_widget.JSProxyWidget._require_checked = True action = MagicMock() with self.assertRaises(ImportError): widget.uses_require(action) assert not action.called @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_loads(self, *mocks): widget = proxy_widget.JSProxyWidget() e = widget.element = RequireMockElement() e.require_is_loaded = False proxy_widget.JSProxyWidget._require_checked = False action = MagicMock() widget.uses_require(action) assert action.called @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_loads_action_fails(self, *mocks): widget = proxy_widget.JSProxyWidget() e = widget.element = RequireMockElement() e.require_is_loaded = False proxy_widget.JSProxyWidget._require_checked = False action = MagicMock(side_effect=KeyError('foo')) # with self.assertRaises(KeyError): widget.error_msg = "" widget.uses_require(action) assert action.called assert widget.error_msg.startswith( "require.js delayed action exception") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_loads_delayed(self, *mocks): widget = proxy_widget.JSProxyWidget() e = widget.element = RequireMockElement() e.require_is_loaded = False e.when_loaded_delayed = True proxy_widget.JSProxyWidget._require_checked = False action1 = MagicMock() action2 = MagicMock() widget.uses_require(action1) widget.uses_require(action2) assert not action1.called assert not action2.called e.load_completed() assert action1.called assert action2.called @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_css_text") def test_load_css(self, *mocks): widget = proxy_widget.JSProxyWidget() widget.load_css("js/simple.css") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.__call__") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_css_command") def test_load_css_text(self, *mocks): widget = proxy_widget.JSProxyWidget() widget.load_css_text("js/simple.css", "fake content") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_module_text") def test_require_js(self, *mocks): widget = proxy_widget.JSProxyWidget() def uses_require(action): action() widget.uses_require = uses_require widget.require_js("js/simple.css", "js/simple.css") def test_load_js_module_text(self, *mocks): widget = proxy_widget.JSProxyWidget() m = widget.element._load_js_module = MagicMock() widget.load_js_module_text("name", "text") assert m.called def test_save_new(self, *mocks): widget = proxy_widget.JSProxyWidget() # m = widget.element.New = MagicMock() m2 = widget.save = MagicMock() widget.save_new("name", "constructor", [1, 2, 3]) # assert m.called assert m2.called def test_save_function(self): widget = proxy_widget.JSProxyWidget() m = widget.save_new = MagicMock() class fakeWindow: Function = None m2 = widget.window = MagicMock(return_value=fakeWindow) widget.save_function("name", ("a", "b"), "return a+b") assert m.called assert m2.called @patch("jp_proxy_widget.proxy_widget.print") def test_handle_results(self, *args): widget = proxy_widget.JSProxyWidget() widget.verbose = True idnt = 1 cb = MagicMock() i2c = widget.identifier_to_callback = {idnt: cb} v = "the value" new_results = [idnt, v] widget.handle_results(new_results) assert cb.called assert len(i2c) == 0 @patch("jp_proxy_widget.proxy_widget.print") def test_handle_results_error(self, *args): widget = proxy_widget.JSProxyWidget() widget.verbose = True idnt = 1 cb = MagicMock(side_effect=KeyError('foo')) i2c = widget.identifier_to_callback = {idnt: cb} v = "the value" new_results = [idnt, v] with self.assertRaises(KeyError): widget.handle_results(new_results) assert cb.called assert len(i2c) == 0 @patch("jp_proxy_widget.proxy_widget.print") def test_callback_results(self, *args): widget = proxy_widget.JSProxyWidget() widget.verbose = True new_results = [1, 2, [3], 4] [identifier, json_value, arguments, counter] = new_results cb = MagicMock() i2c = widget.identifier_to_callback = {identifier: cb} widget.handle_callback_results(new_results) assert cb.called assert len(i2c) == 1 @patch("jp_proxy_widget.proxy_widget.print") def test_callback_results_error(self, *args): widget = proxy_widget.JSProxyWidget() widget.verbose = True new_results = [1, 2, [3], 4] [identifier, json_value, arguments, counter] = new_results cb = MagicMock(side_effect=KeyError('foo')) i2c = widget.identifier_to_callback = {identifier: cb} with self.assertRaises(KeyError): widget.handle_callback_results(new_results) assert cb.called assert len(i2c) == 1 assert widget.error_msg.startswith("Handle callback results") def test_send_command_before_render(self, *args): widget = proxy_widget.JSProxyWidget() widget.rendered = False command = [1, 2, 3] cb = MagicMock() before = len(widget.buffered_commands) widget.send_command(command, cb) assert not cb.called assert len(widget.buffered_commands) == before + 1 return widget def test_send_command_after_rendered(self, *args): widget = self.test_send_command_before_render() widget.rendered = True command = [2, 3, 4] cb = MagicMock() s = widget.send_custom_message = MagicMock() widget.send_command(command, cb) assert not widget.buffered_commands assert not cb.called assert s.called def test_send_command_segmented(self, *args): widget = self.test_send_command_before_render() widget.rendered = True command = [2, 3, 4] cb = MagicMock() s = widget.send_segmented_message = MagicMock() widget.send_commands([command], cb, segmented=1000) assert not widget.buffered_commands assert not cb.called assert s.called def test_send_segmented_message(self, *args): payload = list(range(1000)) widget = proxy_widget.JSProxyWidget() s = widget.send_custom_message = MagicMock() widget.send_segmented_message("frag", "final", payload, 100) assert s.called """ def test_evaluate(self, *args): payload = list(range(1000)) widget = proxy_widget.JSProxyWidget() e = widget.evaluate_commands = MagicMock(return_value=[123]) x = widget.evaluate(payload) assert e.called assert x == 123 @patch("jp_proxy_widget.proxy_widget.ip") def test_evaluate_commands(self, *args): commands = list(range(100)) results_in = [33] widget = proxy_widget.JSProxyWidget() #s = widget.send_commands = MagicMock() callback = [None] test = MagicMock() def send_commands(iter, cb, lvl): callback[0] = cb widget.send_commands = send_commands def do_one_iteration(): callback[0](results_in) test() proxy_widget.ip = MagicMock() proxy_widget.ip.kernel = MagicMock() proxy_widget.ip.kernel.do_one_iteration = do_one_iteration values = widget.evaluate_commands(commands) assert test.called self.assertEqual(results_in, values)""" # @patch("jp_proxy_widget.proxy_widget.ip") def test_evaluate_commands_timeout(self, *args): commands = list(range(100)) results_in = [33] widget = proxy_widget.JSProxyWidget() # s = widget.send_commands = MagicMock() callback = [None] test = MagicMock() def send_commands(iter, cb, lvl): callback[0] = cb widget.send_commands = send_commands def do_one_iteration(): callback[0](results_in) test() # proxy_widget.ip = MagicMock() # proxy_widget.ip.kernel = MagicMock() # proxy_widget.ip.kernel.do_one_iteration = do_one_iteration with self.assertRaises(Exception): values = widget.evaluate_commands(commands, timeout=-1) def test_seg_callback(self, *args): widget = proxy_widget.JSProxyWidget() def f(*args): return args data = (1, 2, 3) widget.seg_callback(f, data) def test_callable(self, *args): widget = proxy_widget.JSProxyWidget() def f(*args): # print("got args: " + repr(args)) return args c = widget.callable(f) c2 = widget.callable(c) assert c is c2 assert type(c) is jp_proxy_widget.CallMaker # call the callback identifier = c.args[0] callback = widget.identifier_to_callback[identifier] callback("dummy", {"0": "the first argument"}) # self.assertEqual(c.args[1], 1) # (count, data, level, segmented) = c.args def test_forget_callable(self, *args): widget = proxy_widget.JSProxyWidget() widget.identifier_to_callback = {1: list, 2: dict} widget.forget_callback(list) self.assertEqual(list(widget.identifier_to_callback.keys()), [2]) def test_js_debug(self, *args): widget = proxy_widget.JSProxyWidget() widget.get_element = MagicMock() widget.send_command = MagicMock() widget.js_debug() @patch("jp_proxy_widget.proxy_widget.print") def test_print_status(self, p): widget = proxy_widget.JSProxyWidget() widget.print_status() assert p.called def test_load_js_files(self, *args): widget = proxy_widget.JSProxyWidget() def mock_callable(c): return c widget.callable = mock_callable def mock_test_js_loaded(paths, dummy, callback): callback() widget.element.test_js_loaded = mock_test_js_loaded widget.send_command = MagicMock() widget.load_js_files(["js/simple.js"], force=False) widget.load_js_files(["js/simple.js"], force=True) def test_load_css_command(self, *args): widget = proxy_widget.JSProxyWidget() widget.load_css_command( "dummy.css", "this is not really css text content") def test_validate_commands(self, *args): call_args = [ ["element"], ["window"], ] [numerical_identifier, untranslated_data, level, segmented] = [123, "whatever", 2, 10000] commands = call_args + [ ["method", ["element"], "method_name"] + call_args, ["function", ["element"]] + call_args, ["id", "untranslated"], ["bytes", u"12ff"], ["list"] + call_args, ["dict", {"key": ["element"]}], ["callback", numerical_identifier, untranslated_data, level, segmented], ["get", ["element"], "whatever"], ["set", ["element"], "whatever", ["window"]], ["null", ["element"]], dict, ] widget = proxy_widget.JSProxyWidget() widget.validate_commands(commands) with self.assertRaises(ValueError): widget.validate_commands([["BAD_INDICATOR", "OTHER", "STUFF"]]) with self.assertRaises(ValueError): widget.validate_command( "TOP LEVEL COMMAND MUST BE A LIST", top=True) def test_indent(self, *args): indented = proxy_widget.indent_string("a\nx", level=3, indent=" ") self.assertEquals("a\n x", indented) def test_to_javascript(self, *args): thing = [ {"a": proxy_widget.CommandMaker("window")}, "a string", ["a string in a list"], bytearray(b"a byte array"), ] js = proxy_widget.to_javascript(thing) def test_element_wrapper(self, *args): widget = proxy_widget.JSProxyWidget() element = MagicMock() widget.get_element = MagicMock(returns=element) element._set = MagicMock() wrapper = proxy_widget.ElementWrapper(widget) get_attribute = wrapper.some_attribute set_attribute = wrapper._set("some_attribute", "some value") assert widget.get_element.called def test_command_maker(self, *args): m = proxy_widget.CommandMaker("window") exercised_methods = [ repr(m), m.javascript(), m._cmd(), m.some_attribute, m._set("an_attribute", "some_value"), m._null(), ] self.assertEquals(len(exercised_methods), 6) with self.assertRaises(ValueError): m("Cannot call a top level command maker") def test_call_maker(self, *args): for kind in ["function", "method", "unknown"]: c = proxy_widget.CallMaker( kind, proxy_widget.CommandMaker("window"), "arg2") exercised = [ c.javascript(), c("call returned value"), c._cmd() ] self.assertEquals(len(exercised), 3) def test_method_maker(self, *args): c = proxy_widget.MethodMaker( proxy_widget.CommandMaker("window"), "method_name") exercised = [ c.javascript(), c("call the method"), c._cmd() ] self.assertEquals(len(exercised), 3) def test_literal_maker(self, *args): for thing in (["a", "list"], {"a": "dictionary"}, bytearray(b"a bytearray")): c = proxy_widget.LiteralMaker(thing) exercised = [ c.javascript(), c._cmd() ] self.assertEquals(len(exercised), 2) with self.assertRaises(ValueError): c = proxy_widget.LiteralMaker( proxy_widget) # can't translate a module c._cmd() def test_set_maker(self, *args): c = proxy_widget.SetMaker(proxy_widget.CommandMaker( "window"), "some_attribute", "some_value") exercised = [ c.javascript(), c._cmd() ] self.assertEquals(len(exercised), 2) def test_loader(self, *args): indicator = proxy_widget.LOAD_INDICATORS[0] c = proxy_widget.Loader(indicator, "bogus_name", "bogus content") exercised = [ c._cmd() ] self.assertEquals(len(exercised), 1) with self.assertRaises(NotImplementedError): test = c.javascript() def test_debug_check_commands(self, *args): cmds = [ None, 123, 123.4, "a string", ("a", "tuple"), {"a": "dict"}, ["another", "list"], True, False, ] test = proxy_widget.debug_check_commands(cmds) with self.assertRaises(proxy_widget.InvalidCommand): proxy_widget.debug_check_commands([proxy_widget]) def test_wrap_callables(self, *args): widget = proxy_widget.JSProxyWidget() binary = bytearray(b"\x12\xff binary bytes") string_value = "just a string" int_value = -123 float_value = 45.6 json_dictionary = {"keys": None, "must": 321, "be": [ 6, 12], "strings": "values", "can": ["be", "any json"]} list_value = [9, string_value, json_dictionary] all = [binary, string_value, int_value, float_value, json_dictionary, list_value] for unwrapped in all + [all]: wrapped = widget.wrap_callables(unwrapped) self.assertEqual(wrapped, unwrapped) def test_cmd_str(self, *args): s = "a string" L = proxy_widget.LiteralMaker(s) self.assertEqual(L._cmd(), s) def test_lazy_get(self, *args): widget = proxy_widget.JSProxyWidget() get = widget.element["AnyAttribute"] method_call = get("called") self.assertIsInstance(method_call, proxy_widget.LazyMethodCall) call_attribute = method_call["someOtherAttribute"] self.assertIsInstance(call_attribute, proxy_widget.LazyGet) # exercise the repr method self.assertIsInstance(repr(call_attribute), str) def test_clean_dict(self, *args): import numpy as np A = np.array([1.1, 2.2], dtype=np.float32) a1 = A[1] assert type(a1) is not float D = proxy_widget.clean_dict( tuple=(1, 2, 3), array=A, np_float=a1, missing=None) self.assertEqual( D, dict(tuple=[1, 2, 3], array=A.tolist(), np_float=float(a1))) self.assertEqual(type(D["np_float"]), float) @patch("jp_proxy_widget.proxy_widget.run_ui_poll_loop") def test_evaluate_success(self, *args): widget = proxy_widget.JSProxyWidget() def fake_poll(*args): widget._synced_command_evaluated = True widget._synced_command_result = 42 proxy_widget.run_ui_poll_loop = fake_poll get_value = widget.element["AnyAttribute"].sync_value(ms_delay=10) self.assertEqual(get_value, 42) @patch("jp_proxy_widget.proxy_widget.run_ui_poll_loop") def test_evaluate_exception(self, *args): widget = proxy_widget.JSProxyWidget() def fake_poll(*args): widget._synced_command_evaluated = True widget._synced_command_result = "SOMETHING WENT WRONG" widget.error_msg = "SOMETHING WENT WRONG" proxy_widget.run_ui_poll_loop = fake_poll with self.assertRaises(proxy_widget.JavascriptException): get_value = widget.element["AnyAttribute"].sync_value(ms_delay=10) def test_on_rendered(self, *args): widget = proxy_widget.JSProxyWidget() def fake_js_init(js, call_it): call_it() widget.js_init = fake_js_init m = MagicMock() widget.on_rendered(m, "some", "arguments") assert m.called def test_in_dialog(self, *args): widget = proxy_widget.JSProxyWidget() m = MagicMock() widget.element.dialog = m widget.in_dialog( title="A Counter", autoOpen=False, buttons=dict(Increment=MagicMock()), height=150, width=600, modal=True, show=dict(effect="blind", duration=1000), hide=dict(effect="fade", duration=1000), ) assert m.called def test_quote_numpy_array(self, *args): import numpy as np a = np.array([1, 2, 3], dtype=np.int) q = proxy_widget.quoteIfNeeded(a) c = q._cmd() c2 = proxy_widget.quoteIfNeeded([1, 2, 3])._cmd() self.assertEqual(c, c2) def test_quote_numpy_array_in_dict(self, *args): import numpy as np widget = proxy_widget.JSProxyWidget() a = {"array": np.array([1, 2, 3], dtype=np.int), "string": "whatever"} b = {"array": [1, 2, 3], "string": "whatever"} ca = widget.validate_command(proxy_widget.quoteIfNeeded(a)) cb = widget.validate_command(proxy_widget.quoteIfNeeded(b)) self.assertEqual(ca, cb) def test_quote_numpy_array_elt(self, *args): import numpy as np a = np.array([1, 2, 3], dtype=np.int) a1 = a[1] # numpy int b1 = 2 # standard int self.assertNotEqual(type(a1), type(b1)) q = proxy_widget.quoteIfNeeded(a1) self.assertEqual(type(q), type(b1)) self.assertEqual(q, b1)
class TestProxyWidget(unittest.TestCase): def test_path(self): pass def test_create(self): pass def test_set_element(self): '''is this method used?''' pass def test_get_value_async_smoke_test(self): '''real test is in end_to_end_testing''' pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.__call__") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.flush") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.uses_require") def test_js_init_smoke_test(self, mock1, mock2, mock3): pass def f_callable(x): pass @patch("jp_proxy_widget.proxy_widget.print") def test_handle_error_msg(self, m): pass def test_handle_rendered(self): pass def test_handle_rendered_error(self): pass def test_send_custom_message(self): pass def test_handle_custom_message_wrapper(self): pass def test_handle_custom_message_redir(self): pass class mgr: def __init__(self): pass def __enter__(self): pass def __exit__(self, *args): pass @patch("jp_proxy_widget.proxy_widget.widgets.Output") @patch("jp_proxy_widget.proxy_widget.widgets.Text") @patch("jp_proxy_widget.proxy_widget.widgets.VBox") @patch("jp_proxy_widget.traitlets.directional_link") @patch("jp_proxy_widget.print") def test_debugging_display(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.handle_results") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.handle_callback_results") def test_handle_custom_message_wrapper(self): pass def test_handle_custom_message_error(self, *mocks): pass def test_uid(self): pass def test_widget_call(self): pass def test_seg_flush(self): pass def test_flush(self): pass def test_delay_flush(self): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.__call__") def test_save(self, mc): pass class dummy_elt: def _set(self, name, ref): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_css") def test_check_jquery(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_already_loaded(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_wont_load(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_loads(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_loads_action_fails(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_files") def test_require_loads_delayed(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_css_text") def test_load_css(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.__call__") @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_css_command") def test_load_css_text(self, *mocks): pass @patch("jp_proxy_widget.proxy_widget.JSProxyWidget.load_js_module_text") def test_require_js(self, *mocks): pass def uses_require(action): pass def test_load_js_module_text(self, *mocks): pass def test_save_new(self, *mocks): pass def test_save_function(self): pass class fakeWindow: @patch("jp_proxy_widget.proxy_widget.print") def test_handle_results(self, *args): pass @patch("jp_proxy_widget.proxy_widget.print") def test_handle_results_error(self, *args): pass @patch("jp_proxy_widget.proxy_widget.print") def test_callback_results(self, *args): pass @patch("jp_proxy_widget.proxy_widget.print") def test_callback_results_error(self, *args): pass def test_send_command_before_render(self, *args): pass def test_send_command_after_rendered(self, *args): pass def test_send_command_segmented(self, *args): pass def test_send_segmented_message(self, *args): pass def test_evaluate_commands_timeout(self, *args): pass def send_commands(iter, cb, lvl): pass def do_one_iteration(): pass def test_seg_callback(self, *args): pass def f_callable(x): pass def test_callable(self, *args): pass def f_callable(x): pass def test_forget_callable(self, *args): pass def test_js_debug(self, *args): pass @patch("jp_proxy_widget.proxy_widget.print") def test_print_status(self, p): pass def test_load_js_files(self, *args): pass def mock_callable(c): pass def mock_test_js_loaded(paths, dummy, callback): pass def test_load_css_command(self, *args): pass def test_validate_commands(self, *args): pass def test_indent(self, *args): pass def test_to_javascript(self, *args): pass def test_element_wrapper(self, *args): pass def test_command_maker(self, *args): pass def test_call_maker(self, *args): pass def test_method_maker(self, *args): pass def test_literal_maker(self, *args): pass def test_set_maker(self, *args): pass def test_loader(self, *args): pass def test_debug_check_commands(self, *args): pass def test_wrap_callables(self, *args): pass def test_cmd_str(self, *args): pass def test_lazy_get(self, *args): pass def test_clean_dict(self, *args): pass @patch("jp_proxy_widget.proxy_widget.run_ui_poll_loop") def test_evaluate_success(self, *args): pass def fake_poll(*args): pass @patch("jp_proxy_widget.proxy_widget.run_ui_poll_loop") def test_evaluate_exception(self, *args): pass def fake_poll(*args): pass def test_on_rendered(self, *args): pass def fake_js_init(js, call_it): pass def test_in_dialog(self, *args): pass def test_quote_numpy_array(self, *args): pass def test_quote_numpy_array_in_dict(self, *args): pass def test_quote_numpy_array_elt(self, *args): pass
119
2
8
0
7
0
1
0.09
1
30
16
0
70
0
70
142
755
73
629
319
506
58
525
298
432
3
2
2
92
2,774
AaronWatters/jp_proxy_widget
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AaronWatters_jp_proxy_widget/tests/test_js_context.py
test_js_context.TestJsContext.test_remote_content.response
class response: text = "talks about jp_doodle and other things"
class response: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
2,775
AaronWatters/jp_proxy_widget
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AaronWatters_jp_proxy_widget/tests/test_proxy_widget.py
test_proxy_widget.TestProxyWidget.test_handle_custom_message_redir.mgr
class mgr: def __init__(self): self.entered = self.exitted = False def __enter__(self): self.entered = True def __exit__(self, *args): self.exitted = True
class mgr: def __init__(self): pass def __enter__(self): pass def __exit__(self, *args): pass
4
0
2
0
2
0
1
0
0
0
0
0
3
2
3
3
7
0
7
5
3
0
7
5
3
1
0
0
3
2,776
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.CallMaker
class CallMaker(CommandMaker): """ Proxy reference to a JS method call or function call. If kind == "method" and args == [target, name, arg0, ..., argn] Then proxy value is target.name(arg0, ..., argn) """ def __init__(self, kind, *args): self.kind = kind self.args = quoteLists(args) def javascript(self, level=0): kind = self.kind args = self.args # Add newlines in case of long chains. if kind == "function": function_desc = args[0] function_args = [to_javascript(x) for x in args[1:]] function_value = to_javascript(function_desc) call_js = "%s\n%s" % (function_value, format_args(function_args)) return indent_string(call_js, level) elif kind == "method": target_desc = args[0] name = args[1] method_args = [to_javascript(x) for x in args[2:]] target_value = to_javascript(target_desc) name_value = to_javascript(name) method_js = "%s\n[%s]\n%s" % (target_value, name_value, format_args(method_args)) return indent_string(method_js, level) else: # This should never be executed, but the javascript # translation is useful for debugging. message = "Warning: External callable " + repr(self.args) return "function() {alert(%s);}" % to_javascript(message) def __call__(self, *args): """ Call the callable returned by the function or method call. """ return CallMaker("function", self, *args) def _cmd(self): return [self.kind] + self.args
class CallMaker(CommandMaker): ''' Proxy reference to a JS method call or function call. If kind == "method" and args == [target, name, arg0, ..., argn] Then proxy value is target.name(arg0, ..., argn) ''' def __init__(self, kind, *args): pass def javascript(self, level=0): pass def __call__(self, *args): ''' Call the callable returned by the function or method call. ''' pass def _cmd(self): pass
5
2
8
0
7
2
2
0.43
1
0
0
0
4
2
4
13
43
4
28
20
23
12
26
20
21
3
3
1
6
2,777
AaronWatters/jp_proxy_widget
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AaronWatters_jp_proxy_widget/tests/test_proxy_widget.py
test_proxy_widget.TestProxyWidget.test_save_function.fakeWindow
class fakeWindow: Function = None
class fakeWindow: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
2,778
AaronWatters/jp_proxy_widget
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AaronWatters_jp_proxy_widget/tests/test_proxy_widget.py
test_proxy_widget.TestProxyWidget.test_save.dummy_elt
class dummy_elt: def _set(self, name, ref): setattr(self, name, ref)
class dummy_elt: def _set(self, name, ref): pass
2
0
2
0
2
0
1
0
0
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
0
0
1
2,779
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.SetMaker
class SetMaker(CommandMaker): """ Proxy container to set target.name = value. """ def __init__(self, target, name, value): self.target = target self.name = name self.value = value def javascript(self, level=0): innerlevel = 2 target = to_javascript(self.target, innerlevel) value = to_javascript(self.value, innerlevel) name = to_javascript(self.name, innerlevel) T = Set_Template % (target, name, value) return indent_string(T, level) def _cmd(self): #target = validate_command(self.target, False) #@value = validate_command(self.value, False) target = self.target value = self.value return ["set", target, self.name, value]
class SetMaker(CommandMaker): ''' Proxy container to set target.name = value. ''' def __init__(self, target, name, value): pass def javascript(self, level=0): pass def _cmd(self): pass
4
1
6
0
5
1
1
0.31
1
0
0
0
3
3
3
12
24
3
16
14
12
5
16
14
12
1
3
0
3
2,780
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.MethodMaker
class MethodMaker(CommandMaker): """ Proxy reference to a property or method of a JS object. """ def __init__(self, target, name): self.target = target self.name = name def javascript(self, level=0): # use target[value] notation (see comment above) target = to_javascript(self.target) attribute = to_javascript(self.name) # add a line break in case of long chains T = "%s\n[%s]" % (target, attribute) return indent_string(T, level) def _cmd(self): #target = validate_command(self.target, False) target = self.target return ["get", target, self.name] def __call__(self, *args): return CallMaker("method", self.target, self.name, *args)
class MethodMaker(CommandMaker): ''' Proxy reference to a property or method of a JS object. ''' def __init__(self, target, name): pass def javascript(self, level=0): pass def _cmd(self): pass def __call__(self, *args): pass
5
1
4
0
3
1
1
0.43
1
1
1
0
4
2
4
13
24
4
14
11
9
6
14
11
9
1
3
0
4
2,781
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.LiteralMaker
class LiteralMaker(CommandMaker): """ Proxy to make a literal dictionary or list which may contain other proxy references. """ translators = { np.ndarray: np_array_to_list, #np.float128: float, #np.float16: float, #np.float32: float, #np.float64: float, #np.int0: int, #np.int16: int, #np.int32: int, #np.int64: int, } for type_name in "float float128 float16 float32 float64".split(): if hasattr(np, type_name): ty = getattr(np, type_name) translators[ty] = float for type_name in "int int0 int16 int32 int64".split(): if hasattr(np, type_name): ty = getattr(np, type_name) translators[ty] = int indicators = { # things we can translate dict: "dict", list: "list", bytearray: "bytes", # we can't translate non-specific types, modules, etc. type: "don't translate non-specific types, like classes", type(json): "don't translate modules", # xxxx should improve sanity checking on types... } def __init__(self, thing): self.thing = thing def javascript(self, level=0): thing_fmt = to_javascript(self.thing) return indent_string(thing_fmt, level) def _cmd(self): thing = self.thing ty = type(thing) indicator = self.indicators.get(ty) #return [indicator, thing] if indicator: # exact type equality here: if ty is list: return [indicator] + quoteLists(thing) elif ty is dict: return [indicator, dict((k, quoteIfNeeded(thing[k])) for k in thing)] elif ty is bytearray: return [indicator, bytearray_to_hex(thing)] else: raise ValueError("can't translate " + repr(ty)) return thing
class LiteralMaker(CommandMaker): ''' Proxy to make a literal dictionary or list which may contain other proxy references. ''' def __init__(self, thing): pass def javascript(self, level=0): pass def _cmd(self): pass
4
1
7
0
6
1
2
0.47
1
5
0
0
3
1
3
12
58
5
36
13
32
17
27
13
23
5
3
2
7
2,782
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.LazyMethodCall
class LazyMethodCall(LazyCommandSuperClass): def __init__(self, for_widget, for_method, *args): self.for_method = for_method self.for_widget = for_widget args = for_widget.wrap_callables(args) self.args = args # when executing immediately save result of call in fragile_ref set_ref = SetMaker( for_widget.get_element(), FRAGILE_JS_REFERENCE, CallMaker("method", for_method.this_reference(), for_method.attribute, *args) ) for_widget.buffer_commands([set_ref]) for_widget.last_fragile_reference = self def _cmd(self): for_method = self.for_method m = CallMaker("method", for_method.for_target, for_method.attribute, *self.args) return m._cmd()
class LazyMethodCall(LazyCommandSuperClass): def __init__(self, for_widget, for_method, *args): pass def _cmd(self): pass
3
0
9
0
8
1
1
0.06
1
2
2
0
2
3
2
13
20
2
17
9
14
1
13
9
10
1
3
0
2
2,783
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.LazyGet
class LazyGet(LazyCommandSuperClass): def __init__(self, for_widget, for_target, attribute): self.for_target = for_target self.for_widget = for_widget self.attribute = attribute # when executing immediately put target ref in fragile_this and attr value in fragile_ref set_this = SetMaker(for_widget.get_element(), FRAGILE_THIS, for_target.reference()) # get attr value as element.fragile_this.attr attr_ref = MethodMaker(MethodMaker(for_widget.get_element(), FRAGILE_THIS), attribute) set_ref = SetMaker(for_widget.get_element(), FRAGILE_JS_REFERENCE, attr_ref) # execute immediately on init for_widget.buffer_commands([set_this, set_ref]) # use fragile ref to find value, until the cached value is replaced for_widget.last_fragile_reference = self def _cmd(self): m = MethodMaker(self.for_target, self.attribute) return m._cmd() def __call__(self, *args): if type(self.attribute) is str: return LazyMethodCall(self.for_widget, self, *args) else: m = MethodMaker(self.for_target, self.attribute) return LazyCall(self.for_widget, m, *args) def this_reference(self): for_widget = self.for_widget if for_widget.last_fragile_reference is self: #return this.fragile_reference return MethodMaker(for_widget.get_element(), FRAGILE_THIS) else: return self.for_target
class LazyGet(LazyCommandSuperClass): def __init__(self, for_widget, for_target, attribute): pass def _cmd(self): pass def __call__(self, *args): pass def this_reference(self): pass
5
0
7
0
6
1
2
0.2
1
6
4
0
4
3
4
15
34
4
25
14
20
5
23
14
18
2
3
1
6
2,784
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.DisableFlushContextManager
class DisableFlushContextManager(object): """ Temporarily disable flushes and also collect widget messages into a single group. This can speed up widget interactions and prevent the communication channel from flooding. """ def __init__(self, canvas): self.canvas = canvas self.save_flush = canvas.auto_flush def __enter__(self): canvas = self.canvas self.save_flush = canvas.auto_flush canvas.auto_flush = False def __exit__(self, type, value, traceback): canvas = self.canvas canvas.auto_flush = self.save_flush if (self.save_flush): canvas.flush()
class DisableFlushContextManager(object): ''' Temporarily disable flushes and also collect widget messages into a single group. This can speed up widget interactions and prevent the communication channel from flooding. ''' def __init__(self, canvas): pass def __enter__(self): pass def __exit__(self, type, value, traceback): pass
4
1
4
0
4
0
1
0.31
1
0
0
0
3
2
3
3
20
3
13
8
9
4
13
8
9
2
1
1
4
2,785
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.ElementWrapper
class ElementWrapper(object): """ Convenient top level access to the widget element. widget.element.action_name(arg1, arg2) executes the same as widget(widget.get_element.action_name(arg1, arg2)) which executes this.$$el.action_name(arg1, arg2) on the Javascript side. """ def __init__(self, for_widget): assert isinstance(for_widget, JSProxyWidget) self.widget = for_widget self.widget_element = for_widget.get_element() def __getattr__(self, name): #return ElementCallWrapper(self.widget, self.widget_element, name) if name == '_ipython_canary_method_should_not_exist_': return 42 # ipython poking around... return LazyGet(self.widget, self.widget_element, name) # for parallelism to _set _get = __getattr__ # in javascript these are essentially the same thing. __getitem__ = __getattr__ def _set(self, name, value): "Proxy to set a property of the widget element." #return self.widget(self.widget_element._set(name, value)) ref = value if isinstance(value, CommandMakerSuperClass): ref = value.reference() command = SetMaker(self.widget_element, name, ref) self.widget.buffer_commands([command]) return LazyGet(self.widget, self.widget_element, name)
class ElementWrapper(object): ''' Convenient top level access to the widget element. widget.element.action_name(arg1, arg2) executes the same as widget(widget.get_element.action_name(arg1, arg2)) which executes this.$$el.action_name(arg1, arg2) on the Javascript side. ''' def __init__(self, for_widget): pass def __getattr__(self, name): pass def _set(self, name, value): '''Proxy to set a property of the widget element.''' pass
4
2
6
0
5
1
2
0.67
1
4
4
0
3
2
3
3
37
8
18
10
14
12
18
10
14
2
1
1
5
2,786
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.InvalidCommand
class InvalidCommand(Exception): "Invalid command"
class InvalidCommand(Exception): '''Invalid command''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
10
2
0
1
1
0
1
1
1
0
0
3
0
0
2,787
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.JSProxyWidget
class JSProxyWidget(widgets.DOMWidget): """Introspective javascript proxy widget.""" _view_name = Unicode('JSProxyView').tag(sync=True) _model_name = Unicode('JSProxyModel').tag(sync=True) _view_module = Unicode('jp_proxy_widget').tag(sync=True) _model_module = Unicode('jp_proxy_widget').tag(sync=True) _view_module_version = Unicode('^1.0.10').tag(sync=True) _model_module_version = Unicode('^1.0.10').tag(sync=True) # traitlet port to use for sending commands to javascript #commands = traitlets.List([], sync=True) # Rendered flag sent by JS view after render is complete. rendered = traitlets.Bool(False, sync=True) status = traitlets.Unicode("Not initialized", sync=True) error_msg = traitlets.Unicode("No error", sync=True) # increment this after every flush to force a sync? _send_counter = traitlets.Integer(0, sync=True) verbose = False # Set to automatically flush messages to javascript side without buffering after render. auto_flush = True def __init__(self, *pargs, **kwargs): super(JSProxyWidget, self).__init__(*pargs, **kwargs) # top level access for element operations self.element = ElementWrapper(self) self.counter = 0 self.count_to_results_callback = {} self.default_event_callback = None self.identifier_to_callback = {} self.callable_cache = {} #self.callback_to_identifier = {} #self.on_trait_change(self.handle_callback_results, "callback_results") #self.on_trait_change(self.handle_results, "results") self.on_trait_change(self.handle_rendered, "rendered") self.on_trait_change(self.handle_error_msg, "error_msg") ##pr "registered on_msg(handle_custom_message)" self.on_msg(self.handle_custom_message_wrapper) self.buffered_commands = [] #self.commands_awaiting_render = [] self.last_commands_sent = [] self.last_callback_results = None self.results = [] self.status = "Not yet rendered" self.last_attribute = None # Used for D3 style "chaining" -- reference to last object reference cached on JS side self.last_fragile_reference = None #self.executing_fragile = False # standard initialization in javascript self.js_init(""" // make the window accessible through the element element.window = window; // Initialize caching slots. element._FRAGILE_THIS = null; element._FRAGILE_JS_REFERENCE = null; // The following is used for sending synchronous values. element._SEND_FRAGILE_JS_REFERENCE = function(ms_delay) { // xxxxx add a delay to allow the Python side to be ready for the response (???) ms_delay = ms_delay || 100; var ref = element._FRAGILE_JS_REFERENCE; var delayed = function () { RECEIVE_FRAGILE_REFERENCE(ref); }; setTimeout(delayed, ms_delay); }; """, RECEIVE_FRAGILE_REFERENCE=self._RECEIVE_FRAGILE_REFERENCE, callable_level=5) def set_element(self, slot_name, value): """ Map value to javascript and attach it as element[slot_name]. """ self.js_init("element[slot_name] = value;", slot_name=slot_name, value=value) def get_value_async(self, callback, javascript_expression, debug=False): """ Evaluate the Javascript expression and send the result value to the callback as callback(value) asynchronously. """ codeList = [] codeList.append("// get_value_async") if debug: codeList.append("debugger;") codeList.append("callback(" + javascript_expression + ");") code = "\n".join(codeList) self.js_init(code, callback=callback) def js_init(self, js_function_body, callable_level=3, **other_arguments): """ Run special purpose javascript initialization code. The function body is provided with the element as a free variable. """ #pr ("js_init") #pr(js_function_body) other_argument_names = list(other_arguments.keys()) #pr ("other names", other_argument_names) def listiffy(v): "convert tuples and elements of tuples to lists" type_v = type(v) if type_v in [tuple, list]: return list(listiffy(x) for x in v) elif type_v is dict: return dict((a, listiffy(b)) for (a,b) in v.items()) else: return v def map_value(v): #if callable(v): # return self.callable(v, level=callable_level) v = self.wrap_callables(v, callable_level=callable_level) return listiffy(v) other_argument_values = [map_value(other_arguments[name]) for name in other_argument_names] #pr( "other_values", other_argument_values) #other_argument_values = [other_arguments[name] for name in other_argument_names] #other_argument_values = self.wrap_callables(other_argument_values) argument_names = list(["element"] + other_argument_names) argument_values = list([self.get_element()] + other_argument_values) function = self.function(argument_names, js_function_body) function_call = function(*argument_values) # execute the function call on the javascript side. def action(): self(function_call) self.flush() if self._needs_requirejs: # defer action until require is defined self.uses_require(action) else: # just execute it action() def wrap_callables(self, x, callable_level=3): def wrapit(x): if callable(x) and not isinstance(x, CommandMakerSuperClass): return self.callable(x, level=callable_level) # otherwise ty = type(x) if ty is list: return list(wrapit(y) for y in x) if ty is tuple: return tuple(wrapit(y) for y in x) if ty is dict: return dict((k, wrapit(v)) for (k,v) in x.items()) # default return x return wrapit(x) def wrap_callables0(self, x, callable_level=3): if callable(x) and not isinstance(x, CommandMakerSuperClass): return self.callable(x, level=callable_level) w = self.wrap_callables ty = type(x) if ty is list: return list(w(y) for y in x) if ty is tuple: return tuple(w(y) for y in x) if ty is dict: return dict((k, w(v)) for (k,v) in x.items()) # default return x print_on_error = True def setTimeout(self, callable, milliseconds): "Convenience access to window.setTimeout in Javascript" self.element.window.setTimeout(callable, milliseconds) def on_rendered(self, callable, *positional, **keyword): """ After the widget has rendered, call the callable using the provided arguments. This can be used to initialize an animation after the widget is visible, for example. """ def call_it(): return callable(*positional, **keyword) self.js_init("call_it();", call_it=call_it) def handle_error_msg(self, att_name, old, new): if self.print_on_error: print("new error message: " + new) def handle_rendered(self, att_name, old, new): "when rendered send any commands awaiting the render event." try: #if self.commands_awaiting_render: #self.send_commands([]) if self.auto_flush: #("xxxx flushing on render") self.flush() self.status= "Rendered." except Exception as e: self.error_msg = repr(e) raise def send_custom_message(self, indicator, payload): package = { INDICATOR: indicator, PAYLOAD: payload, } self._last_payload = payload if self.verbose: print("sending") pprint(package) #debug_check_commands(package) self.send(package) # slot for last message data debugging _last_message_data = None _json_accumulator = [] _last_custom_message_error = None _last_accumulated_json = None # Output context for message handling -- will print exception traces, for example, if set output = None def handle_custom_message_wrapper(self, widget, data, *etcetera): "wrapper to enable output redirects for custom messages." output = self.output if output is not None: with output: self.handle_custom_message(widget, data, *etcetera) else: self.handle_custom_message(widget, data, *etcetera) def debugging_display(self, tagline="debug message area for widget:", border='1px solid black'): if border: out = widgets.Output(layout={'border': border}) else: out = widgets.Output() if tagline: with out: print (tagline) self.output = out status_text = widgets.Text(description="status:", value="") traitlets.directional_link((self, "status"), (status_text, "value")) error_text = widgets.Text(description="error", value="") traitlets.directional_link((self, "error_msg"), (error_text, "value")) assembly = widgets.VBox(children=[self, status_text, error_text, out]) return assembly def handle_custom_message(self, widget, data, *etcetera): #pr("handle custom message") #pprint(data) try: self._last_message_data = data indicator = data[INDICATOR] payload = data[PAYLOAD] if indicator == RESULTS: self.results = payload self.status = "Got results." self.handle_results(payload) elif indicator == CALLBACK_RESULTS: self.status = "got callback results" self.last_callback_results = payload self.handle_callback_results(payload) elif indicator == JSON_CB_FRAGMENT: self.status = "got callback fragment" self._json_accumulator.append(payload) elif indicator == JSON_CB_FINAL: self.status = "got callback final" acc = self._json_accumulator self._json_accumulator = [] acc.append(payload) self._last_accumulated_json = acc accumulated_json_str = u"".join(acc) accumulated_json_ob = json.loads(accumulated_json_str) self.handle_callback_results(accumulated_json_ob) else: self.status = "Unknown indicator from custom message " + repr(indicator) except Exception as e: # for debugging assistance #pr ("custom message error " + repr(e)) self._last_custom_message_error = e self.error_msg = repr(e) raise def unique_id(self, prefix="jupyter_proxy_widget_id_"): IDENTITY_COUNTER[0] += 1 return prefix + str(IDENTITY_COUNTER[0]) def __call__(self, command): "Send command convenience." return self.buffer_command(command) def buffer_command(self, command): "Add a command to the buffered commands. Convenience." self.buffer_commands([command]) return command def buffer_commands(self, commands): self.buffered_commands.extend(commands) if self.auto_flush: self.flush() return commands def seg_flush(self, results_callback=None, level=1, segmented=BIG_SEGMENT): "flush a potentially large command sequence, segmented." return self.flush(results_callback, level, segmented) error_on_flush = False # Primarily for debugging def flush(self, results_callback=None, level=1, segmented=None): "send the buffered commands and clear the buffer. Convenience." if not self.rendered: #("XXXX not flushing before render", len(self.buffered_commands)) self.status = "deferring flush until render" return None if self.error_on_flush: raise ValueError("flush is disabled") commands = self.buffered_commands self.buffered_commands = [] #("XXXXX now flushing", len(commands)) result = self.send_commands(commands, results_callback, level, segmented=segmented) self._send_counter += 1 return result def save(self, name, reference): """ Proxy to save referent in the element namespace by name. The command to save the element is buffered and the return value is a reference to the element by name. """ elt = self.get_element() reference = self.wrap_callables(reference) save_command = elt._set(name, reference) # buffer the save operation self(save_command) # return the reference by name return getattr(self.element, name) _jqueryUI_checked = False def check_jquery(self, onsuccess=None, force=False, code_fn="js/jquery-ui-1.12.1/jquery-ui.js", style_fn="js/jquery-ui-1.12.1/jquery-ui.css"): """ Make JQuery and JQueryUI globally available for other modules. """ # window.jQuery is automatically defined if absent. if force or not self._jqueryUI_checked: self.load_js_files([code_fn]) self.load_css(style_fn) # no need to load twice. JSProxyWidget._jqueryUI_checked = True if onsuccess: onsuccess() def in_dialog( self, title="", autoOpen=True, buttons=None, # dict of label to callback height="auto", width=300, modal=False, **other_options, ): """ Pop the widget into a floating jQueryUI dialog. See https://api.jqueryui.com/1.9/dialog """ self.check_jquery() options = clean_dict( title=title, autoOpen=autoOpen, buttons=buttons, height=height, width=width, modal=modal, **other_options, ) self.element.dialog(options) _require_checked = False _needs_requirejs = False _delayed_require_actions = None def uses_require(self, action=None, filepath="js/require.js"): """ Force load require.js if window.require is not yet available. """ # For subsequent actions wait for require to have loaded before executing self._needs_requirejs = True def load_failed(): raise ImportError("Failed to load require.js in javascript context.") def require_ok(): pass # do nothing # this is a sequence of message callbacks: if self._require_checked: # if require is loaded, just do it self.element.alias_require(require_ok, load_failed) if action: action() return # uses_require actions should be done in order. # delay subsequent actions until this action is complete # NOTE: if communications fail this mechanism may lock up the widget. delayed = self._delayed_require_actions if delayed: # do this action when the previous delayed actions are complete # pr("delaying action because uses_require is in process") if action: delayed.append(action) return # otherwise this is the first delayed action if action: self._delayed_require_actions = [action] def check_require(): "alias require/define or load it if is not available." # pr ("calling alias_require") self.element.alias_require(load_succeeded, load_require) def load_require(): "load require.js and validate the load, fail on timeout" # pr ("loading " + filepath) self.load_js_files([filepath]) # pr ("calling when loaded " + filepath) self.element.when_loaded([filepath], validate_require, load_failed) def validate_require(): # pr ("validating require load") self.element.alias_require(load_succeeded, load_failed) def load_succeeded(): JSProxyWidget._require_checked = True #if action: # action() # execute all delayed actions in insertion order delayed = self._delayed_require_actions while delayed: current_action = delayed[0] del delayed[0] try: current_action() except Exception as e: self.error_msg = "require.js delayed action exception " + repr(e) self._delayed_require_actions[:] = [] return self._delayed_require_actions = None # Start the async message sequence # pr ("checking require") check_require() def load_css(self, filepath, local=True): """ Load a CSS text content from a file accessible by Python. """ text = js_context.get_text_from_file_name(filepath, local) return self.load_css_text(filepath, text) def load_css_text(self, filepath, text): cmd = self.load_css_command(filepath, text) self(cmd) #return js_context.display_css(self, text) def require_js(self, name, filepath, local=True): """ Load a require.js module from a file accessible by Python. Define the module content using the name in the requirejs module system. """ def load_it(): text = js_context.get_text_from_file_name(filepath, local) return self.load_js_module_text(name, text) self.uses_require(load_it) def load_js_module_text(self, name, text): """ Load a require.js module text. """ return self.element._load_js_module(name, text); #elt = self.get_element() #load_call = elt._load_js_module(name, text) #self(load_call) # return reference to the loaded module #return getattr(elt, name) def save_new(self, name, constructor, arguments): """ Construct a 'new constructor(arguments)' and save in the element namespace. Store the construction in the command buffer and return a reference to the new object. This must be followed by a flush() to execute the command. """ new_reference = self.get_element().New(constructor, arguments) return self.save(name, new_reference) def save_function(self, name, arguments, body): """ Buffer a command to create a JS function using "new Function(...)" """ klass = self.window().Function return self.save_new(name, klass, list(arguments) + [body]) def function(self, arguments, body): klass = self.window().Function return self.get_element().New(klass, list(arguments) + [body]) handle_results_exception = None def handle_results(self, new): "Callback for when results arrive after the JS View executes commands." if self.verbose: print ("got results", new) [identifier, json_value] = new i2c = self.identifier_to_callback results_callback = i2c.get(identifier) if results_callback is not None: del i2c[identifier] try: results_callback(json_value) except Exception as e: #pr ("handle results exception " + repr(e)) self.handle_results_exception = e self.error_msg = "Handle results: " + repr(e) raise handle_callback_results_exception = None last_callback_results = None def handle_callback_results(self, new): "Callback for when the JS View sends an event notification." #pr ("HANDLE CALLBACK RESULTS") #pprint(new) self.last_callback_results = new if self.verbose: print ("got callback results", new) [identifier, json_value, arguments, counter] = new i2c = self.identifier_to_callback results_callback = i2c.get(identifier) self.status = "call back to " + repr(results_callback) if results_callback is not None: try: results_callback(json_value, arguments) except Exception as e: #pr ("handle results callback exception " +repr(e)) self.handle_callback_results_exception = e self.error_msg = "Handle callback results: " + repr(e) raise def send_command(self, command, results_callback=None, level=1): "Send a single command to the JS View." return self.send_commands([command], results_callback, level) def send_commands(self, commands_iter, results_callback=None, level=1, segmented=None, check=False): """Send several commands fo the JS View. If segmented is a positive integer then the commands payload will be pre-encoded as a json string and sent in segments of that length """ count = self.counter self.counter = count + 1 commands_iter = list(commands_iter) qcommands = list(map(quoteIfNeeded, commands_iter)) commands = self.validate_commands(qcommands) if check: debug_check_commands(commands) if self.rendered: # also send buffered commands #if self.commands_awaiting_render: # commands = commands + self.commands_awaiting_render # self.commands_awaiting_render = None if self.buffered_commands: commands = self.buffered_commands + commands self.buffered_commands = [] payload = [count, commands, level] if results_callback is not None: self.identifier_to_callback[count] = results_callback # send the command using the commands traitlet which is mirrored to javascript. #self.commands = payload if segmented and segmented > 0: self.send_segmented_message(COMMANDS_FRAGMENT, COMMANDS_FINAL, payload, segmented) else: self.send_custom_message(COMMANDS, payload) self.last_commands_sent = payload return payload else: # wait for render event before sending commands. ##pr "waiting for render!", commands #self.commands_awaiting_render.extend(commands) self.buffered_commands.extend(commands) return ("awaiting render", commands) def send_segmented_message(self, frag_ind, final_ind, payload, segmented): "Send a message in fragments." json_str = json.dumps(payload) len_json = len(json_str) cursor = 0 # don't reallocate large string tails... while len_json - cursor > segmented: next_cursor = cursor + segmented json_fragment = json_str[cursor: next_cursor] # send the fragment self.send_custom_message(frag_ind, json_fragment) cursor = next_cursor json_tail = json_str[cursor:] self.send_custom_message(final_ind, json_tail) _synced_command_result = None _synced_command_evaluated = False _synced_command_timed_out = False _synced_command_timeout_time = None def evaluate(self, command, level=3, timeout=3000, ms_delay=100): "Evaluate the command and return the converted javascript value." # temporarily disable error prints print_on_error = self.print_on_error old_err = self.error_msg try: # Note: if the command buffer has not been flushed other operations may set the error_msg self.print_on_error = False self.error_msg = "" self._synced_command_result = None self._synced_command_timed_out = False self._synced_command_evaluated = False self._synced_command_timeout_time = None start = time.time() if timeout is not None and timeout > 0: self._synced_command_timeout_time = start + timeout start = self._synced_command_start_time = time.time() self._send_synced_command(command, level, ms_delay=ms_delay) run_ui_poll_loop(self._sync_complete) if self._synced_command_timed_out: raise TimeoutError("wait: %s, started: %s; gave up %s" % (timeout, start, time.time())) assert self._synced_command_evaluated, repr((self._synced_command_evaluated, self._synced_command_result)) error_msg = self.error_msg result = self._synced_command_result if error_msg: if error_msg == result: raise JavascriptException("sync error: " + repr(error_msg)) else: old_err = error_msg return result finally: # restore error prints if formerly enabled self.error_msg = old_err self.print_on_error = print_on_error def _send_synced_command(self, command, level, ms_delay=100): if self.last_fragile_reference is not command: set_ref = SetMaker(self.get_element(), FRAGILE_JS_REFERENCE, command) self.buffer_command(set_ref) #self.element._SEND_FRAGILE_JS_REFERENCE() get_ref = CallMaker("method", self.get_element(), SEND_FRAGILE_JS_REFERENCE, ms_delay) self.buffer_command(get_ref) self.flush() def _RECEIVE_FRAGILE_REFERENCE(self, value): self._synced_command_result = value self._synced_command_evaluated = True def _sync_complete(self): if self._synced_command_timeout_time is not None: self._synced_command_timed_out = (time.time() > self._synced_command_timeout_time) test = self._synced_command_evaluated or self._synced_command_timed_out if test: return test else: return None # only None signals end of polling loop. """ # doesn't work: not used. def evaluate(self, command, level=1, timeout=3000): "Send one command and wait for result. Return result." results = self.evaluate_commands([command], level, timeout) assert len(results) == 1 return results[0] def evaluate_commands(self, commands_iter, level=1, timeout=3000): "Send commands and wait for results. Return results." # inspired by https://github.com/jdfreder/ipython-jsobject/blob/master/jsobject/utils.py result_list = [] def evaluation_callback(json_value): result_list.append(json_value) self.send_commands(commands_iter, evaluation_callback, level) # get_ipython is a builtin in the ipython context (no import needed (?)) #ip = get_ipython() start = time.time() while not result_list: if time.time() - start > timeout/ 1000.0: raise Exception("Timeout waiting for command results: " + repr(timeout)) ip.kernel.do_one_iteration() return result_list[0] """ def seg_callback(self, callback_function, data, level=1, delay=False, segmented=BIG_SEGMENT): """ Proxy callback with message segmentation to support potentially large messages. """ return self.callback(callback_function, data, level, delay, segmented) def callable(self, function_or_method, level=1, delay=False, segmented=None): """ Simplified callback protocol. Map function_or_method to a javascript function js_function Calls to js_function(x, y, z) will trigger calls to function_or_method(x, y, z) where x, y, z are json compatible values. """ # do not double wrap CallMakers if isinstance(function_or_method, CallMaker): return function_or_method # get existing wrapper value from cache, if available cache = self.callable_cache result = cache.get(function_or_method) if result is not None: return result data = repr(function_or_method) def callback_function(_data, arguments): count = 0 # construct the Python argument list from argument mapping py_arguments = [] while 1: argstring = str(count) if argstring in arguments: argvalue = arguments[argstring] py_arguments.append(argvalue) count += 1 else: break function_or_method(*py_arguments) result = self.callback(callback_function, data, level, delay, segmented) cache[function_or_method] = result return result def callback(self, callback_function, data, level=1, delay=False, segmented=None): "Create a 'proxy callback' to receive events detected by the JS View." assert level > 0, "level must be positive " + repr(level) assert level <= 5, "level cannot exceed 5 " + repr(level) assert segmented is None or (type(segmented) is int and segmented > 0), "bad segment " + repr(segmented) count = self.counter self.counter = count + 1 assert not isinstance(callback_function, CommandMakerSuperClass), "can't callback command maker " + type(callback_function) assert not str(data).startswith("Fragile"), "DEBUG::" + repr(data) command = CallMaker("callback", count, data, level, segmented) #if delay: # callback_function = delay_in_thread(callback_function) self.identifier_to_callback[count] = callback_function return command def forget_callback(self, callback_function): "Remove all uses of callback_function in proxy callbacks (Python side only)." i2c = self.identifier_to_callback deletes = [i for i in i2c if i2c[i] == callback_function] for i in deletes: del i2c[i] def js_debug(self, *arguments): """ Break in the Chrome debugger (only if developer tools is open) """ if not arguments: arguments = [self.get_element()] return self.send_command(self.function(["element"], "debugger;")(self.get_element())) def print_status(self): status_slots = """ results auto_flush _last_message_data _json_accumulator _last_custom_message_error _last_accumulated_json _jqueryUI_checked _require_checked handle_results_exception last_callback_results """ print (repr(self) + " STATUS:") for slot_name in status_slots.split(): print ("\t::::: " + slot_name + " :::::") print (getattr(self, slot_name, "MISSING")) def get_element(self): "Return a proxy reference to the Widget JQuery element this.$el." return CommandMaker("element") def window(self): "Return a proxy reference to the browser window top level name space." return CommandMaker("window") def load_js_files(self, filenames, force=True, local=True): for filepath in filenames: def load_the_file(filepath=filepath): # pr ("loading " + filepath) filetext = js_context.get_text_from_file_name(filepath, local=True) cmd = self.load_js_command(filepath, filetext) self(cmd) if force: # this may result in reading and sending the file content too many times... load_the_file() else: # only load the file if no file of that name has been loaded load_callback = self.callable(load_the_file) # pr ("test/loading " + filepath + " " + repr(load_callback)) self.element.test_js_loaded([filepath], None, load_callback) def load_js_command(self, js_name, js_text): return Loader(LOAD_JS, js_name, js_text) def load_css_command(self, css_name, css_text): return Loader(LOAD_CSS, css_name, css_text) def validate_commands(self, commands, top=True): """ Validate a command sequence (and convert to list format if needed.) """ return [self.validate_command(c, top) for c in commands] def validate_command(self, command, top=True): # convert CommandMaker to list format. if isinstance(command, CommandMakerSuperClass): command = command._cmd() elif callable(command): # otherwise convert callables to callbacks, in list format command = self.callable(command)._cmd() assert not isinstance(command, CommandMakerSuperClass), repr((type(command), command)) ty = type(command) if ty is list: indicator = command[0] remainder = command[1:] if indicator == "element" or indicator == "window": assert len(remainder) == 0 elif indicator == "method": target = remainder[0] name = remainder[1] args = remainder[2:] target = self.validate_command(target, top=True) assert type(name) is str, "method name must be a string " + repr(name) args = self.validate_commands(args, top=False) remainder = [target, name] + args elif indicator == "function": target = remainder[0] args = remainder[1:] target = self.validate_command(target, top=True) args = self.validate_commands(args, top=False) remainder = [target] + args elif indicator == "id" or indicator == "bytes": assert len(remainder) == 1, "id or bytes takes one argument only " + repr(remainder) elif indicator in LOAD_INDICATORS: assert len(remainder) == 2, "loaders take exactly 2 arguments" + repr(len(remainder)) elif indicator == "list": remainder = self.validate_commands(remainder, top=False) elif indicator == "dict": [d] = remainder d = dict((k, self.validate_command(d[k], top=False)) for k in d) remainder = [d] elif indicator == "callback": [numerical_identifier, untranslated_data, level, segmented] = remainder assert type(numerical_identifier) is int, \ "must be integer " + repr(numerical_identifier) assert type(level) is int, \ "must be integer " + repr(level) assert (segmented is None) or (type(segmented) is int and segmented > 0), \ "must be None or positive integer " + repr(segmented) elif indicator == "get": [target, name] = remainder target = self.validate_command(target, top=True) name = self.validate_command(name, top=False) remainder = [target, name] elif indicator == "set": [target, name, value] = remainder target = self.validate_command(target, top=True) name = self.validate_command(name, top=False) value = self.validate_command(value, top=False) remainder = [target, name, value] elif indicator == "null": [target] = remainder remainder = [self.validate_command(target, top=False)] else: raise ValueError("bad indicator " + repr(indicator)) command = [indicator] + remainder elif top: raise ValueError("top level command must be a list " + repr(command)) # Non-lists are untranslated (but should be JSON compatible). return command def delay_flush(self): """ Context manager to group a large number of operations into one message. This can prevent flooding messages over the ZMQ communications link between the Javascript front end and the Python kernel backend. >>> with widget.delay_flush(): ... many_operations(widget) ... even_more_operations(widget) """ return DisableFlushContextManager(self)
class JSProxyWidget(widgets.DOMWidget): '''Introspective javascript proxy widget.''' def __init__(self, *pargs, **kwargs): pass def set_element(self, slot_name, value): ''' Map value to javascript and attach it as element[slot_name]. ''' pass def get_value_async(self, callback, javascript_expression, debug=False): ''' Evaluate the Javascript expression and send the result value to the callback as callback(value) asynchronously. ''' pass def js_init(self, js_function_body, callable_level=3, **other_arguments): ''' Run special purpose javascript initialization code. The function body is provided with the element as a free variable. ''' pass def listiffy(v): '''convert tuples and elements of tuples to lists''' pass def map_value(v): pass def action(): pass def wrap_callables(self, x, callable_level=3): pass def wrapit(x): pass def wrap_callables0(self, x, callable_level=3): pass def setTimeout(self, callable, milliseconds): '''Convenience access to window.setTimeout in Javascript''' pass def on_rendered(self, callable, *positional, **keyword): ''' After the widget has rendered, call the callable using the provided arguments. This can be used to initialize an animation after the widget is visible, for example. ''' pass def call_it(): pass def handle_error_msg(self, att_name, old, new): pass def handle_rendered(self, att_name, old, new): '''when rendered send any commands awaiting the render event.''' pass def send_custom_message(self, indicator, payload): pass def handle_custom_message_wrapper(self, widget, data, *etcetera): '''wrapper to enable output redirects for custom messages.''' pass def debugging_display(self, tagline="debug message area for widget:", border='1px solid black'): pass def handle_custom_message_wrapper(self, widget, data, *etcetera): pass def unique_id(self, prefix="jupyter_proxy_widget_id_"): pass def __call__(self, command): '''Send command convenience.''' pass def buffer_command(self, command): '''Add a command to the buffered commands. Convenience.''' pass def buffer_commands(self, commands): pass def seg_flush(self, results_callback=None, level=1, segmented=BIG_SEGMENT): '''flush a potentially large command sequence, segmented.''' pass def flush(self, results_callback=None, level=1, segmented=None): '''send the buffered commands and clear the buffer. Convenience.''' pass def save(self, name, reference): ''' Proxy to save referent in the element namespace by name. The command to save the element is buffered and the return value is a reference to the element by name. ''' pass def check_jquery(self, onsuccess=None, force=False, code_fn="js/jquery-ui-1.12.1/jquery-ui.js", style_fn="js/jquery-ui-1.12.1/jquery-ui.css"): ''' Make JQuery and JQueryUI globally available for other modules. ''' pass def in_dialog( self, title="", autoOpen=True, buttons=None, # dict of label to callback height="auto", width=300, modal=False, **other_options, ): ''' Pop the widget into a floating jQueryUI dialog. See https://api.jqueryui.com/1.9/dialog ''' pass def uses_require(self, action=None, filepath="js/require.js"): ''' Force load require.js if window.require is not yet available. ''' pass def load_failed(): pass def require_ok(): pass def check_require(): '''alias require/define or load it if is not available.''' pass def load_require(): '''load require.js and validate the load, fail on timeout''' pass def validate_require(): pass def load_succeeded(): pass def load_css(self, filepath, local=True): ''' Load a CSS text content from a file accessible by Python. ''' pass def load_css_text(self, filepath, text): pass def require_js(self, name, filepath, local=True): ''' Load a require.js module from a file accessible by Python. Define the module content using the name in the requirejs module system. ''' pass def load_it(): pass def load_js_module_text(self, name, text): ''' Load a require.js module text. ''' pass def save_new(self, name, constructor, arguments): ''' Construct a 'new constructor(arguments)' and save in the element namespace. Store the construction in the command buffer and return a reference to the new object. This must be followed by a flush() to execute the command. ''' pass def save_function(self, name, arguments, body): ''' Buffer a command to create a JS function using "new Function(...)" ''' pass def function(self, arguments, body): pass def handle_results(self, new): '''Callback for when results arrive after the JS View executes commands.''' pass def handle_callback_results(self, new): '''Callback for when the JS View sends an event notification.''' pass def send_command(self, command, results_callback=None, level=1): '''Send a single command to the JS View.''' pass def send_commands(self, commands_iter, results_callback=None, level=1, segmented=None, check=False): '''Send several commands fo the JS View. If segmented is a positive integer then the commands payload will be pre-encoded as a json string and sent in segments of that length ''' pass def send_segmented_message(self, frag_ind, final_ind, payload, segmented): '''Send a message in fragments.''' pass def evaluate(self, command, level=3, timeout=3000, ms_delay=100): '''Evaluate the command and return the converted javascript value.''' pass def _send_synced_command(self, command, level, ms_delay=100): pass def _RECEIVE_FRAGILE_REFERENCE(self, value): pass def _sync_complete(self): pass def seg_callback(self, callback_function, data, level=1, delay=False, segmented=BIG_SEGMENT): ''' Proxy callback with message segmentation to support potentially large messages. ''' pass def callable(self, function_or_method, level=1, delay=False, segmented=None): ''' Simplified callback protocol. Map function_or_method to a javascript function js_function Calls to js_function(x, y, z) will trigger calls to function_or_method(x, y, z) where x, y, z are json compatible values. ''' pass def callback_function(_data, arguments): pass def callback_function(_data, arguments): '''Create a 'proxy callback' to receive events detected by the JS View.''' pass def forget_callback(self, callback_function): '''Remove all uses of callback_function in proxy callbacks (Python side only).''' pass def js_debug(self, *arguments): ''' Break in the Chrome debugger (only if developer tools is open) ''' pass def print_status(self): pass def get_element(self): '''Return a proxy reference to the Widget JQuery element this.$el.''' pass def window(self): '''Return a proxy reference to the browser window top level name space.''' pass def load_js_files(self, filenames, force=True, local=True): pass def load_the_file(filepath=filepath): pass def load_js_command(self, js_name, js_text): pass def load_css_command(self, css_name, css_text): pass def validate_commands(self, commands, top=True): ''' Validate a command sequence (and convert to list format if needed.) ''' pass def validate_commands(self, commands, top=True): pass def delay_flush(self): ''' Context manager to group a large number of operations into one message. This can prevent flooding messages over the ZMQ communications link between the Javascript front end and the Python kernel backend. >>> with widget.delay_flush(): ... many_operations(widget) ... even_more_operations(widget) ''' pass
69
39
12
0
9
3
2
0.38
1
20
8
0
54
13
54
54
881
78
586
210
506
221
511
193
442
16
1
3
147
2,788
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.JavascriptException
class JavascriptException(ValueError): "The sync operation caused an exception in the Javascript interpreter."
class JavascriptException(ValueError): '''The sync operation caused an exception in the Javascript interpreter.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
2,789
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.LazyCall
class LazyCall(LazyCommandSuperClass): def __init__(self, for_widget, for_target, *args): self.for_target = for_target self.for_widget = for_widget args = for_widget.wrap_callables(args) self.args = args # when executing immediately save result of call in fragile_ref set_ref = SetMaker( for_widget.get_element(), FRAGILE_JS_REFERENCE, CallMaker("function", self.for_target.reference(), *args) ) for_widget.buffer_commands([set_ref]) for_widget.last_fragile_reference = self def _cmd(self): c = CallMaker("function", self.for_target, *self.args) return c.cmd()
class LazyCall(LazyCommandSuperClass): def __init__(self, for_widget, for_target, *args): pass def _cmd(self): pass
3
0
8
0
8
1
1
0.06
1
2
2
0
2
3
2
13
19
2
16
8
13
1
12
8
9
1
3
0
2
2,790
AaronWatters/jp_proxy_widget
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AaronWatters_jp_proxy_widget/tests/test_js_context.py
test_js_context.TestJsContext.test_eval_javascript.dummyRecord
class dummyRecord: def __call__(self, *args): pass
class dummyRecord: def __call__(self, *args): pass
2
0
2
0
2
0
1
0
0
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
0
0
1
2,791
AaronWatters/jp_proxy_widget
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AaronWatters_jp_proxy_widget/tests/test_js_context.py
test_js_context.TestJsContext
class TestJsContext(unittest.TestCase): def test_local_path(self): f = tempfile.NamedTemporaryFile() name = f.name path = js_context.get_file_path(name) abspath = os.path.abspath(name) self.assertEqual(path, abspath) def test_local_path_relative_to_module(self): f = tempfile.NamedTemporaryFile() name = f.name path = js_context.get_file_path(name, relative_to_module=tempfile) abspath = os.path.abspath(name) self.assertEqual(path, abspath) def test_module_path(self): name = "js/simple.js" path = js_context.get_file_path(name,) abspath = os.path.abspath(name) assert abspath.endswith("jp_proxy_widget/js/simple.js") # @patch("jp_proxy_widget.js_context.requests.get") # dunno why I had to comment this... def test_remote_content( self, path="https://raw.githubusercontent.com/AaronWatters/jp_proxy_widget/master/README.md"): class response: text = "talks about jp_doodle and other things" save = js_context.requests.get js_context.requests.get = MagicMock(return_value=response) content = js_context.get_text_from_file_name(path) js_context.requests.get = save assert "jp_doodle" in content def test_local_content(self, path="js/simple.js"): content = js_context.get_text_from_file_name(path) assert "simple javascript" in content def test_byte_content(self, path="js/simple.js"): from unittest.mock import patch, mock_open byte_content = b"byte content" unicode_content = u"byte content" m = mock_open(read_data=byte_content) open_name = '%s.open' % js_context.__name__ path = "js/simple.js" with patch(open_name, m): content = js_context.get_text_from_file_name(path) self.assertEqual(content, unicode_content) @patch("jp_proxy_widget.js_context.display") @patch("jp_proxy_widget.js_context.Javascript") def test_display_javacript(self, mock1, mock2): js_text = "debugger" js_context.display_javascript(None, js_text) assert mock1.called assert mock2.called assert mock2.called_with(data=js_text) @patch("jp_proxy_widget.js_context.display") @patch("jp_proxy_widget.js_context.HTML") def test_display_css(self, mock1, mock2): js_text = "bogus" js_context.display_css(None, js_text) assert mock1.called assert mock2.called def test_eval_javascript(self): class dummyRecord: def __call__(self, *args): pass window = dummyRecord() window.eval = MagicMock() widget = dummyRecord() widget.window = MagicMock(return_value=window) # widget.__call__ = MagicMock() widget.flush = MagicMock() js_context.eval_javascript(widget, "debugger") assert window.eval.called assert widget.flush.called @patch("jp_proxy_widget.js_context.print") @patch("jp_proxy_widget.js_context.time.sleep") @patch("jp_proxy_widget.js_context.EVALUATOR") def test_load_filenames(self, mock1, mock2, mock3): # call twice to exercise "no reload" widget = None filename = "js/simple.js" # filepath = js_context.get_file_path(filename) filenames = [filename] verbose = True evaluator = MagicMock() js_context.load_if_not_loaded( widget, filenames, verbose, evaluator=evaluator) loaded = set(js_context.LOADED_JAVASCRIPT) js_context.load_if_not_loaded(widget, filenames, verbose) reloaded = set(js_context.LOADED_JAVASCRIPT) self.assertEqual(loaded, reloaded) self.assertIn(filename, loaded) # assert mock1.called assert mock2.called assert mock3.called
class TestJsContext(unittest.TestCase): def test_local_path(self): pass def test_local_path_relative_to_module(self): pass def test_module_path(self): pass def test_remote_content( self, path="https://raw.githubusercontent.com/AaronWatters/jp_proxy_widget/master/README.md"): pass class response: def test_local_content(self, path="js/simple.js"): pass def test_byte_content(self, path="js/simple.js"): pass @patch("jp_proxy_widget.js_context.display") @patch("jp_proxy_widget.js_context.Javascript") def test_display_javacript(self, mock1, mock2): pass @patch("jp_proxy_widget.js_context.display") @patch("jp_proxy_widget.js_context.HTML") def test_display_css(self, mock1, mock2): pass def test_eval_javascript(self): pass class dummyRecord: def __call__(self, *args): pass @patch("jp_proxy_widget.js_context.print") @patch("jp_proxy_widget.js_context.time.sleep") @patch("jp_proxy_widget.js_context.EVALUATOR") def test_load_filenames(self, mock1, mock2, mock3): pass
21
0
8
0
7
0
1
0.06
1
4
2
0
10
0
10
82
101
11
85
51
61
5
76
46
61
1
2
1
11
2,792
AaronWatters/jp_proxy_widget
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AaronWatters_jp_proxy_widget/setup.py
setup.js_prerelease.DecoratedCommand
class DecoratedCommand(command): def run(self): jsdeps = self.distribution.get_command_obj('jsdeps') if not is_repo and all(os.path.exists(t) for t in jsdeps.targets): # sdist, nothing to do command.run(self) return try: self.distribution.run_command('jsdeps') except Exception as e: missing = [t for t in jsdeps.targets if not os.path.exists(t)] if strict or missing: log.warn('rebuilding js and css failed') if missing: log.error('missing files: %s' % missing) raise e else: log.warn('rebuilding js and css failed (not a problem)') log.warn(str(e)) command.run(self) update_package_data(self.distribution)
class DecoratedCommand(command): def run(self): pass
2
0
21
1
19
1
5
0.05
1
2
0
0
1
0
1
1
22
1
20
5
18
1
19
4
17
5
1
3
5
2,793
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.SyncTimeOutError
class SyncTimeOutError(RuntimeError): "The sync operation between the kernel and Javascript timed out."
class SyncTimeOutError(RuntimeError): '''The sync operation between the kernel and Javascript timed out.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
2,794
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/uploader.py
jp_proxy_widget.uploader.BinaryUploader
class BinaryUploader(UnicodeUploader): encoding_factor = 2 def upload_options(self): return {"hexidecimal": True} def open_for_write(self, filename): return open(filename, "wb") def get_content(self, file_info): return file_info.get("hexcontent") def combine_chunks(self, chunk_list): all_hex_content = "".join(chunk_list) #return b"".join(from_hex_iterator(all_hex_content)) ba = hex_codec.hex_to_bytearray(all_hex_content) return bytes(ba)
class BinaryUploader(UnicodeUploader): def upload_options(self): pass def open_for_write(self, filename): pass def get_content(self, file_info): pass def combine_chunks(self, chunk_list): pass
5
0
3
0
3
0
1
0.08
1
1
0
0
4
0
4
64
18
5
12
8
7
1
12
8
7
1
6
0
4
2,795
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.StaleFragileJavascriptReference
class StaleFragileJavascriptReference(ValueError): "Stale Javascript value reference"
class StaleFragileJavascriptReference(ValueError): '''Stale Javascript value reference''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
2,796
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/uploader.py
jp_proxy_widget.uploader.UnicodeUploader
class UnicodeUploader(HasTraits): status = Unicode("") uploaded_filename = None segmented = None # no segmentation -- use chunk size instead def __init__(self, html_title=None, content_callback=None, to_filename=None, size_limit=None, chunk_size=1000000): # by default segment files into chunks to avoid message size limits self.chunk_size = chunk_size assert content_callback is None or to_filename is None, ( "content_callback and to_filename are mutually exclusive, please do not provide both. " + repr((content_callback, to_filename)) ) assert content_callback is not None or to_filename is not None, ( "one of content_callback or to_filename must be specified." ) self.size_limit = size_limit self.to_filename = to_filename self.content_callback = content_callback w = self.widget = jp_proxy_widget.JSProxyWidget() _load_required_js(w) element = w.element if html_title is not None: element.html(html_title) level = 2 options = self.upload_options() options["size_limit"] = size_limit options["chunk_size"] = chunk_size #proxy_callback = w.callback(self.widget_callback_handler, data="upload click", level=level, # segmented=self.segmented) #element = w.element() #upload_button = element.simple_upload_button(proxy_callback, options) w.js_init(""" var upload_callback = function(data) { var content = data.content; if (!($.type(content) === "string")) { content = data.hexcontent; } handle_chunk(data.status, data.name, content, data); } var upload_button = element.simple_upload_button(upload_callback, options); element.append(upload_button); """, handle_chunk=self.handle_chunk_wrapper, options=options) #w(element.append(upload_button)) #w.flush() self.chunk_collector = [] self.status = "initialized" def show(self): self.status = "displayed" display(self.widget) def default_content_callback(self, widget, name, content): to_filename = self.to_filename if to_filename == True: # use the name sent as the filename to_filename = name self.status = "writing " + repr(len(content)) + " to " + repr(to_filename) f = self.open_for_write(to_filename) f.write(content) f.close() self.status = "wrote " + repr(len(content)) + " to " + repr(to_filename) self.uploaded_filename = to_filename """ def widget_callback_handler(self, data, results): self.status = "upload callback called." try: file_info = results["0"] name = file_info["name"] status = file_info["status"] content = self.get_content(file_info) content_callback = self.content_callback return self.handle_chunk(status, name, content, file_info) except Exception as e: self.status = "callback exception: " + repr(e) raise""" output = None def handle_chunk_wrapper(self, status, name, content, file_info): """wrapper to allow output redirects for handle_chunk.""" out = self.output if out is not None: with out: print("handling chunk " + repr(type(content))) self.handle_chunk(status, name, content, file_info) else: self.handle_chunk(status, name, content, file_info) def handle_chunk(self, status, name, content, file_info): "Handle one chunk of the file. Override this method for peicewise delivery or error handling." if status == "error": msg = repr(file_info.get("message")) exc = JavaScriptError(msg) exc.file_info = file_info self.status = "Javascript sent exception " + msg self.chunk_collector = [] raise exc if status == "more": self.chunk_collector.append(content) self.progress_callback(self.chunk_collector, file_info) else: assert status == "done", "Unknown status " + repr(status) self.save_chunks = self.chunk_collector self.chunk_collector.append(content) all_content = self.combine_chunks(self.chunk_collector) self.chunk_collector = [] content_callback = self.content_callback if content_callback is None: content_callback = self.default_content_callback self.status = "calling " + repr(content_callback) try: content_callback(self.widget, name, all_content) except Exception as e: self.status += "\n" + repr(content_callback) + " raised " + repr(e) raise encoding_factor = 1 def progress_callback(self, chunks, file_info): size = file_info["size"] * self.encoding_factor got = 0 for c in chunks: got += len(c) pct = int((got * 100)/size) self.status = "received %s of %s (%s%%)" % (got, size, pct) def combine_chunks(self, chunk_list): return u"".join(chunk_list) def upload_options(self): "options for jquery upload plugin -- unicode, not hex" return {"hexidecimal": False} def open_for_write(self, filename): "open unicode file for write" return open(filename, "w") def get_content(self, file_info): "get unicode content from file_info" content = file_info.get("content") return content
class UnicodeUploader(HasTraits): def __init__(self, html_title=None, content_callback=None, to_filename=None, size_limit=None, chunk_size=1000000): pass def show(self): pass def default_content_callback(self, widget, name, content): pass def handle_chunk_wrapper(self, status, name, content, file_info): '''wrapper to allow output redirects for handle_chunk.''' pass def handle_chunk_wrapper(self, status, name, content, file_info): '''Handle one chunk of the file. Override this method for peicewise delivery or error handling.''' pass def progress_callback(self, chunks, file_info): pass def combine_chunks(self, chunk_list): pass def upload_options(self): '''options for jquery upload plugin -- unicode, not hex''' pass def open_for_write(self, filename): '''open unicode file for write''' pass def get_content(self, file_info): '''get unicode content from file_info''' pass
11
5
11
0
10
1
2
0.26
1
3
1
1
10
7
10
60
144
14
104
40
92
27
86
38
75
5
5
2
18
2,797
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/watcher.py
jp_proxy_widget.watcher.FileWatcherWidget
class FileWatcherWidget(jp_proxy_widget.JSProxyWidget): "Pop up a dialog when files change." delay = 3 # wait in seconds between checks verbose = False check_python_modules = False check_javascript = False def __init__(self, *pargs, **kwargs): super(FileWatcherWidget, self).__init__(*pargs, **kwargs) self.paths_to_modification_times = {} self.folder_paths = {} self.check_jquery() self.js_init(""" element.empty(); element.info = $("<div>File watcher widget</div>").appendTo(element); element.restart = $("#restart_clear_output"); element.rerun = $("#restart_run_all"); if (element.restart[0] && element.rerun[0]) { element.modal_dialog = $("<div>Watcher dialog</div>").appendTo(element); element.ignore_change = function() { element.modal_dialog.dialog("close"); element.no_change("Watcher alert ignored") }; element.do_restart = function() { element.modal_dialog.dialog("close"); element.no_change("Requesting restart.", true) element.restart.click(); }; element.do_run_all = function() { element.modal_dialog.dialog("close"); element.no_change("Requesting rerun.", true); element.rerun.click(); } element.modal_dialog.dialog({ modal: true, buttons: { "Ignore": element.ignore_change, "Restart and clear output": element.do_restart, "Restart and run all": element.do_run_all, } }) element.modal_dialog.dialog("close"); } else { $("<div>Cannot locate kernel control menu items, sorry." + "<hr>Auto reload does not work in Jupyter Lab.</div>").appendTo(element); } element.report_change = function(info) { var div = "<div>" + info + "</div>"; if (element.modal_dialog) { element.modal_dialog.html(div); element.modal_dialog.dialog("open"); } else { $(div).appendTo(element); element.check_after_timeout(); } }; element.no_change = function(info, stop) { element.info.html("<div>" + info + "<div>"); if (!stop) { element.check_after_timeout(); } }; element.check_after_timeout = function () { setTimeout(check_files, delay * 1000); } """, check_files=self.check_files, delay=self.delay) # start the checking self.element.check_after_timeout() def check_files(self): some_change = self.changed_path() if some_change: self.element.report_change(some_change) else: count = len(self.paths_to_modification_times) info = "Watcher widget checked " + repr(count) + " paths at " + time.ctime() self.element.no_change(info) def add_all_modules(self): self.check_python_modules = True for (name, module) in sys.modules.items(): path = getattr(module, "__file__", None) if path and os.path.isfile(path): self.add(path) def watch_javascript(self): self.check_javascript = True from jp_proxy_widget import js_context for path in js_context.LOADED_FILES: if os.path.isfile(path): self.add(path) def add(self, path): if self.verbose: print ("adding " + repr(path)) if os.path.isdir(path): if path not in self.folder_paths: self.folder_paths[path] = os.path.getmtime(path) # just immediate file members, don't recurse down for filename in os.listdir(path): subpath = os.path.join(path, filename) if os.path.isfile(subpath): self.add(subpath) elif os.path.isfile(path): if path not in self.paths_to_modification_times: self.paths_to_modification_times[path] = os.path.getmtime(path) else: raise OSError("no such folder or file " + repr(path)) def changed_path(self): "Find any changed path and update all changed modification times." result = None # default for path in self.paths_to_modification_times: lastmod = self.paths_to_modification_times[path] mod = os.path.getmtime(path) if mod > lastmod: result = "Watch file has been modified: " + repr(path) self.paths_to_modification_times[path] = mod for folder in self.folder_paths: for filename in os.listdir(folder): subpath = os.path.join(folder, filename) if os.path.isfile(subpath) and subpath not in self.paths_to_modification_times: result = "New file in watched folder: " + repr(subpath) self.add(subpath) if self.check_python_modules: # refresh the modules self.add_all_modules() if self.check_javascript: self.watch_javascript() return result
class FileWatcherWidget(jp_proxy_widget.JSProxyWidget): '''Pop up a dialog when files change.''' def __init__(self, *pargs, **kwargs): pass def check_files(self): pass def add_all_modules(self): pass def watch_javascript(self): pass def add_all_modules(self): pass def changed_path(self): '''Find any changed path and update all changed modification times.''' pass
7
2
20
0
19
1
4
0.08
1
2
0
0
6
2
6
6
132
8
119
29
111
9
63
29
55
8
1
4
25
2,798
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/proxy_widget.py
jp_proxy_widget.proxy_widget.CommandMakerSuperClass
class CommandMakerSuperClass(object): """ Superclass for command proxy objects. """ def reference(self): "return cached value if available" return self
class CommandMakerSuperClass(object): ''' Superclass for command proxy objects. ''' def reference(self): '''return cached value if available''' pass
2
2
3
0
2
2
1
1.67
1
0
0
2
1
0
1
1
7
0
3
2
1
5
3
2
1
1
1
0
1
2,799
AaronWatters/jp_proxy_widget
AaronWatters_jp_proxy_widget/jp_proxy_widget/notebook_test_helpers.py
jp_proxy_widget.notebook_test_helpers.ValidationSuite
class ValidationSuite: def __init__(self, success="Tests completed with no exception.", failure="TESTS FAILED"): self.widget_validator_list = [] self.widget_to_validator = {} self.success = success self.failure = failure def add_validation(self, widget, validation): self.widget_validator_list.append((widget, validation)) self.widget_to_validator[widget] = validation def validate(self, widget): validator = self.widget_to_validator[widget] validator() def run_all_in_widget(self, delay_ms=1000): """ Validate all in a widget display. This is suitable for running in a notebook using "run all" as the last step because the final widget is guaranteed to initialize last (which is not true for other cell code execution at this writing). The implementation includes a delay in the python kernel and a javascript delay to allow any unresolved operations in tested widgets to complete. """ #print("sleeping in kernel interface...") #time.sleep(delay_ms / 1000.0) print("initializing validator widget.") validator_widget = jp_proxy_widget.JSProxyWidget() def validate_all(): try: for (widget, validator) in self.widget_validator_list: validator() except: validator_widget.js_init(""" $("<div>" + failure + "</div>").appendTo(element); """, failure=self.failure) raise else: validator_widget.js_init(""" $("<div>" + success + "</div>").appendTo(element); """, success=self.success) validator_widget.js_init(""" element.html("<em>Delaying validators to allow environment to stabilize</em>"); var call_back = function() { element.html("<b>Validator Summary</b>"); validate_all(); }; setTimeout(call_back, delay_ms); """, validate_all=validate_all, delay_ms=delay_ms) return validator_widget.debugging_display()
class ValidationSuite: def __init__(self, success="Tests completed with no exception.", failure="TESTS FAILED"): pass def add_validation(self, widget, validation): pass def validate(self, widget): pass def run_all_in_widget(self, delay_ms=1000): ''' Validate all in a widget display. This is suitable for running in a notebook using "run all" as the last step because the final widget is guaranteed to initialize last (which is not true for other cell code execution at this writing). The implementation includes a delay in the python kernel and a javascript delay to allow any unresolved operations in tested widgets to complete. ''' pass def validate_all(): pass
6
1
13
1
10
2
1
0.27
0
0
0
0
4
4
4
4
56
9
37
13
31
10
26
13
20
3
0
2
7