hexsha
stringlengths 40
40
| size
int64 4
1.02M
| ext
stringclasses 8
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
209
| max_stars_repo_name
stringlengths 5
121
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
209
| max_issues_repo_name
stringlengths 5
121
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
209
| max_forks_repo_name
stringlengths 5
121
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 4
1.02M
| avg_line_length
float64 1.07
66.1k
| max_line_length
int64 4
266k
| alphanum_fraction
float64 0.01
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1aa30d3ae4ab2cc760c49678cc9092fba7d4f66
| 2,593
|
py
|
Python
|
presqt/targets/curate_nd/tests/views/resource/test_resource_collection.py
|
djordjetrajkovic/presqt
|
8424b61b1c5b8d29de74c7a333889d9e9eb7aee8
|
[
"Apache-2.0"
] | 3
|
2019-01-29T19:45:25.000Z
|
2020-12-01T18:24:51.000Z
|
presqt/targets/curate_nd/tests/views/resource/test_resource_collection.py
|
djordjetrajkovic/presqt
|
8424b61b1c5b8d29de74c7a333889d9e9eb7aee8
|
[
"Apache-2.0"
] | 419
|
2018-09-13T23:11:15.000Z
|
2021-09-22T17:49:00.000Z
|
presqt/targets/curate_nd/tests/views/resource/test_resource_collection.py
|
djordjetrajkovic/presqt
|
8424b61b1c5b8d29de74c7a333889d9e9eb7aee8
|
[
"Apache-2.0"
] | 2
|
2020-04-10T08:19:41.000Z
|
2021-01-04T15:29:42.000Z
|
import os
from django.test import SimpleTestCase
from rest_framework.reverse import reverse
from rest_framework.test import APIClient
from unittest import skip
class TestResourceCollection(SimpleTestCase):
"""
Test the 'api_v1/targets/curate_nd/resources' endpoint's GET method.
Testing Curate ND integration.
"""
def setUp(self):
self.client = APIClient()
self.header = {'HTTP_PRESQT_SOURCE_TOKEN': os.environ['CURATE_ND_TEST_TOKEN']}
@skip('Curate Test Server Issues')
def test_success_curate_nd(self):
"""
Return a 200 if the GET method is successful when grabbing CurateND resources.
"""
url = reverse('resource_collection', kwargs={'target_name': 'curate_nd'})
response = self.client.get(url, **self.header)
# Verify the status code
self.assertEqual(response.status_code, 200)
# Verify the dict keys match what we expect,
# Verify the dict keys match what we expect
keys = ['kind', 'kind_name', 'id', 'container', 'title', 'links']
for data in response.data['resources']:
self.assertListEqual(keys, list(data.keys()))
# Verify the count of resource objects is what we expect.
self.assertEqual(37, len(response.data['resources']))
for data in response.data:
self.assertEqual(len(data['links']), 1)
@skip('Curate Test Server Issues')
def test_error_400_missing_token_curate_nd(self):
"""
Return a 400 if the GET method fails because the presqt-source-token was not provided.
"""
url = reverse('resource_collection', kwargs={'target_name': 'curate_nd'})
response = self.client.get(url)
# Verify the error status code and message
self.assertEqual(response.status_code, 400)
self.assertEqual(response.data,
{'error': "'presqt-source-token' missing in the request headers."})
@skip('Curate Test Server Issues')
def test_error_401_invalid_token_curate_nd(self):
"""
Return a 401 if the token provided is not a valid token.
"""
client = APIClient()
header = {'HTTP_PRESQT_SOURCE_TOKEN': 'eggyboi'}
url = reverse('resource_collection', kwargs={'target_name': 'curate_nd'})
response = client.get(url, **header)
# Verify the error status code and message.
self.assertEqual(response.status_code, 401)
self.assertEqual(response.data,
{'error': "Token is invalid. Response returned a 401 status code."})
| 40.515625
| 94
| 0.650983
|
22eb7ec04ddb186908f6b340cba141e70d46f969
| 712
|
py
|
Python
|
dev_6/authapp/forms.py
|
EvgenDEP1/dev-6
|
bf01ece91a0bb0efd6be99661c0cc2c59162b1c6
|
[
"Apache-2.0"
] | null | null | null |
dev_6/authapp/forms.py
|
EvgenDEP1/dev-6
|
bf01ece91a0bb0efd6be99661c0cc2c59162b1c6
|
[
"Apache-2.0"
] | null | null | null |
dev_6/authapp/forms.py
|
EvgenDEP1/dev-6
|
bf01ece91a0bb0efd6be99661c0cc2c59162b1c6
|
[
"Apache-2.0"
] | null | null | null |
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, item in self.fields.items():
item.widget.attrs['class'] = f'form-control {name}'
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'password1', 'password2')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, item in self.fields.items():
item.widget.attrs['class'] = f'form-control {name}'
item.help_text = ''
| 32.363636
| 74
| 0.639045
|
e7e918ab05d28d9b33aea7fc56f2f3f5d91c1e0c
| 35,827
|
py
|
Python
|
test/test_tag_matcher.py
|
pi-sjp/behave-parallel
|
35e745828f9fd6c796a8980104a277a0028070cb
|
[
"BSD-2-Clause"
] | 5
|
2019-01-15T18:49:16.000Z
|
2020-02-21T20:24:39.000Z
|
test/test_tag_matcher.py
|
pi-sjp/behave-parallel
|
35e745828f9fd6c796a8980104a277a0028070cb
|
[
"BSD-2-Clause"
] | 6
|
2019-04-26T19:34:34.000Z
|
2020-06-03T21:49:13.000Z
|
test/test_tag_matcher.py
|
pi-sjp/behave-parallel
|
35e745828f9fd6c796a8980104a277a0028070cb
|
[
"BSD-2-Clause"
] | 9
|
2019-04-23T19:43:41.000Z
|
2020-05-12T09:17:27.000Z
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from behave.tag_matcher import *
from mock import Mock
from unittest import TestCase
import warnings
# -- REQUIRES: pytest
# import pytest
class Traits4ActiveTagMatcher(object):
TagMatcher = ActiveTagMatcher
value_provider = {
"foo": "alice",
"bar": "BOB",
}
category1_enabled_tag = TagMatcher.make_category_tag("foo", "alice")
category1_disabled_tag = TagMatcher.make_category_tag("foo", "bob")
category1_disabled_tag2 = TagMatcher.make_category_tag("foo", "charly")
category1_similar_tag = TagMatcher.make_category_tag("foo", "alice2")
category2_enabled_tag = TagMatcher.make_category_tag("bar", "BOB")
category2_disabled_tag = TagMatcher.make_category_tag("bar", "CHARLY")
category2_similar_tag = TagMatcher.make_category_tag("bar", "BOB2")
unknown_category_tag = TagMatcher.make_category_tag("UNKNOWN", "one")
# -- NEGATED TAGS:
category1_not_enabled_tag = \
TagMatcher.make_category_tag("foo", "alice", "not_active")
category1_not_enabled_tag2 = \
TagMatcher.make_category_tag("foo", "alice", "not")
category1_not_disabled_tag = \
TagMatcher.make_category_tag("foo", "bob", "not_active")
category1_negated_similar_tag1 = \
TagMatcher.make_category_tag("foo", "alice2", "not_active")
active_tags1 = [
category1_enabled_tag, category1_disabled_tag, category1_similar_tag,
category1_not_enabled_tag, category1_not_enabled_tag2,
]
active_tags2 = [
category2_enabled_tag, category2_disabled_tag, category2_similar_tag,
]
active_tags = active_tags1 + active_tags2
# -- REQUIRES: pytest
# class TestActiveTagMatcher2(object):
# TagMatcher = ActiveTagMatcher
# traits = Traits4ActiveTagMatcher
#
# @classmethod
# def make_tag_matcher(cls):
# value_provider = {
# "foo": "alice",
# "bar": "BOB",
# }
# tag_matcher = cls.TagMatcher(value_provider)
# return tag_matcher
#
# @pytest.mark.parametrize("case, expected_len, tags", [
# ("case: Two enabled tags", 2,
# [traits.category1_enabled_tag, traits.category2_enabled_tag]),
# ("case: Active enabled and normal tag", 1,
# [traits.category1_enabled_tag, "foo"]),
# ("case: Active disabled and normal tag", 1,
# [traits.category1_disabled_tag, "foo"]),
# ("case: Normal and active negated tag", 1,
# ["foo", traits.category1_not_enabled_tag]),
# ("case: Two normal tags", 0,
# ["foo", "bar"]),
# ])
# def test_select_active_tags__with_two_tags(self, case, expected_len, tags):
# tag_matcher = self.make_tag_matcher()
# selected = tag_matcher.select_active_tags(tags)
# selected = list(selected)
# assert len(selected) == expected_len, case
#
# @pytest.mark.parametrize("case, expected, tags", [
# # -- GROUP: With positive logic (non-negated tags)
# ("case P00: 2 disabled tags", True,
# [ traits.category1_disabled_tag, traits.category2_disabled_tag]),
# ("case P01: disabled and enabled tag", True,
# [ traits.category1_disabled_tag, traits.category2_enabled_tag]),
# ("case P10: enabled and disabled tag", True,
# [ traits.category1_enabled_tag, traits.category2_disabled_tag]),
# ("case P11: 2 enabled tags", False, # -- SHOULD-RUN
# [ traits.category1_enabled_tag, traits.category2_enabled_tag]),
# # -- GROUP: With negated tag
# ("case N00: not-enabled and disabled tag", True,
# [ traits.category1_not_enabled_tag, traits.category2_disabled_tag]),
# ("case N01: not-enabled and enabled tag", True,
# [ traits.category1_not_enabled_tag, traits.category2_enabled_tag]),
# ("case N10: not-disabled and disabled tag", True,
# [ traits.category1_not_disabled_tag, traits.category2_disabled_tag]),
# ("case N11: not-disabled and enabled tag", False, # -- SHOULD-RUN
# [ traits.category1_not_disabled_tag, traits.category2_enabled_tag]),
# # -- GROUP: With unknown category
# ("case U0x: disabled and unknown tag", True,
# [ traits.category1_disabled_tag, traits.unknown_category_tag]),
# ("case U1x: enabled and unknown tag", False, # -- SHOULD-RUN
# [ traits.category1_enabled_tag, traits.unknown_category_tag]),
# ])
# def test_should_exclude_with__combinations_of_2_categories(self, case, expected, tags):
# tag_matcher = self.make_tag_matcher()
# actual_result = tag_matcher.should_exclude_with(tags)
# assert expected == actual_result, case
#
# @pytest.mark.parametrize("case, expected, tags", [
# # -- GROUP: With positive logic (non-negated tags)
# ("case P00: 2 disabled tags", True,
# [ traits.category1_disabled_tag, traits.category1_disabled_tag2]),
# ("case P01: disabled and enabled tag", True,
# [ traits.category1_disabled_tag, traits.category1_enabled_tag]),
# ("case P10: enabled and disabled tag", True,
# [ traits.category1_enabled_tag, traits.category1_disabled_tag]),
# ("case P11: 2 enabled tags (same)", False, # -- SHOULD-RUN
# [ traits.category1_enabled_tag, traits.category1_enabled_tag]),
# # -- GROUP: With negated tag
# ("case N00: not-enabled and disabled tag", True,
# [ traits.category1_not_enabled_tag, traits.category1_disabled_tag]),
# ("case N01: not-enabled and enabled tag", True,
# [ traits.category1_not_enabled_tag, traits.category1_enabled_tag]),
# ("case N10: not-disabled and disabled tag", True,
# [ traits.category1_not_disabled_tag, traits.category1_disabled_tag]),
# ("case N11: not-disabled and enabled tag", False, # -- SHOULD-RUN
# [ traits.category1_not_disabled_tag, traits.category1_enabled_tag]),
# ])
# def test_should_exclude_with__combinations_with_same_category(self,
# case, expected, tags):
# tag_matcher = self.make_tag_matcher()
# actual_result = tag_matcher.should_exclude_with(tags)
# assert expected == actual_result, case
class TestActiveTagMatcher1(TestCase):
TagMatcher = ActiveTagMatcher
traits = Traits4ActiveTagMatcher
@classmethod
def make_tag_matcher(cls):
tag_matcher = cls.TagMatcher(cls.traits.value_provider)
return tag_matcher
def setUp(self):
self.tag_matcher = self.make_tag_matcher()
def test_select_active_tags__basics(self):
active_tag = "active.with_CATEGORY=VALUE"
tags = ["foo", active_tag, "bar"]
selected = list(self.tag_matcher.select_active_tags(tags))
self.assertEqual(len(selected), 1)
selected_tag, selected_match = selected[0]
self.assertEqual(selected_tag, active_tag)
def test_select_active_tags__matches_tag_parts(self):
tags = ["active.with_CATEGORY=VALUE"]
selected = list(self.tag_matcher.select_active_tags(tags))
self.assertEqual(len(selected), 1)
selected_tag, selected_match = selected[0]
self.assertEqual(selected_match.group("prefix"), "active")
self.assertEqual(selected_match.group("category"), "CATEGORY")
self.assertEqual(selected_match.group("value"), "VALUE")
def test_select_active_tags__finds_tag_with_any_valid_tag_prefix(self):
TagMatcher = self.TagMatcher
for tag_prefix in TagMatcher.tag_prefixes:
tag = TagMatcher.make_category_tag("foo", "alice", tag_prefix)
tags = [ tag ]
selected = self.tag_matcher.select_active_tags(tags)
selected = list(selected)
self.assertEqual(len(selected), 1)
selected_tag0 = selected[0][0]
self.assertEqual(selected_tag0, tag)
self.assertTrue(selected_tag0.startswith(tag_prefix))
def test_select_active_tags__ignores_invalid_active_tags(self):
invalid_active_tags = [
("foo.alice", "case: Normal tag"),
("with_foo=alice", "case: Subset of an active tag"),
("ACTIVE.with_foo.alice", "case: Wrong tag_prefix (uppercase)"),
("only.with_foo.alice", "case: Wrong value_separator"),
]
for invalid_tag, case in invalid_active_tags:
tags = [ invalid_tag ]
selected = self.tag_matcher.select_active_tags(tags)
selected = list(selected)
self.assertEqual(len(selected), 0, case)
def test_select_active_tags__with_two_tags(self):
# XXX-JE-DUPLICATED:
traits = self.traits
test_patterns = [
("case: Two enabled tags",
[traits.category1_enabled_tag, traits.category2_enabled_tag]),
("case: Active enabled and normal tag",
[traits.category1_enabled_tag, "foo"]),
("case: Active disabled and normal tag",
[traits.category1_disabled_tag, "foo"]),
("case: Active negated and normal tag",
[traits.category1_not_enabled_tag, "foo"]),
]
for case, tags in test_patterns:
selected = self.tag_matcher.select_active_tags(tags)
selected = list(selected)
self.assertTrue(len(selected) >= 1, case)
def test_should_exclude_with__returns_false_with_enabled_tag(self):
traits = self.traits
tags1 = [ traits.category1_enabled_tag ]
tags2 = [ traits.category2_enabled_tag ]
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags1))
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags2))
def test_should_exclude_with__returns_false_with_disabled_tag_and_more(self):
# -- NOTE: Need 1+ enabled active-tags of same category => ENABLED
traits = self.traits
test_patterns = [
([ traits.category1_enabled_tag, traits.category1_disabled_tag ], "case: first"),
([ traits.category1_disabled_tag, traits.category1_enabled_tag ], "case: last"),
([ "foo", traits.category1_enabled_tag, traits.category1_disabled_tag, "bar" ], "case: middle"),
]
enabled = True # EXPECTED
for tags, case in test_patterns:
self.assertEqual(not enabled, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_true_with_other_tag(self):
traits = self.traits
tags = [ traits.category1_disabled_tag ]
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__returns_true_with_other_tag_and_more(self):
traits = self.traits
test_patterns = [
([ traits.category1_disabled_tag, "foo" ], "case: first"),
([ "foo", traits.category1_disabled_tag ], "case: last"),
([ "foo", traits.category1_disabled_tag, "bar" ], "case: middle"),
]
for tags, case in test_patterns:
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_true_with_similar_tag(self):
traits = self.traits
tags = [ traits.category1_similar_tag ]
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__returns_true_with_similar_and_more(self):
traits = self.traits
test_patterns = [
([ traits.category1_similar_tag, "foo" ], "case: first"),
([ "foo", traits.category1_similar_tag ], "case: last"),
([ "foo", traits.category1_similar_tag, "bar" ], "case: middle"),
]
for tags, case in test_patterns:
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_false_without_category_tag(self):
test_patterns = [
([ ], "case: No tags"),
([ "foo" ], "case: One tag"),
([ "foo", "bar" ], "case: Two tags"),
]
for tags, case in test_patterns:
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_false_with_unknown_category_tag(self):
"""Tags from unknown categories, not supported by value_provider,
should not be excluded.
"""
traits = self.traits
tags = [ traits.unknown_category_tag ]
self.assertEqual("active.with_UNKNOWN=one", traits.unknown_category_tag)
self.assertEqual(None, self.tag_matcher.value_provider.get("UNKNOWN"))
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__combinations_of_2_categories(self):
# XXX-JE-DUPLICATED:
traits = self.traits
test_patterns = [
("case P00: 2 disabled category tags", True,
[ traits.category1_disabled_tag, traits.category2_disabled_tag]),
("case P01: disabled and enabled category tags", True,
[ traits.category1_disabled_tag, traits.category2_enabled_tag]),
("case P10: enabled and disabled category tags", True,
[ traits.category1_enabled_tag, traits.category2_disabled_tag]),
("case P11: 2 enabled category tags", False, # -- SHOULD-RUN
[ traits.category1_enabled_tag, traits.category2_enabled_tag]),
# -- SPECIAL CASE: With negated category
("case N00: not-enabled and disabled category tags", True,
[ traits.category1_not_enabled_tag, traits.category2_disabled_tag]),
("case N01: not-enabled and enabled category tags", True,
[ traits.category1_not_enabled_tag, traits.category2_enabled_tag]),
("case N10: not-disabled and disabled category tags", True,
[ traits.category1_not_disabled_tag, traits.category2_disabled_tag]),
("case N11: not-enabled and enabled category tags", False, # -- SHOULD-RUN
[ traits.category1_not_disabled_tag, traits.category2_enabled_tag]),
# -- SPECIAL CASE: With unknown category
("case 0x: disabled and unknown category tags", True,
[ traits.category1_disabled_tag, traits.unknown_category_tag]),
("case 1x: enabled and unknown category tags", False, # SHOULD-RUN
[ traits.category1_enabled_tag, traits.unknown_category_tag]),
]
for case, expected, tags in test_patterns:
actual_result = self.tag_matcher.should_exclude_with(tags)
self.assertEqual(expected, actual_result,
"%s: tags=%s" % (case, tags))
def test_should_run_with__negates_result_of_should_exclude_with(self):
traits = self.traits
test_patterns = [
([ ], "case: No tags"),
([ "foo" ], "case: One non-category tag"),
([ "foo", "bar" ], "case: Two non-category tags"),
([ traits.category1_enabled_tag ], "case: enabled tag"),
([ traits.category1_enabled_tag, traits.category1_disabled_tag ], "case: enabled and other tag"),
([ traits.category1_enabled_tag, "foo" ], "case: enabled and foo tag"),
([ traits.category1_disabled_tag ], "case: other tag"),
([ traits.category1_disabled_tag, "foo" ], "case: other and foo tag"),
([ traits.category1_similar_tag ], "case: similar tag"),
([ "foo", traits.category1_similar_tag ], "case: foo and similar tag"),
]
for tags, case in test_patterns:
result1 = self.tag_matcher.should_run_with(tags)
result2 = self.tag_matcher.should_exclude_with(tags)
self.assertEqual(result1, not result2, "%s: tags=%s" % (case, tags))
self.assertEqual(not result1, result2, "%s: tags=%s" % (case, tags))
class TestPredicateTagMatcher(TestCase):
def test_exclude_with__mechanics(self):
predicate_function_blueprint = lambda tags: False
predicate_function = Mock(predicate_function_blueprint)
predicate_function.return_value = True
tag_matcher = PredicateTagMatcher(predicate_function)
tags = [ "foo", "bar" ]
self.assertEqual(True, tag_matcher.should_exclude_with(tags))
predicate_function.assert_called_once_with(tags)
self.assertEqual(True, predicate_function(tags))
def test_should_exclude_with__returns_true_when_predicate_is_true(self):
predicate_always_true = lambda tags: True
tag_matcher1 = PredicateTagMatcher(predicate_always_true)
tags = [ "foo", "bar" ]
self.assertEqual(True, tag_matcher1.should_exclude_with(tags))
self.assertEqual(True, predicate_always_true(tags))
def test_should_exclude_with__returns_true_when_predicate_is_true2(self):
# -- CASE: Use predicate function instead of lambda.
def predicate_contains_foo(tags):
return any(x == "foo" for x in tags)
tag_matcher2 = PredicateTagMatcher(predicate_contains_foo)
tags = [ "foo", "bar" ]
self.assertEqual(True, tag_matcher2.should_exclude_with(tags))
self.assertEqual(True, predicate_contains_foo(tags))
def test_should_exclude_with__returns_false_when_predicate_is_false(self):
predicate_always_false = lambda tags: False
tag_matcher1 = PredicateTagMatcher(predicate_always_false)
tags = [ "foo", "bar" ]
self.assertEqual(False, tag_matcher1.should_exclude_with(tags))
self.assertEqual(False, predicate_always_false(tags))
class TestPredicateTagMatcher(TestCase):
def test_exclude_with__mechanics(self):
predicate_function_blueprint = lambda tags: False
predicate_function = Mock(predicate_function_blueprint)
predicate_function.return_value = True
tag_matcher = PredicateTagMatcher(predicate_function)
tags = [ "foo", "bar" ]
self.assertEqual(True, tag_matcher.should_exclude_with(tags))
predicate_function.assert_called_once_with(tags)
self.assertEqual(True, predicate_function(tags))
def test_should_exclude_with__returns_true_when_predicate_is_true(self):
predicate_always_true = lambda tags: True
tag_matcher1 = PredicateTagMatcher(predicate_always_true)
tags = [ "foo", "bar" ]
self.assertEqual(True, tag_matcher1.should_exclude_with(tags))
self.assertEqual(True, predicate_always_true(tags))
def test_should_exclude_with__returns_true_when_predicate_is_true2(self):
# -- CASE: Use predicate function instead of lambda.
def predicate_contains_foo(tags):
return any(x == "foo" for x in tags)
tag_matcher2 = PredicateTagMatcher(predicate_contains_foo)
tags = [ "foo", "bar" ]
self.assertEqual(True, tag_matcher2.should_exclude_with(tags))
self.assertEqual(True, predicate_contains_foo(tags))
def test_should_exclude_with__returns_false_when_predicate_is_false(self):
predicate_always_false = lambda tags: False
tag_matcher1 = PredicateTagMatcher(predicate_always_false)
tags = [ "foo", "bar" ]
self.assertEqual(False, tag_matcher1.should_exclude_with(tags))
self.assertEqual(False, predicate_always_false(tags))
class TestCompositeTagMatcher(TestCase):
@staticmethod
def count_tag_matcher_with_result(tag_matchers, tags, result_value):
count = 0
for tag_matcher in tag_matchers:
current_result = tag_matcher.should_exclude_with(tags)
if current_result == result_value:
count += 1
return count
def setUp(self):
predicate_false = lambda tags: False
predicate_contains_foo = lambda tags: any(x == "foo" for x in tags)
self.tag_matcher_false = PredicateTagMatcher(predicate_false)
self.tag_matcher_foo = PredicateTagMatcher(predicate_contains_foo)
tag_matchers = [
self.tag_matcher_foo,
self.tag_matcher_false
]
self.ctag_matcher = CompositeTagMatcher(tag_matchers)
def test_should_exclude_with__returns_true_when_any_tag_matcher_returns_true(self):
test_patterns = [
("case: with foo", ["foo", "bar"]),
("case: with foo2", ["foozy", "foo", "bar"]),
]
for case, tags in test_patterns:
actual_result = self.ctag_matcher.should_exclude_with(tags)
self.assertEqual(True, actual_result,
"%s: tags=%s" % (case, tags))
actual_true_count = self.count_tag_matcher_with_result(
self.ctag_matcher.tag_matchers, tags, True)
self.assertEqual(1, actual_true_count)
def test_should_exclude_with__returns_false_when_no_tag_matcher_return_true(self):
test_patterns = [
("case: without foo", ["fool", "bar"]),
("case: without foo2", ["foozy", "bar"]),
]
for case, tags in test_patterns:
actual_result = self.ctag_matcher.should_exclude_with(tags)
self.assertEqual(False, actual_result,
"%s: tags=%s" % (case, tags))
actual_true_count = self.count_tag_matcher_with_result(
self.ctag_matcher.tag_matchers, tags, True)
self.assertEqual(0, actual_true_count)
# -----------------------------------------------------------------------------
# PROTOTYPING CLASSES (deprecating)
# -----------------------------------------------------------------------------
class TestOnlyWithCategoryTagMatcher(TestCase):
TagMatcher = OnlyWithCategoryTagMatcher
def setUp(self):
category = "xxx"
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self.tag_matcher = OnlyWithCategoryTagMatcher(category, "alice")
self.enabled_tag = self.TagMatcher.make_category_tag(category, "alice")
self.similar_tag = self.TagMatcher.make_category_tag(category, "alice2")
self.other_tag = self.TagMatcher.make_category_tag(category, "other")
self.category = category
def test_should_exclude_with__returns_false_with_enabled_tag(self):
tags = [ self.enabled_tag ]
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__returns_false_with_enabled_tag_and_more(self):
test_patterns = [
([ self.enabled_tag, self.other_tag ], "case: first"),
([ self.other_tag, self.enabled_tag ], "case: last"),
([ "foo", self.enabled_tag, self.other_tag, "bar" ], "case: middle"),
]
for tags, case in test_patterns:
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_true_with_other_tag(self):
tags = [ self.other_tag ]
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__returns_true_with_other_tag_and_more(self):
test_patterns = [
([ self.other_tag, "foo" ], "case: first"),
([ "foo", self.other_tag ], "case: last"),
([ "foo", self.other_tag, "bar" ], "case: middle"),
]
for tags, case in test_patterns:
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_true_with_similar_tag(self):
tags = [ self.similar_tag ]
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__returns_true_with_similar_and_more(self):
test_patterns = [
([ self.similar_tag, "foo" ], "case: first"),
([ "foo", self.similar_tag ], "case: last"),
([ "foo", self.similar_tag, "bar" ], "case: middle"),
]
for tags, case in test_patterns:
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_false_without_category_tag(self):
test_patterns = [
([ ], "case: No tags"),
([ "foo" ], "case: One tag"),
([ "foo", "bar" ], "case: Two tags"),
]
for tags, case in test_patterns:
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_run_with__negates_result_of_should_exclude_with(self):
test_patterns = [
([ ], "case: No tags"),
([ "foo" ], "case: One non-category tag"),
([ "foo", "bar" ], "case: Two non-category tags"),
([ self.enabled_tag ], "case: enabled tag"),
([ self.enabled_tag, self.other_tag ], "case: enabled and other tag"),
([ self.enabled_tag, "foo" ], "case: enabled and foo tag"),
([ self.other_tag ], "case: other tag"),
([ self.other_tag, "foo" ], "case: other and foo tag"),
([ self.similar_tag ], "case: similar tag"),
([ "foo", self.similar_tag ], "case: foo and similar tag"),
]
for tags, case in test_patterns:
result1 = self.tag_matcher.should_run_with(tags)
result2 = self.tag_matcher.should_exclude_with(tags)
self.assertEqual(result1, not result2, "%s: tags=%s" % (case, tags))
self.assertEqual(not result1, result2, "%s: tags=%s" % (case, tags))
def test_make_category_tag__returns_category_tag_prefix_without_value(self):
category = "xxx"
tag1 = OnlyWithCategoryTagMatcher.make_category_tag(category)
tag2 = OnlyWithCategoryTagMatcher.make_category_tag(category, None)
tag3 = OnlyWithCategoryTagMatcher.make_category_tag(category, value=None)
self.assertEqual("only.with_xxx=", tag1)
self.assertEqual("only.with_xxx=", tag2)
self.assertEqual("only.with_xxx=", tag3)
self.assertTrue(tag1.startswith(OnlyWithCategoryTagMatcher.tag_prefix))
def test_make_category_tag__returns_category_tag_with_value(self):
category = "xxx"
tag1 = OnlyWithCategoryTagMatcher.make_category_tag(category, "alice")
tag2 = OnlyWithCategoryTagMatcher.make_category_tag(category, "bob")
self.assertEqual("only.with_xxx=alice", tag1)
self.assertEqual("only.with_xxx=bob", tag2)
def test_make_category_tag__returns_category_tag_with_tag_prefix(self):
my_tag_prefix = "ONLY_WITH."
category = "xxx"
TagMatcher = OnlyWithCategoryTagMatcher
tag0 = TagMatcher.make_category_tag(category, tag_prefix=my_tag_prefix)
tag1 = TagMatcher.make_category_tag(category, "alice", my_tag_prefix)
tag2 = TagMatcher.make_category_tag(category, "bob", tag_prefix=my_tag_prefix)
self.assertEqual("ONLY_WITH.xxx=", tag0)
self.assertEqual("ONLY_WITH.xxx=alice", tag1)
self.assertEqual("ONLY_WITH.xxx=bob", tag2)
self.assertTrue(tag1.startswith(my_tag_prefix))
def test_ctor__with_tag_prefix(self):
tag_prefix = "ONLY_WITH."
tag_matcher = OnlyWithCategoryTagMatcher("xxx", "alice", tag_prefix)
tags = ["foo", "ONLY_WITH.xxx=foo", "only.with_xxx=bar", "bar"]
actual_tags = tag_matcher.select_category_tags(tags)
self.assertEqual(["ONLY_WITH.xxx=foo"], actual_tags)
class Traits4OnlyWithAnyCategoryTagMatcher(object):
"""Test data for OnlyWithAnyCategoryTagMatcher."""
TagMatcher0 = OnlyWithCategoryTagMatcher
TagMatcher = OnlyWithAnyCategoryTagMatcher
category1_enabled_tag = TagMatcher0.make_category_tag("foo", "alice")
category1_similar_tag = TagMatcher0.make_category_tag("foo", "alice2")
category1_disabled_tag = TagMatcher0.make_category_tag("foo", "bob")
category2_enabled_tag = TagMatcher0.make_category_tag("bar", "BOB")
category2_similar_tag = TagMatcher0.make_category_tag("bar", "BOB2")
category2_disabled_tag = TagMatcher0.make_category_tag("bar", "CHARLY")
unknown_category_tag = TagMatcher0.make_category_tag("UNKNOWN", "one")
class TestOnlyWithAnyCategoryTagMatcher(TestCase):
TagMatcher = OnlyWithAnyCategoryTagMatcher
traits = Traits4OnlyWithAnyCategoryTagMatcher
def setUp(self):
value_provider = {
"foo": "alice",
"bar": "BOB",
}
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self.tag_matcher = self.TagMatcher(value_provider)
# def test_deprecating_warning_is_issued(self):
# value_provider = {"foo": "alice"}
# with warnings.catch_warnings(record=True) as recorder:
# warnings.simplefilter("always", DeprecationWarning)
# tag_matcher = OnlyWithAnyCategoryTagMatcher(value_provider)
# self.assertEqual(len(recorder), 1)
# last_warning = recorder[-1]
# assert issubclass(last_warning.category, DeprecationWarning)
# assert "deprecated" in str(last_warning.message)
def test_should_exclude_with__returns_false_with_enabled_tag(self):
traits = self.traits
tags1 = [ traits.category1_enabled_tag ]
tags2 = [ traits.category2_enabled_tag ]
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags1))
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags2))
def test_should_exclude_with__returns_false_with_enabled_tag_and_more(self):
traits = self.traits
test_patterns = [
([ traits.category1_enabled_tag, traits.category1_disabled_tag ], "case: first"),
([ traits.category1_disabled_tag, traits.category1_enabled_tag ], "case: last"),
([ "foo", traits.category1_enabled_tag, traits.category1_disabled_tag, "bar" ], "case: middle"),
]
for tags, case in test_patterns:
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_true_with_other_tag(self):
traits = self.traits
tags = [ traits.category1_disabled_tag ]
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__returns_true_with_other_tag_and_more(self):
traits = self.traits
test_patterns = [
([ traits.category1_disabled_tag, "foo" ], "case: first"),
([ "foo", traits.category1_disabled_tag ], "case: last"),
([ "foo", traits.category1_disabled_tag, "bar" ], "case: middle"),
]
for tags, case in test_patterns:
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_true_with_similar_tag(self):
traits = self.traits
tags = [ traits.category1_similar_tag ]
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__returns_true_with_similar_and_more(self):
traits = self.traits
test_patterns = [
([ traits.category1_similar_tag, "foo" ], "case: first"),
([ "foo", traits.category1_similar_tag ], "case: last"),
([ "foo", traits.category1_similar_tag, "bar" ], "case: middle"),
]
for tags, case in test_patterns:
self.assertEqual(True, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_false_without_category_tag(self):
test_patterns = [
([ ], "case: No tags"),
([ "foo" ], "case: One tag"),
([ "foo", "bar" ], "case: Two tags"),
]
for tags, case in test_patterns:
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags),
"%s: tags=%s" % (case, tags))
def test_should_exclude_with__returns_false_with_unknown_category_tag(self):
"""Tags from unknown categories, not supported by value_provider,
should not be excluded.
"""
traits = self.traits
tags = [ traits.unknown_category_tag ]
self.assertEqual("only.with_UNKNOWN=one", traits.unknown_category_tag)
self.assertEqual(None, self.tag_matcher.value_provider.get("UNKNOWN"))
self.assertEqual(False, self.tag_matcher.should_exclude_with(tags))
def test_should_exclude_with__combinations_of_2_categories(self):
traits = self.traits
test_patterns = [
("case 00: 2 disabled category tags", True,
[ traits.category1_disabled_tag, traits.category2_disabled_tag]),
("case 01: disabled and enabled category tags", True,
[ traits.category1_disabled_tag, traits.category2_enabled_tag]),
("case 10: enabled and disabled category tags", True,
[ traits.category1_enabled_tag, traits.category2_disabled_tag]),
("case 11: 2 enabled category tags", False, # -- SHOULD-RUN
[ traits.category1_enabled_tag, traits.category2_enabled_tag]),
# -- SPECIAL CASE: With unknown category
("case 0x: disabled and unknown category tags", True,
[ traits.category1_disabled_tag, traits.unknown_category_tag]),
("case 1x: enabled and unknown category tags", False, # SHOULD-RUN
[ traits.category1_enabled_tag, traits.unknown_category_tag]),
]
for case, expected, tags in test_patterns:
actual_result = self.tag_matcher.should_exclude_with(tags)
self.assertEqual(expected, actual_result,
"%s: tags=%s" % (case, tags))
def test_should_run_with__negates_result_of_should_exclude_with(self):
traits = self.traits
test_patterns = [
([ ], "case: No tags"),
([ "foo" ], "case: One non-category tag"),
([ "foo", "bar" ], "case: Two non-category tags"),
([ traits.category1_enabled_tag ], "case: enabled tag"),
([ traits.category1_enabled_tag, traits.category1_disabled_tag ], "case: enabled and other tag"),
([ traits.category1_enabled_tag, "foo" ], "case: enabled and foo tag"),
([ traits.category1_disabled_tag ], "case: other tag"),
([ traits.category1_disabled_tag, "foo" ], "case: other and foo tag"),
([ traits.category1_similar_tag ], "case: similar tag"),
([ "foo", traits.category1_similar_tag ], "case: foo and similar tag"),
]
for tags, case in test_patterns:
result1 = self.tag_matcher.should_run_with(tags)
result2 = self.tag_matcher.should_exclude_with(tags)
self.assertEqual(result1, not result2, "%s: tags=%s" % (case, tags))
self.assertEqual(not result1, result2, "%s: tags=%s" % (case, tags))
| 49.078082
| 110
| 0.643481
|
fd1783e09806177acb953da3225526f493e20ec4
| 111,659
|
py
|
Python
|
test/sql/test_types.py
|
thereisnosun/sqlalchemy
|
94aed8b17d21da9a20be4b092f6a60b12f60b761
|
[
"MIT"
] | 1
|
2020-12-09T21:56:16.000Z
|
2020-12-09T21:56:16.000Z
|
test/sql/test_types.py
|
thereisnosun/sqlalchemy
|
94aed8b17d21da9a20be4b092f6a60b12f60b761
|
[
"MIT"
] | null | null | null |
test/sql/test_types.py
|
thereisnosun/sqlalchemy
|
94aed8b17d21da9a20be4b092f6a60b12f60b761
|
[
"MIT"
] | 1
|
2020-12-04T14:51:39.000Z
|
2020-12-04T14:51:39.000Z
|
# coding: utf-8
import datetime
import decimal
import importlib
import operator
import os
import sqlalchemy as sa
from sqlalchemy import and_
from sqlalchemy import ARRAY
from sqlalchemy import BigInteger
from sqlalchemy import bindparam
from sqlalchemy import BLOB
from sqlalchemy import BOOLEAN
from sqlalchemy import Boolean
from sqlalchemy import cast
from sqlalchemy import CHAR
from sqlalchemy import CLOB
from sqlalchemy import DATE
from sqlalchemy import Date
from sqlalchemy import DATETIME
from sqlalchemy import DateTime
from sqlalchemy import DECIMAL
from sqlalchemy import dialects
from sqlalchemy import distinct
from sqlalchemy import Enum
from sqlalchemy import exc
from sqlalchemy import FLOAT
from sqlalchemy import Float
from sqlalchemy import func
from sqlalchemy import inspection
from sqlalchemy import INTEGER
from sqlalchemy import Integer
from sqlalchemy import Interval
from sqlalchemy import JSON
from sqlalchemy import LargeBinary
from sqlalchemy import literal
from sqlalchemy import MetaData
from sqlalchemy import NCHAR
from sqlalchemy import NUMERIC
from sqlalchemy import Numeric
from sqlalchemy import NVARCHAR
from sqlalchemy import PickleType
from sqlalchemy import REAL
from sqlalchemy import select
from sqlalchemy import SMALLINT
from sqlalchemy import SmallInteger
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy import Text
from sqlalchemy import text
from sqlalchemy import TIME
from sqlalchemy import Time
from sqlalchemy import TIMESTAMP
from sqlalchemy import type_coerce
from sqlalchemy import TypeDecorator
from sqlalchemy import types
from sqlalchemy import Unicode
from sqlalchemy import util
from sqlalchemy import VARCHAR
from sqlalchemy.engine import default
from sqlalchemy.schema import AddConstraint
from sqlalchemy.schema import CheckConstraint
from sqlalchemy.sql import column
from sqlalchemy.sql import ddl
from sqlalchemy.sql import elements
from sqlalchemy.sql import null
from sqlalchemy.sql import operators
from sqlalchemy.sql import sqltypes
from sqlalchemy.sql import table
from sqlalchemy.sql import visitors
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_not
from sqlalchemy.testing import mock
from sqlalchemy.testing import pickleable
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import picklers
from sqlalchemy.testing.util import round_decimal
from sqlalchemy.util import OrderedDict
from sqlalchemy.util import u
def _all_dialect_modules():
return [
importlib.import_module("sqlalchemy.dialects.%s" % d)
for d in dialects.__all__
if not d.startswith("_")
]
def _all_dialects():
return [d.base.dialect() for d in _all_dialect_modules()]
def _types_for_mod(mod):
for key in dir(mod):
typ = getattr(mod, key)
if not isinstance(typ, type) or not issubclass(typ, types.TypeEngine):
continue
yield typ
def _all_types(omit_special_types=False):
seen = set()
for typ in _types_for_mod(types):
if omit_special_types and typ in (
types.TypeDecorator,
types.TypeEngine,
types.Variant,
):
continue
if typ in seen:
continue
seen.add(typ)
yield typ
for dialect in _all_dialect_modules():
for typ in _types_for_mod(dialect):
if typ in seen:
continue
seen.add(typ)
yield typ
class AdaptTest(fixtures.TestBase):
@testing.combinations(((t,) for t in _types_for_mod(types)), id_="n")
def test_uppercase_importable(self, typ):
if typ.__name__ == typ.__name__.upper():
assert getattr(sa, typ.__name__) is typ
assert typ.__name__ in types.__all__
@testing.combinations(
((d.name, d) for d in _all_dialects()), argnames="dialect", id_="ia"
)
@testing.combinations(
(REAL(), "REAL"),
(FLOAT(), "FLOAT"),
(NUMERIC(), "NUMERIC"),
(DECIMAL(), "DECIMAL"),
(INTEGER(), "INTEGER"),
(SMALLINT(), "SMALLINT"),
(TIMESTAMP(), ("TIMESTAMP", "TIMESTAMP WITHOUT TIME ZONE")),
(DATETIME(), "DATETIME"),
(DATE(), "DATE"),
(TIME(), ("TIME", "TIME WITHOUT TIME ZONE")),
(CLOB(), "CLOB"),
(VARCHAR(10), ("VARCHAR(10)", "VARCHAR(10 CHAR)")),
(
NVARCHAR(10),
("NVARCHAR(10)", "NATIONAL VARCHAR(10)", "NVARCHAR2(10)"),
),
(CHAR(), "CHAR"),
(NCHAR(), ("NCHAR", "NATIONAL CHAR")),
(BLOB(), ("BLOB", "BLOB SUB_TYPE 0")),
(BOOLEAN(), ("BOOLEAN", "BOOL", "INTEGER")),
argnames="type_, expected",
id_="ra",
)
def test_uppercase_rendering(self, dialect, type_, expected):
"""Test that uppercase types from types.py always render as their
type.
As of SQLA 0.6, using an uppercase type means you want specifically
that type. If the database in use doesn't support that DDL, it (the DB
backend) should raise an error - it means you should be using a
lowercased (genericized) type.
"""
if isinstance(expected, str):
expected = (expected,)
try:
compiled = type_.compile(dialect=dialect)
except NotImplementedError:
return
assert compiled in expected, "%r matches none of %r for dialect %s" % (
compiled,
expected,
dialect.name,
)
assert (
str(types.to_instance(type_)) in expected
), "default str() of type %r not expected, %r" % (type_, expected)
def _adaptions():
for typ in _all_types(omit_special_types=True):
# up adapt from LowerCase to UPPERCASE,
# as well as to all non-sqltypes
up_adaptions = [typ] + typ.__subclasses__()
yield "%s.%s" % (
typ.__module__,
typ.__name__,
), False, typ, up_adaptions
for subcl in typ.__subclasses__():
if (
subcl is not typ
and typ is not TypeDecorator
and "sqlalchemy" in subcl.__module__
):
yield "%s.%s" % (
subcl.__module__,
subcl.__name__,
), True, subcl, [typ]
@testing.combinations(_adaptions(), id_="iaaa")
def test_adapt_method(self, is_down_adaption, typ, target_adaptions):
"""ensure all types have a working adapt() method,
which creates a distinct copy.
The distinct copy ensures that when we cache
the adapted() form of a type against the original
in a weak key dictionary, a cycle is not formed.
This test doesn't test type-specific arguments of
adapt() beyond their defaults.
"""
if issubclass(typ, ARRAY):
t1 = typ(String)
else:
t1 = typ()
for cls in target_adaptions:
if (is_down_adaption and issubclass(typ, sqltypes.Emulated)) or (
not is_down_adaption and issubclass(cls, sqltypes.Emulated)
):
continue
# print("ADAPT %s -> %s" % (t1.__class__, cls))
t2 = t1.adapt(cls)
assert t1 is not t2
if is_down_adaption:
t2, t1 = t1, t2
for k in t1.__dict__:
if k in (
"impl",
"_is_oracle_number",
"_create_events",
"create_constraint",
"inherit_schema",
"schema",
"metadata",
"name",
):
continue
# assert each value was copied, or that
# the adapted type has a more specific
# value than the original (i.e. SQL Server
# applies precision=24 for REAL)
assert (
getattr(t2, k) == t1.__dict__[k] or t1.__dict__[k] is None
)
eq_(t1.evaluates_none().should_evaluate_none, True)
def test_python_type(self):
eq_(types.Integer().python_type, int)
eq_(types.Numeric().python_type, decimal.Decimal)
eq_(types.Numeric(asdecimal=False).python_type, float)
eq_(types.LargeBinary().python_type, util.binary_type)
eq_(types.Float().python_type, float)
eq_(types.Interval().python_type, datetime.timedelta)
eq_(types.Date().python_type, datetime.date)
eq_(types.DateTime().python_type, datetime.datetime)
eq_(types.String().python_type, str)
eq_(types.Unicode().python_type, util.text_type)
eq_(types.Enum("one", "two", "three").python_type, str)
assert_raises(
NotImplementedError, lambda: types.TypeEngine().python_type
)
@testing.uses_deprecated()
@testing.combinations(*[(t,) for t in _all_types(omit_special_types=True)])
def test_repr(self, typ):
if issubclass(typ, ARRAY):
t1 = typ(String)
else:
t1 = typ()
repr(t1)
@testing.uses_deprecated()
@testing.combinations(*[(t,) for t in _all_types(omit_special_types=True)])
def test_str(self, typ):
if issubclass(typ, ARRAY):
t1 = typ(String)
else:
t1 = typ()
str(t1)
def test_str_third_party(self):
class TINYINT(types.TypeEngine):
__visit_name__ = "TINYINT"
eq_(str(TINYINT()), "TINYINT")
def test_str_third_party_uppercase_no_visit_name(self):
class TINYINT(types.TypeEngine):
pass
eq_(str(TINYINT()), "TINYINT")
def test_str_third_party_camelcase_no_visit_name(self):
class TinyInt(types.TypeEngine):
pass
eq_(str(TinyInt()), "TinyInt()")
def test_adapt_constructor_copy_override_kw(self):
"""test that adapt() can accept kw args that override
the state of the original object.
This essentially is testing the behavior of util.constructor_copy().
"""
t1 = String(length=50)
t2 = t1.adapt(Text)
eq_(t2.length, 50)
def test_convert_unicode_text_type(self):
with testing.expect_deprecated(
"The String.convert_unicode parameter is deprecated"
):
eq_(types.String(convert_unicode=True).python_type, util.text_type)
class TypeAffinityTest(fixtures.TestBase):
@testing.combinations(
(String(), String),
(VARCHAR(), String),
(Date(), Date),
(LargeBinary(), types._Binary),
id_="rn",
)
def test_type_affinity(self, type_, affin):
eq_(type_._type_affinity, affin)
@testing.combinations(
(Integer(), SmallInteger(), True),
(Integer(), String(), False),
(Integer(), Integer(), True),
(Text(), String(), True),
(Text(), Unicode(), True),
(LargeBinary(), Integer(), False),
(LargeBinary(), PickleType(), True),
(PickleType(), LargeBinary(), True),
(PickleType(), PickleType(), True),
id_="rra",
)
def test_compare_type_affinity(self, t1, t2, comp):
eq_(t1._compare_type_affinity(t2), comp, "%s %s" % (t1, t2))
def test_decorator_doesnt_cache(self):
from sqlalchemy.dialects import postgresql
class MyType(TypeDecorator):
impl = CHAR
def load_dialect_impl(self, dialect):
if dialect.name == "postgresql":
return dialect.type_descriptor(postgresql.UUID())
else:
return dialect.type_descriptor(CHAR(32))
t1 = MyType()
d = postgresql.dialect()
assert t1._type_affinity is String
assert t1.dialect_impl(d)._type_affinity is postgresql.UUID
class PickleTypesTest(fixtures.TestBase):
@testing.combinations(
("Boo", Boolean()),
("Str", String()),
("Tex", Text()),
("Uni", Unicode()),
("Int", Integer()),
("Sma", SmallInteger()),
("Big", BigInteger()),
("Num", Numeric()),
("Flo", Float()),
("Dat", DateTime()),
("Dat", Date()),
("Tim", Time()),
("Lar", LargeBinary()),
("Pic", PickleType()),
("Int", Interval()),
id_="ar",
)
def test_pickle_types(self, name, type_):
column_type = Column(name, type_)
meta = MetaData()
Table("foo", meta, column_type)
for loads, dumps in picklers():
loads(dumps(column_type))
loads(dumps(meta))
class _UserDefinedTypeFixture(object):
@classmethod
def define_tables(cls, metadata):
class MyType(types.UserDefinedType):
def get_col_spec(self):
return "VARCHAR(100)"
def bind_processor(self, dialect):
def process(value):
return "BIND_IN" + value
return process
def result_processor(self, dialect, coltype):
def process(value):
return value + "BIND_OUT"
return process
def adapt(self, typeobj):
return typeobj()
class MyDecoratedType(types.TypeDecorator):
impl = String
def bind_processor(self, dialect):
impl_processor = super(MyDecoratedType, self).bind_processor(
dialect
) or (lambda value: value)
def process(value):
return "BIND_IN" + impl_processor(value)
return process
def result_processor(self, dialect, coltype):
impl_processor = super(MyDecoratedType, self).result_processor(
dialect, coltype
) or (lambda value: value)
def process(value):
return impl_processor(value) + "BIND_OUT"
return process
def copy(self):
return MyDecoratedType()
class MyNewUnicodeType(types.TypeDecorator):
impl = Unicode
def process_bind_param(self, value, dialect):
return "BIND_IN" + value
def process_result_value(self, value, dialect):
return value + "BIND_OUT"
def copy(self):
return MyNewUnicodeType(self.impl.length)
class MyNewIntType(types.TypeDecorator):
impl = Integer
def process_bind_param(self, value, dialect):
return value * 10
def process_result_value(self, value, dialect):
return value * 10
def copy(self):
return MyNewIntType()
class MyNewIntSubClass(MyNewIntType):
def process_result_value(self, value, dialect):
return value * 15
def copy(self):
return MyNewIntSubClass()
class MyUnicodeType(types.TypeDecorator):
impl = Unicode
def bind_processor(self, dialect):
impl_processor = super(MyUnicodeType, self).bind_processor(
dialect
) or (lambda value: value)
def process(value):
return "BIND_IN" + impl_processor(value)
return process
def result_processor(self, dialect, coltype):
impl_processor = super(MyUnicodeType, self).result_processor(
dialect, coltype
) or (lambda value: value)
def process(value):
return impl_processor(value) + "BIND_OUT"
return process
def copy(self):
return MyUnicodeType(self.impl.length)
Table(
"users",
metadata,
Column("user_id", Integer, primary_key=True),
# totall custom type
Column("goofy", MyType, nullable=False),
# decorated type with an argument, so its a String
Column("goofy2", MyDecoratedType(50), nullable=False),
Column("goofy4", MyUnicodeType(50), nullable=False),
Column("goofy7", MyNewUnicodeType(50), nullable=False),
Column("goofy8", MyNewIntType, nullable=False),
Column("goofy9", MyNewIntSubClass, nullable=False),
)
class UserDefinedRoundTripTest(_UserDefinedTypeFixture, fixtures.TablesTest):
__backend__ = True
def _data_fixture(self):
users = self.tables.users
with testing.db.connect() as conn:
conn.execute(
users.insert(),
dict(
user_id=2,
goofy="jack",
goofy2="jack",
goofy4=util.u("jack"),
goofy7=util.u("jack"),
goofy8=12,
goofy9=12,
),
)
conn.execute(
users.insert(),
dict(
user_id=3,
goofy="lala",
goofy2="lala",
goofy4=util.u("lala"),
goofy7=util.u("lala"),
goofy8=15,
goofy9=15,
),
)
conn.execute(
users.insert(),
dict(
user_id=4,
goofy="fred",
goofy2="fred",
goofy4=util.u("fred"),
goofy7=util.u("fred"),
goofy8=9,
goofy9=9,
),
)
def test_processing(self, connection):
users = self.tables.users
self._data_fixture()
result = connection.execute(
users.select().order_by(users.c.user_id)
).fetchall()
for assertstr, assertint, assertint2, row in zip(
[
"BIND_INjackBIND_OUT",
"BIND_INlalaBIND_OUT",
"BIND_INfredBIND_OUT",
],
[1200, 1500, 900],
[1800, 2250, 1350],
result,
):
for col in list(row)[1:5]:
eq_(col, assertstr)
eq_(row[5], assertint)
eq_(row[6], assertint2)
for col in row[3], row[4]:
assert isinstance(col, util.text_type)
def test_plain_in(self, connection):
users = self.tables.users
self._data_fixture()
stmt = (
select(users.c.user_id, users.c.goofy8)
.where(users.c.goofy8.in_([15, 9]))
.order_by(users.c.user_id)
)
result = connection.execute(stmt, {"goofy": [15, 9]})
eq_(result.fetchall(), [(3, 1500), (4, 900)])
def test_expanding_in(self, connection):
users = self.tables.users
self._data_fixture()
stmt = (
select(users.c.user_id, users.c.goofy8)
.where(users.c.goofy8.in_(bindparam("goofy", expanding=True)))
.order_by(users.c.user_id)
)
result = connection.execute(stmt, {"goofy": [15, 9]})
eq_(result.fetchall(), [(3, 1500), (4, 900)])
class UserDefinedTest(
_UserDefinedTypeFixture, fixtures.TablesTest, AssertsCompiledSQL
):
run_create_tables = None
run_inserts = None
run_deletes = None
"""tests user-defined types."""
def test_typedecorator_literal_render(self):
class MyType(types.TypeDecorator):
impl = String
def process_literal_param(self, value, dialect):
return "HI->%s<-THERE" % value
self.assert_compile(
select(literal("test", MyType)),
"SELECT 'HI->test<-THERE' AS anon_1",
dialect="default",
literal_binds=True,
)
def test_kw_colspec(self):
class MyType(types.UserDefinedType):
def get_col_spec(self, **kw):
return "FOOB %s" % kw["type_expression"].name
class MyOtherType(types.UserDefinedType):
def get_col_spec(self):
return "BAR"
t = Table("t", MetaData(), Column("bar", MyType, nullable=False))
self.assert_compile(ddl.CreateColumn(t.c.bar), "bar FOOB bar NOT NULL")
t = Table("t", MetaData(), Column("bar", MyOtherType, nullable=False))
self.assert_compile(ddl.CreateColumn(t.c.bar), "bar BAR NOT NULL")
def test_typedecorator_literal_render_fallback_bound(self):
# fall back to process_bind_param for literal
# value rendering.
class MyType(types.TypeDecorator):
impl = String
def process_bind_param(self, value, dialect):
return "HI->%s<-THERE" % value
self.assert_compile(
select(literal("test", MyType)),
"SELECT 'HI->test<-THERE' AS anon_1",
dialect="default",
literal_binds=True,
)
def test_typedecorator_impl(self):
for impl_, exp, kw in [
(Float, "FLOAT", {}),
(Float, "FLOAT(2)", {"precision": 2}),
(Float(2), "FLOAT(2)", {"precision": 4}),
(Numeric(19, 2), "NUMERIC(19, 2)", {}),
]:
for dialect_ in (
dialects.postgresql,
dialects.mssql,
dialects.mysql,
):
dialect_ = dialect_.dialect()
raw_impl = types.to_instance(impl_, **kw)
class MyType(types.TypeDecorator):
impl = impl_
dec_type = MyType(**kw)
eq_(dec_type.impl.__class__, raw_impl.__class__)
raw_dialect_impl = raw_impl.dialect_impl(dialect_)
dec_dialect_impl = dec_type.dialect_impl(dialect_)
eq_(dec_dialect_impl.__class__, MyType)
eq_(
raw_dialect_impl.__class__, dec_dialect_impl.impl.__class__
)
self.assert_compile(MyType(**kw), exp, dialect=dialect_)
def test_user_defined_typedec_impl(self):
class MyType(types.TypeDecorator):
impl = Float
def load_dialect_impl(self, dialect):
if dialect.name == "sqlite":
return String(50)
else:
return super(MyType, self).load_dialect_impl(dialect)
sl = dialects.sqlite.dialect()
pg = dialects.postgresql.dialect()
t = MyType()
self.assert_compile(t, "VARCHAR(50)", dialect=sl)
self.assert_compile(t, "FLOAT", dialect=pg)
eq_(
t.dialect_impl(dialect=sl).impl.__class__,
String().dialect_impl(dialect=sl).__class__,
)
eq_(
t.dialect_impl(dialect=pg).impl.__class__,
Float().dialect_impl(pg).__class__,
)
def test_type_decorator_repr(self):
class MyType(TypeDecorator):
impl = VARCHAR
eq_(repr(MyType(45)), "MyType(length=45)")
def test_user_defined_typedec_impl_bind(self):
class TypeOne(types.TypeEngine):
def bind_processor(self, dialect):
def go(value):
return value + " ONE"
return go
class TypeTwo(types.TypeEngine):
def bind_processor(self, dialect):
def go(value):
return value + " TWO"
return go
class MyType(types.TypeDecorator):
impl = TypeOne
def load_dialect_impl(self, dialect):
if dialect.name == "sqlite":
return TypeOne()
else:
return TypeTwo()
def process_bind_param(self, value, dialect):
return "MYTYPE " + value
sl = dialects.sqlite.dialect()
pg = dialects.postgresql.dialect()
t = MyType()
eq_(t._cached_bind_processor(sl)("foo"), "MYTYPE foo ONE")
eq_(t._cached_bind_processor(pg)("foo"), "MYTYPE foo TWO")
def test_user_defined_dialect_specific_args(self):
class MyType(types.UserDefinedType):
def __init__(self, foo="foo", **kwargs):
super(MyType, self).__init__()
self.foo = foo
self.dialect_specific_args = kwargs
def adapt(self, cls):
return cls(foo=self.foo, **self.dialect_specific_args)
t = MyType(bar="bar")
a = t.dialect_impl(testing.db.dialect)
eq_(a.foo, "foo")
eq_(a.dialect_specific_args["bar"], "bar")
class StringConvertUnicodeTest(fixtures.TestBase):
@testing.combinations((Unicode,), (String,), argnames="datatype")
@testing.combinations((True,), (False,), argnames="convert_unicode")
@testing.combinations(
(String.RETURNS_CONDITIONAL,),
(String.RETURNS_BYTES,),
(String.RETURNS_UNICODE),
argnames="returns_unicode_strings",
)
def test_convert_unicode(
self, datatype, convert_unicode, returns_unicode_strings
):
s1 = datatype()
dialect = mock.Mock(
returns_unicode_strings=returns_unicode_strings,
encoding="utf-8",
convert_unicode=convert_unicode,
)
proc = s1.result_processor(dialect, None)
string = u("méil")
bytestring = string.encode("utf-8")
if (
datatype is Unicode or convert_unicode
) and returns_unicode_strings in (
String.RETURNS_CONDITIONAL,
String.RETURNS_BYTES,
):
eq_(proc(bytestring), string)
if returns_unicode_strings is String.RETURNS_CONDITIONAL:
eq_(proc(string), string)
else:
if util.py3k:
# trying to decode a unicode
assert_raises(TypeError, proc, string)
else:
assert_raises(UnicodeEncodeError, proc, string)
else:
is_(proc, None)
class TypeCoerceCastTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
class MyType(types.TypeDecorator):
impl = String(50)
def process_bind_param(self, value, dialect):
return "BIND_IN" + str(value)
def process_result_value(self, value, dialect):
return value + "BIND_OUT"
cls.MyType = MyType
Table("t", metadata, Column("data", String(50)))
def test_insert_round_trip_cast(self, connection):
self._test_insert_round_trip(cast, connection)
def test_insert_round_trip_type_coerce(self, connection):
self._test_insert_round_trip(type_coerce, connection)
def _test_insert_round_trip(self, coerce_fn, conn):
MyType = self.MyType
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn("d1", MyType)))
eq_(
conn.execute(select(coerce_fn(t.c.data, MyType))).fetchall(),
[("BIND_INd1BIND_OUT",)],
)
def test_coerce_from_nulltype_cast(self, connection):
self._test_coerce_from_nulltype(cast, connection)
def test_coerce_from_nulltype_type_coerce(self, connection):
self._test_coerce_from_nulltype(type_coerce, connection)
def _test_coerce_from_nulltype(self, coerce_fn, conn):
MyType = self.MyType
# test coerce from nulltype - e.g. use an object that
# does't match to a known type
class MyObj(object):
def __str__(self):
return "THISISMYOBJ"
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn(MyObj(), MyType)))
eq_(
conn.execute(select(coerce_fn(t.c.data, MyType))).fetchall(),
[("BIND_INTHISISMYOBJBIND_OUT",)],
)
def test_vs_non_coerced_cast(self, connection):
self._test_vs_non_coerced(cast, connection)
def test_vs_non_coerced_type_coerce(self, connection):
self._test_vs_non_coerced(type_coerce, connection)
def _test_vs_non_coerced(self, coerce_fn, conn):
MyType = self.MyType
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn("d1", MyType)))
eq_(
conn.execute(
select(t.c.data, coerce_fn(t.c.data, MyType))
).fetchall(),
[("BIND_INd1", "BIND_INd1BIND_OUT")],
)
def test_vs_non_coerced_alias_cast(self, connection):
self._test_vs_non_coerced_alias(cast, connection)
def test_vs_non_coerced_alias_type_coerce(self, connection):
self._test_vs_non_coerced_alias(type_coerce, connection)
def _test_vs_non_coerced_alias(self, coerce_fn, conn):
MyType = self.MyType
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn("d1", MyType)))
eq_(
conn.execute(
select(t.c.data.label("x"), coerce_fn(t.c.data, MyType))
.alias()
.select()
).fetchall(),
[("BIND_INd1", "BIND_INd1BIND_OUT")],
)
def test_vs_non_coerced_where_cast(self, connection):
self._test_vs_non_coerced_where(cast, connection)
def test_vs_non_coerced_where_type_coerce(self, connection):
self._test_vs_non_coerced_where(type_coerce, connection)
def _test_vs_non_coerced_where(self, coerce_fn, conn):
MyType = self.MyType
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn("d1", MyType)))
# coerce on left side
eq_(
conn.execute(
select(t.c.data, coerce_fn(t.c.data, MyType)).where(
coerce_fn(t.c.data, MyType) == "d1"
)
).fetchall(),
[("BIND_INd1", "BIND_INd1BIND_OUT")],
)
# coerce on right side
eq_(
conn.execute(
select(t.c.data, coerce_fn(t.c.data, MyType)).where(
t.c.data == coerce_fn("d1", MyType)
)
).fetchall(),
[("BIND_INd1", "BIND_INd1BIND_OUT")],
)
def test_coerce_none_cast(self, connection):
self._test_coerce_none(cast, connection)
def test_coerce_none_type_coerce(self, connection):
self._test_coerce_none(type_coerce, connection)
def _test_coerce_none(self, coerce_fn, conn):
MyType = self.MyType
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn("d1", MyType)))
eq_(
conn.execute(
select(t.c.data, coerce_fn(t.c.data, MyType)).where(
t.c.data == coerce_fn(None, MyType)
)
).fetchall(),
[],
)
eq_(
conn.execute(
select(t.c.data, coerce_fn(t.c.data, MyType)).where(
coerce_fn(t.c.data, MyType) == None
)
).fetchall(), # noqa
[],
)
def test_resolve_clause_element_cast(self, connection):
self._test_resolve_clause_element(cast, connection)
def test_resolve_clause_element_type_coerce(self, connection):
self._test_resolve_clause_element(type_coerce, connection)
def _test_resolve_clause_element(self, coerce_fn, conn):
MyType = self.MyType
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn("d1", MyType)))
class MyFoob(object):
def __clause_element__(self):
return t.c.data
eq_(
conn.execute(
select(t.c.data, coerce_fn(MyFoob(), MyType))
).fetchall(),
[("BIND_INd1", "BIND_INd1BIND_OUT")],
)
def test_cast_replace_col_w_bind(self, connection):
self._test_replace_col_w_bind(cast, connection)
def test_type_coerce_replace_col_w_bind(self, connection):
self._test_replace_col_w_bind(type_coerce, connection)
def _test_replace_col_w_bind(self, coerce_fn, conn):
MyType = self.MyType
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn("d1", MyType)))
stmt = select(t.c.data, coerce_fn(t.c.data, MyType))
def col_to_bind(col):
if col is t.c.data:
return bindparam(None, "x", type_=col.type, unique=True)
return None
# ensure we evaluate the expression so that we can see
# the clone resets this info
stmt.compile()
new_stmt = visitors.replacement_traverse(stmt, {}, col_to_bind)
# original statement
eq_(
conn.execute(stmt).fetchall(),
[("BIND_INd1", "BIND_INd1BIND_OUT")],
)
# replaced with binds; CAST can't affect the bound parameter
# on the way in here
eq_(
conn.execute(new_stmt).fetchall(),
[("x", "BIND_INxBIND_OUT")]
if coerce_fn is type_coerce
else [("x", "xBIND_OUT")],
)
def test_cast_bind(self, connection):
self._test_bind(cast, connection)
def test_type_bind(self, connection):
self._test_bind(type_coerce, connection)
def _test_bind(self, coerce_fn, conn):
MyType = self.MyType
t = self.tables.t
conn.execute(t.insert().values(data=coerce_fn("d1", MyType)))
stmt = select(
bindparam(None, "x", String(50), unique=True),
coerce_fn(bindparam(None, "x", String(50), unique=True), MyType),
)
eq_(
conn.execute(stmt).fetchall(),
[("x", "BIND_INxBIND_OUT")]
if coerce_fn is type_coerce
else [("x", "xBIND_OUT")],
)
def test_cast_existing_typed(self, connection):
MyType = self.MyType
coerce_fn = cast
# when cast() is given an already typed value,
# the type does not take effect on the value itself.
eq_(
connection.scalar(select(coerce_fn(literal("d1"), MyType))),
"d1BIND_OUT",
)
def test_type_coerce_existing_typed(self, connection):
MyType = self.MyType
coerce_fn = type_coerce
t = self.tables.t
# type_coerce does upgrade the given expression to the
# given type.
connection.execute(
t.insert().values(data=coerce_fn(literal("d1"), MyType))
)
eq_(
connection.execute(select(coerce_fn(t.c.data, MyType))).fetchall(),
[("BIND_INd1BIND_OUT",)],
)
class VariantTest(fixtures.TestBase, AssertsCompiledSQL):
def setup(self):
class UTypeOne(types.UserDefinedType):
def get_col_spec(self):
return "UTYPEONE"
def bind_processor(self, dialect):
def process(value):
return value + "UONE"
return process
class UTypeTwo(types.UserDefinedType):
def get_col_spec(self):
return "UTYPETWO"
def bind_processor(self, dialect):
def process(value):
return value + "UTWO"
return process
class UTypeThree(types.UserDefinedType):
def get_col_spec(self):
return "UTYPETHREE"
self.UTypeOne = UTypeOne
self.UTypeTwo = UTypeTwo
self.UTypeThree = UTypeThree
self.variant = self.UTypeOne().with_variant(
self.UTypeTwo(), "postgresql"
)
self.composite = self.variant.with_variant(self.UTypeThree(), "mysql")
def test_illegal_dupe(self):
v = self.UTypeOne().with_variant(self.UTypeTwo(), "postgresql")
assert_raises_message(
exc.ArgumentError,
"Dialect 'postgresql' is already present "
"in the mapping for this Variant",
lambda: v.with_variant(self.UTypeThree(), "postgresql"),
)
def test_compile(self):
self.assert_compile(self.variant, "UTYPEONE", use_default_dialect=True)
self.assert_compile(
self.variant, "UTYPEONE", dialect=dialects.mysql.dialect()
)
self.assert_compile(
self.variant, "UTYPETWO", dialect=dialects.postgresql.dialect()
)
def test_to_instance(self):
self.assert_compile(
self.UTypeOne().with_variant(self.UTypeTwo, "postgresql"),
"UTYPETWO",
dialect=dialects.postgresql.dialect(),
)
def test_compile_composite(self):
self.assert_compile(
self.composite, "UTYPEONE", use_default_dialect=True
)
self.assert_compile(
self.composite, "UTYPETHREE", dialect=dialects.mysql.dialect()
)
self.assert_compile(
self.composite, "UTYPETWO", dialect=dialects.postgresql.dialect()
)
def test_bind_process(self):
eq_(
self.variant._cached_bind_processor(dialects.mysql.dialect())(
"foo"
),
"fooUONE",
)
eq_(
self.variant._cached_bind_processor(default.DefaultDialect())(
"foo"
),
"fooUONE",
)
eq_(
self.variant._cached_bind_processor(dialects.postgresql.dialect())(
"foo"
),
"fooUTWO",
)
def test_bind_process_composite(self):
assert (
self.composite._cached_bind_processor(dialects.mysql.dialect())
is None
)
eq_(
self.composite._cached_bind_processor(default.DefaultDialect())(
"foo"
),
"fooUONE",
)
eq_(
self.composite._cached_bind_processor(
dialects.postgresql.dialect()
)("foo"),
"fooUTWO",
)
def test_comparator_variant(self):
expr = column("x", self.variant) == "bar"
is_(expr.right.type, self.variant)
@testing.only_on("sqlite")
@testing.provide_metadata
def test_round_trip(self):
variant = self.UTypeOne().with_variant(self.UTypeTwo(), "sqlite")
t = Table("t", self.metadata, Column("x", variant))
with testing.db.connect() as conn:
t.create(conn)
conn.execute(t.insert(), x="foo")
eq_(conn.scalar(select(t.c.x).where(t.c.x == "foo")), "fooUTWO")
@testing.only_on("sqlite")
@testing.provide_metadata
def test_round_trip_sqlite_datetime(self):
variant = DateTime().with_variant(
dialects.sqlite.DATETIME(truncate_microseconds=True), "sqlite"
)
t = Table("t", self.metadata, Column("x", variant))
with testing.db.connect() as conn:
t.create(conn)
conn.execute(
t.insert(), x=datetime.datetime(2015, 4, 18, 10, 15, 17, 4839)
)
eq_(
conn.scalar(
select(t.c.x).where(
t.c.x
== datetime.datetime(2015, 4, 18, 10, 15, 17, 1059)
)
),
datetime.datetime(2015, 4, 18, 10, 15, 17),
)
class UnicodeTest(fixtures.TestBase):
"""Exercise the Unicode and related types.
Note: unicode round trip tests are now in
sqlalchemy/testing/suite/test_types.py.
"""
__backend__ = True
data = util.u(
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. "
"Elle disait: « S’il vous plaît… dessine-moi un mouton! »"
)
def test_unicode_warnings_typelevel_native_unicode(self):
unicodedata = self.data
u = Unicode()
dialect = default.DefaultDialect()
dialect.supports_unicode_binds = True
uni = u.dialect_impl(dialect).bind_processor(dialect)
if util.py3k:
assert_raises(exc.SAWarning, uni, b"x")
assert isinstance(uni(unicodedata), str)
else:
assert_raises(exc.SAWarning, uni, "x")
assert isinstance(uni(unicodedata), unicode) # noqa
def test_unicode_warnings_typelevel_sqla_unicode(self):
unicodedata = self.data
u = Unicode()
dialect = default.DefaultDialect()
dialect.supports_unicode_binds = False
uni = u.dialect_impl(dialect).bind_processor(dialect)
assert_raises(exc.SAWarning, uni, util.b("x"))
assert isinstance(uni(unicodedata), util.binary_type)
eq_(uni(unicodedata), unicodedata.encode("utf-8"))
def test_unicode_warnings_totally_wrong_type(self):
u = Unicode()
dialect = default.DefaultDialect()
dialect.supports_unicode_binds = False
uni = u.dialect_impl(dialect).bind_processor(dialect)
with expect_warnings(
"Unicode type received non-unicode bind param value 5."
):
eq_(uni(5), 5)
class EnumTest(AssertsCompiledSQL, fixtures.TablesTest):
__backend__ = True
class SomeEnum(object):
# Implements PEP 435 in the minimal fashion needed by SQLAlchemy
__members__ = OrderedDict()
def __init__(self, name, value, alias=None):
self.name = name
self.value = value
self.__members__[name] = self
setattr(self.__class__, name, self)
if alias:
self.__members__[alias] = self
setattr(self.__class__, alias, self)
class SomeOtherEnum(SomeEnum):
__members__ = OrderedDict()
one = SomeEnum("one", 1)
two = SomeEnum("two", 2)
three = SomeEnum("three", 3, "four")
a_member = SomeEnum("AMember", "a")
b_member = SomeEnum("BMember", "b")
other_one = SomeOtherEnum("one", 1)
other_two = SomeOtherEnum("two", 2)
other_three = SomeOtherEnum("three", 3)
other_a_member = SomeOtherEnum("AMember", "a")
other_b_member = SomeOtherEnum("BMember", "b")
@staticmethod
def get_enum_string_values(some_enum):
return [str(v.value) for v in some_enum.__members__.values()]
@classmethod
def define_tables(cls, metadata):
# note create_constraint has changed in 1.4 as of #5367
Table(
"enum_table",
metadata,
Column("id", Integer, primary_key=True),
Column(
"someenum",
Enum(
"one",
"two",
"three",
name="myenum",
create_constraint=True,
),
),
)
Table(
"non_native_enum_table",
metadata,
Column("id", Integer, primary_key=True, autoincrement=False),
Column(
"someenum",
Enum(
"one",
"two",
"three",
native_enum=False,
create_constraint=True,
),
),
Column(
"someotherenum",
Enum(
"one",
"two",
"three",
native_enum=False,
validate_strings=True,
),
),
)
Table(
"stdlib_enum_table",
metadata,
Column("id", Integer, primary_key=True),
Column("someenum", Enum(cls.SomeEnum, create_constraint=True)),
)
Table(
"stdlib_enum_table2",
metadata,
Column("id", Integer, primary_key=True),
Column(
"someotherenum",
Enum(
cls.SomeOtherEnum,
values_callable=EnumTest.get_enum_string_values,
create_constraint=True,
),
),
)
def test_python_type(self):
eq_(types.Enum(self.SomeEnum).python_type, self.SomeEnum)
def test_pickle_types(self):
global SomeEnum
SomeEnum = self.SomeEnum
for loads, dumps in picklers():
column_types = [
Column("Enu", Enum("x", "y", "z", name="somename")),
Column("En2", Enum(self.SomeEnum)),
]
for column_type in column_types:
meta = MetaData()
Table("foo", meta, column_type)
loads(dumps(column_type))
loads(dumps(meta))
def test_validators_pep435(self):
type_ = Enum(self.SomeEnum)
validate_type = Enum(self.SomeEnum, validate_strings=True)
bind_processor = type_.bind_processor(testing.db.dialect)
bind_processor_validates = validate_type.bind_processor(
testing.db.dialect
)
eq_(bind_processor("one"), "one")
eq_(bind_processor(self.one), "one")
eq_(bind_processor("foo"), "foo")
assert_raises_message(
LookupError,
"'5' is not among the defined enum values. Enum name: someenum. "
"Possible values: one, two, three, ..., BMember",
bind_processor,
5,
)
assert_raises_message(
LookupError,
"'foo' is not among the defined enum values. Enum name: someenum. "
"Possible values: one, two, three, ..., BMember",
bind_processor_validates,
"foo",
)
result_processor = type_.result_processor(testing.db.dialect, None)
eq_(result_processor("one"), self.one)
assert_raises_message(
LookupError,
"'foo' is not among the defined enum values. Enum name: someenum. "
"Possible values: one, two, three, ..., BMember",
result_processor,
"foo",
)
literal_processor = type_.literal_processor(testing.db.dialect)
validate_literal_processor = validate_type.literal_processor(
testing.db.dialect
)
eq_(literal_processor("one"), "'one'")
eq_(literal_processor("foo"), "'foo'")
assert_raises_message(
LookupError,
"'5' is not among the defined enum values. Enum name: someenum. "
"Possible values: one, two, three, ..., BMember",
literal_processor,
5,
)
assert_raises_message(
LookupError,
"'foo' is not among the defined enum values. Enum name: someenum. "
"Possible values: one, two, three, ..., BMember",
validate_literal_processor,
"foo",
)
def test_validators_plain(self):
type_ = Enum("one", "two")
validate_type = Enum("one", "two", validate_strings=True)
bind_processor = type_.bind_processor(testing.db.dialect)
bind_processor_validates = validate_type.bind_processor(
testing.db.dialect
)
eq_(bind_processor("one"), "one")
eq_(bind_processor("foo"), "foo")
assert_raises_message(
LookupError,
"'5' is not among the defined enum values. Enum name: None. "
"Possible values: one, two",
bind_processor,
5,
)
assert_raises_message(
LookupError,
"'foo' is not among the defined enum values. Enum name: None. "
"Possible values: one, two",
bind_processor_validates,
"foo",
)
result_processor = type_.result_processor(testing.db.dialect, None)
eq_(result_processor("one"), "one")
assert_raises_message(
LookupError,
"'foo' is not among the defined enum values. Enum name: None. "
"Possible values: one, two",
result_processor,
"foo",
)
literal_processor = type_.literal_processor(testing.db.dialect)
validate_literal_processor = validate_type.literal_processor(
testing.db.dialect
)
eq_(literal_processor("one"), "'one'")
eq_(literal_processor("foo"), "'foo'")
assert_raises_message(
LookupError,
"'5' is not among the defined enum values. Enum name: None. "
"Possible values: one, two",
literal_processor,
5,
)
assert_raises_message(
LookupError,
"'foo' is not among the defined enum values. Enum name: None. "
"Possible values: one, two",
validate_literal_processor,
"foo",
)
def test_enum_raise_lookup_ellipses(self):
type_ = Enum("one", "twothreefourfivesix", "seven", "eight")
bind_processor = type_.bind_processor(testing.db.dialect)
eq_(bind_processor("one"), "one")
assert_raises_message(
LookupError,
"'5' is not among the defined enum values. Enum name: None. "
"Possible values: one, twothreefou.., seven, eight",
bind_processor,
5,
)
def test_enum_raise_lookup_none(self):
type_ = Enum()
bind_processor = type_.bind_processor(testing.db.dialect)
assert_raises_message(
LookupError,
"'5' is not among the defined enum values. Enum name: None. "
"Possible values: None",
bind_processor,
5,
)
def test_validators_not_in_like_roundtrip(self, connection):
enum_table = self.tables["non_native_enum_table"]
connection.execute(
enum_table.insert(),
[
{"id": 1, "someenum": "two"},
{"id": 2, "someenum": "two"},
{"id": 3, "someenum": "one"},
],
)
eq_(
connection.execute(
enum_table.select()
.where(enum_table.c.someenum.like("%wo%"))
.order_by(enum_table.c.id)
).fetchall(),
[(1, "two", None), (2, "two", None)],
)
def test_validators_not_in_concatenate_roundtrip(self, connection):
enum_table = self.tables["non_native_enum_table"]
connection.execute(
enum_table.insert(),
[
{"id": 1, "someenum": "two"},
{"id": 2, "someenum": "two"},
{"id": 3, "someenum": "one"},
],
)
eq_(
connection.execute(
select("foo" + enum_table.c.someenum).order_by(enum_table.c.id)
).fetchall(),
[("footwo",), ("footwo",), ("fooone",)],
)
def test_round_trip(self, connection):
enum_table = self.tables["enum_table"]
connection.execute(
enum_table.insert(),
[
{"id": 1, "someenum": "two"},
{"id": 2, "someenum": "two"},
{"id": 3, "someenum": "one"},
],
)
eq_(
connection.execute(
enum_table.select().order_by(enum_table.c.id)
).fetchall(),
[(1, "two"), (2, "two"), (3, "one")],
)
def test_null_round_trip(self, connection):
enum_table = self.tables.enum_table
non_native_enum_table = self.tables.non_native_enum_table
connection.execute(enum_table.insert(), {"id": 1, "someenum": None})
eq_(connection.scalar(select(enum_table.c.someenum)), None)
connection.execute(
non_native_enum_table.insert(), {"id": 1, "someenum": None}
)
eq_(connection.scalar(select(non_native_enum_table.c.someenum)), None)
@testing.requires.enforces_check_constraints
def test_check_constraint(self, connection):
assert_raises(
(
exc.IntegrityError,
exc.ProgrammingError,
exc.OperationalError,
# PyMySQL raising InternalError until
# https://github.com/PyMySQL/PyMySQL/issues/607 is resolved
exc.InternalError,
),
connection.exec_driver_sql,
"insert into non_native_enum_table "
"(id, someenum) values(1, 'four')",
)
@testing.requires.enforces_check_constraints
@testing.provide_metadata
def test_variant_we_are_default(self):
# test that the "variant" does not create a constraint
t = Table(
"my_table",
self.metadata,
Column(
"data",
Enum(
"one",
"two",
"three",
native_enum=False,
name="e1",
create_constraint=True,
).with_variant(
Enum(
"four",
"five",
"six",
native_enum=False,
name="e2",
create_constraint=True,
),
"some_other_db",
),
),
mysql_engine="InnoDB",
)
eq_(
len([c for c in t.constraints if isinstance(c, CheckConstraint)]),
2,
)
with testing.db.connect() as conn:
self.metadata.create_all(conn)
assert_raises(
(exc.DBAPIError,),
conn.exec_driver_sql,
"insert into my_table " "(data) values('four')",
)
conn.exec_driver_sql("insert into my_table (data) values ('two')")
@testing.requires.enforces_check_constraints
@testing.provide_metadata
def test_variant_we_are_not_default(self):
# test that the "variant" does not create a constraint
t = Table(
"my_table",
self.metadata,
Column(
"data",
Enum(
"one",
"two",
"three",
native_enum=False,
name="e1",
create_constraint=True,
).with_variant(
Enum(
"four",
"five",
"six",
native_enum=False,
name="e2",
create_constraint=True,
),
testing.db.dialect.name,
),
),
)
# ensure Variant isn't exploding the constraints
eq_(
len([c for c in t.constraints if isinstance(c, CheckConstraint)]),
2,
)
with testing.db.connect() as conn:
self.metadata.create_all(conn)
assert_raises(
(exc.DBAPIError,),
conn.exec_driver_sql,
"insert into my_table " "(data) values('two')",
)
conn.exec_driver_sql("insert into my_table (data) values ('four')")
def test_skip_check_constraint(self):
with testing.db.connect() as conn:
conn.exec_driver_sql(
"insert into non_native_enum_table "
"(id, someotherenum) values(1, 'four')"
)
eq_(
conn.exec_driver_sql(
"select someotherenum from non_native_enum_table"
).scalar(),
"four",
)
assert_raises_message(
LookupError,
"'four' is not among the defined enum values. "
"Enum name: None. Possible values: one, two, three",
conn.scalar,
select(self.tables.non_native_enum_table.c.someotherenum),
)
def test_non_native_round_trip(self, connection):
non_native_enum_table = self.tables["non_native_enum_table"]
connection.execute(
non_native_enum_table.insert(),
[
{"id": 1, "someenum": "two"},
{"id": 2, "someenum": "two"},
{"id": 3, "someenum": "one"},
],
)
eq_(
connection.execute(
select(
non_native_enum_table.c.id,
non_native_enum_table.c.someenum,
).order_by(non_native_enum_table.c.id)
).fetchall(),
[(1, "two"), (2, "two"), (3, "one")],
)
def test_pep435_default_sort_key(self):
one, two, a_member, b_member = (
self.one,
self.two,
self.a_member,
self.b_member,
)
typ = Enum(self.SomeEnum)
is_(typ.sort_key_function.__func__, typ._db_value_for_elem.__func__)
eq_(
sorted([two, one, a_member, b_member], key=typ.sort_key_function),
[a_member, b_member, one, two],
)
def test_pep435_custom_sort_key(self):
one, two, a_member, b_member = (
self.one,
self.two,
self.a_member,
self.b_member,
)
def sort_enum_key_value(value):
return str(value.value)
typ = Enum(self.SomeEnum, sort_key_function=sort_enum_key_value)
is_(typ.sort_key_function, sort_enum_key_value)
eq_(
sorted([two, one, a_member, b_member], key=typ.sort_key_function),
[one, two, a_member, b_member],
)
def test_pep435_no_sort_key(self):
typ = Enum(self.SomeEnum, sort_key_function=None)
is_(typ.sort_key_function, None)
def test_pep435_enum_round_trip(self, connection):
stdlib_enum_table = self.tables["stdlib_enum_table"]
connection.execute(
stdlib_enum_table.insert(),
[
{"id": 1, "someenum": self.SomeEnum.two},
{"id": 2, "someenum": self.SomeEnum.two},
{"id": 3, "someenum": self.SomeEnum.one},
{"id": 4, "someenum": self.SomeEnum.three},
{"id": 5, "someenum": self.SomeEnum.four},
{"id": 6, "someenum": "three"},
{"id": 7, "someenum": "four"},
],
)
eq_(
connection.execute(
stdlib_enum_table.select().order_by(stdlib_enum_table.c.id)
).fetchall(),
[
(1, self.SomeEnum.two),
(2, self.SomeEnum.two),
(3, self.SomeEnum.one),
(4, self.SomeEnum.three),
(5, self.SomeEnum.three),
(6, self.SomeEnum.three),
(7, self.SomeEnum.three),
],
)
def test_pep435_enum_values_callable_round_trip(self, connection):
stdlib_enum_table_custom_values = self.tables["stdlib_enum_table2"]
connection.execute(
stdlib_enum_table_custom_values.insert(),
[
{"id": 1, "someotherenum": self.SomeOtherEnum.AMember},
{"id": 2, "someotherenum": self.SomeOtherEnum.BMember},
{"id": 3, "someotherenum": self.SomeOtherEnum.AMember},
],
)
eq_(
connection.execute(
stdlib_enum_table_custom_values.select().order_by(
stdlib_enum_table_custom_values.c.id
)
).fetchall(),
[
(1, self.SomeOtherEnum.AMember),
(2, self.SomeOtherEnum.BMember),
(3, self.SomeOtherEnum.AMember),
],
)
def test_pep435_enum_expanding_in(self, connection):
stdlib_enum_table_custom_values = self.tables["stdlib_enum_table2"]
connection.execute(
stdlib_enum_table_custom_values.insert(),
[
{"id": 1, "someotherenum": self.SomeOtherEnum.one},
{"id": 2, "someotherenum": self.SomeOtherEnum.two},
{"id": 3, "someotherenum": self.SomeOtherEnum.three},
],
)
stmt = (
stdlib_enum_table_custom_values.select()
.where(
stdlib_enum_table_custom_values.c.someotherenum.in_(
bindparam("member", expanding=True)
)
)
.order_by(stdlib_enum_table_custom_values.c.id)
)
eq_(
connection.execute(
stmt,
{"member": [self.SomeOtherEnum.one, self.SomeOtherEnum.three]},
).fetchall(),
[(1, self.SomeOtherEnum.one), (3, self.SomeOtherEnum.three)],
)
def test_adapt(self):
from sqlalchemy.dialects.postgresql import ENUM
e1 = Enum("one", "two", "three", native_enum=False)
false_adapt = e1.adapt(ENUM)
eq_(false_adapt.native_enum, False)
assert not isinstance(false_adapt, ENUM)
e1 = Enum("one", "two", "three", native_enum=True)
true_adapt = e1.adapt(ENUM)
eq_(true_adapt.native_enum, True)
assert isinstance(true_adapt, ENUM)
e1 = Enum(
"one",
"two",
"three",
name="foo",
schema="bar",
metadata=MetaData(),
)
eq_(e1.adapt(ENUM).name, "foo")
eq_(e1.adapt(ENUM).schema, "bar")
is_(e1.adapt(ENUM).metadata, e1.metadata)
eq_(e1.adapt(Enum).name, "foo")
eq_(e1.adapt(Enum).schema, "bar")
is_(e1.adapt(Enum).metadata, e1.metadata)
e1 = Enum(self.SomeEnum)
eq_(e1.adapt(ENUM).name, "someenum")
eq_(
e1.adapt(ENUM).enums,
["one", "two", "three", "four", "AMember", "BMember"],
)
e1_vc = Enum(
self.SomeOtherEnum, values_callable=EnumTest.get_enum_string_values
)
eq_(e1_vc.adapt(ENUM).name, "someotherenum")
eq_(e1_vc.adapt(ENUM).enums, ["1", "2", "3", "a", "b"])
def test_adapt_length(self):
from sqlalchemy.dialects.postgresql import ENUM
e1 = Enum("one", "two", "three", length=50, native_enum=False)
eq_(e1.adapt(ENUM).length, 50)
eq_(e1.adapt(Enum).length, 50)
e1 = Enum("one", "two", "three")
eq_(e1.length, 5)
eq_(e1.adapt(ENUM).length, 5)
eq_(e1.adapt(Enum).length, 5)
@testing.provide_metadata
def test_create_metadata_bound_no_crash(self):
m1 = self.metadata
Enum("a", "b", "c", metadata=m1, name="ncenum")
m1.create_all(testing.db)
def test_non_native_constraint_custom_type(self):
class Foob(object):
def __init__(self, name):
self.name = name
class MyEnum(TypeDecorator):
def __init__(self, values):
self.impl = Enum(
*[v.name for v in values],
name="myenum",
native_enum=False,
create_constraint=True
)
# future method
def process_literal_param(self, value, dialect):
return value.name
def process_bind_param(self, value, dialect):
return value.name
m = MetaData()
t1 = Table("t", m, Column("x", MyEnum([Foob("a"), Foob("b")])))
const = [c for c in t1.constraints if isinstance(c, CheckConstraint)][
0
]
self.assert_compile(
AddConstraint(const),
"ALTER TABLE t ADD CONSTRAINT myenum CHECK (x IN ('a', 'b'))",
dialect="default",
)
def test_lookup_failure(self, connection):
assert_raises(
exc.StatementError,
connection.execute,
self.tables["non_native_enum_table"].insert(),
{"id": 4, "someotherenum": "four"},
)
def test_mock_engine_no_prob(self):
"""ensure no 'checkfirst' queries are run when enums
are created with checkfirst=False"""
e = engines.mock_engine()
t = Table(
"t1",
MetaData(),
Column("x", Enum("x", "y", name="pge", create_constraint=True)),
)
t.create(e, checkfirst=False)
# basically looking for the start of
# the constraint, or the ENUM def itself,
# depending on backend.
assert "('x'," in e.print_sql()
@testing.uses_deprecated(".*convert_unicode")
def test_repr(self):
e = Enum(
"x",
"y",
name="somename",
convert_unicode=True,
quote=True,
inherit_schema=True,
native_enum=False,
)
eq_(
repr(e),
"Enum('x', 'y', name='somename', "
"inherit_schema=True, native_enum=False)",
)
def test_length_native(self):
e = Enum("x", "y", "long", length=42)
eq_(e.length, len("long"))
# no error is raised
e = Enum("x", "y", "long", length=1)
eq_(e.length, len("long"))
def test_length_raises(self):
assert_raises_message(
ValueError,
"When provided, length must be larger or equal.*",
Enum,
"x",
"y",
"long",
native_enum=False,
length=1,
)
def test_no_length_non_native(self):
e = Enum("x", "y", "long", native_enum=False)
eq_(e.length, len("long"))
def test_length_non_native(self):
e = Enum("x", "y", "long", native_enum=False, length=42)
eq_(e.length, 42)
binary_table = MyPickleType = metadata = None
class BinaryTest(fixtures.TestBase, AssertsExecutionResults):
__backend__ = True
@classmethod
def setup_class(cls):
global binary_table, MyPickleType, metadata
class MyPickleType(types.TypeDecorator):
impl = PickleType
def process_bind_param(self, value, dialect):
if value:
value.stuff = "this is modified stuff"
return value
def process_result_value(self, value, dialect):
if value:
value.stuff = "this is the right stuff"
return value
metadata = MetaData(testing.db)
binary_table = Table(
"binary_table",
metadata,
Column(
"primary_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("data", LargeBinary),
Column("data_slice", LargeBinary(100)),
Column("misc", String(30)),
Column("pickled", PickleType),
Column("mypickle", MyPickleType),
)
metadata.create_all()
@engines.close_first
def teardown(self):
with testing.db.connect() as conn:
conn.execute(binary_table.delete())
@classmethod
def teardown_class(cls):
metadata.drop_all()
@testing.requires.non_broken_binary
def test_round_trip(self, connection):
testobj1 = pickleable.Foo("im foo 1")
testobj2 = pickleable.Foo("im foo 2")
testobj3 = pickleable.Foo("im foo 3")
stream1 = self.load_stream("binary_data_one.dat")
stream2 = self.load_stream("binary_data_two.dat")
connection.execute(
binary_table.insert(),
primary_id=1,
misc="binary_data_one.dat",
data=stream1,
data_slice=stream1[0:100],
pickled=testobj1,
mypickle=testobj3,
)
connection.execute(
binary_table.insert(),
primary_id=2,
misc="binary_data_two.dat",
data=stream2,
data_slice=stream2[0:99],
pickled=testobj2,
)
connection.execute(
binary_table.insert(),
primary_id=3,
misc="binary_data_two.dat",
data=None,
data_slice=stream2[0:99],
pickled=None,
)
for stmt in (
binary_table.select(order_by=binary_table.c.primary_id),
text(
"select * from binary_table order by binary_table.primary_id",
).columns(
**{
"pickled": PickleType,
"mypickle": MyPickleType,
"data": LargeBinary,
"data_slice": LargeBinary,
}
),
):
result = connection.execute(stmt).fetchall()
eq_(stream1, result[0]._mapping["data"])
eq_(stream1[0:100], result[0]._mapping["data_slice"])
eq_(stream2, result[1]._mapping["data"])
eq_(testobj1, result[0]._mapping["pickled"])
eq_(testobj2, result[1]._mapping["pickled"])
eq_(testobj3.moredata, result[0]._mapping["mypickle"].moredata)
eq_(
result[0]._mapping["mypickle"].stuff, "this is the right stuff"
)
@testing.requires.binary_comparisons
def test_comparison(self, connection):
"""test that type coercion occurs on comparison for binary"""
expr = binary_table.c.data == "foo"
assert isinstance(expr.right.type, LargeBinary)
data = os.urandom(32)
connection.execute(binary_table.insert(), data=data)
eq_(
connection.scalar(
select(func.count("*"))
.select_from(binary_table)
.where(binary_table.c.data == data)
),
1,
)
@testing.requires.binary_literals
def test_literal_roundtrip(self, connection):
compiled = select(cast(literal(util.b("foo")), LargeBinary)).compile(
dialect=testing.db.dialect, compile_kwargs={"literal_binds": True}
)
result = connection.execute(compiled)
eq_(result.scalar(), util.b("foo"))
def test_bind_processor_no_dbapi(self):
b = LargeBinary()
eq_(b.bind_processor(default.DefaultDialect()), None)
def load_stream(self, name):
f = os.path.join(os.path.dirname(__file__), "..", name)
with open(f, mode="rb") as o:
return o.read()
class JSONTest(fixtures.TestBase):
def setup(self):
metadata = MetaData()
self.test_table = Table(
"test_table",
metadata,
Column("id", Integer, primary_key=True),
Column("test_column", JSON),
)
self.jsoncol = self.test_table.c.test_column
self.dialect = default.DefaultDialect()
self.dialect._json_serializer = None
self.dialect._json_deserializer = None
def test_bind_serialize_default(self):
proc = self.test_table.c.test_column.type._cached_bind_processor(
self.dialect
)
eq_(
proc({"A": [1, 2, 3, True, False]}),
'{"A": [1, 2, 3, true, false]}',
)
def test_bind_serialize_None(self):
proc = self.test_table.c.test_column.type._cached_bind_processor(
self.dialect
)
eq_(proc(None), "null")
def test_bind_serialize_none_as_null(self):
proc = JSON(none_as_null=True)._cached_bind_processor(self.dialect)
eq_(proc(None), None)
eq_(proc(null()), None)
def test_bind_serialize_null(self):
proc = self.test_table.c.test_column.type._cached_bind_processor(
self.dialect
)
eq_(proc(null()), None)
def test_result_deserialize_default(self):
proc = self.test_table.c.test_column.type._cached_result_processor(
self.dialect, None
)
eq_(
proc('{"A": [1, 2, 3, true, false]}'),
{"A": [1, 2, 3, True, False]},
)
def test_result_deserialize_null(self):
proc = self.test_table.c.test_column.type._cached_result_processor(
self.dialect, None
)
eq_(proc("null"), None)
def test_result_deserialize_None(self):
proc = self.test_table.c.test_column.type._cached_result_processor(
self.dialect, None
)
eq_(proc(None), None)
def _dialect_index_fixture(self, int_processor, str_processor):
class MyInt(Integer):
def bind_processor(self, dialect):
return lambda value: value + 10
def literal_processor(self, diaect):
return lambda value: str(value + 15)
class MyString(String):
def bind_processor(self, dialect):
return lambda value: value + "10"
def literal_processor(self, diaect):
return lambda value: value + "15"
class MyDialect(default.DefaultDialect):
colspecs = {}
if int_processor:
colspecs[Integer] = MyInt
if str_processor:
colspecs[String] = MyString
return MyDialect()
def test_index_bind_proc_int(self):
expr = self.test_table.c.test_column[5]
int_dialect = self._dialect_index_fixture(True, True)
non_int_dialect = self._dialect_index_fixture(False, True)
bindproc = expr.right.type._cached_bind_processor(int_dialect)
eq_(bindproc(expr.right.value), 15)
bindproc = expr.right.type._cached_bind_processor(non_int_dialect)
eq_(bindproc(expr.right.value), 5)
def test_index_literal_proc_int(self):
expr = self.test_table.c.test_column[5]
int_dialect = self._dialect_index_fixture(True, True)
non_int_dialect = self._dialect_index_fixture(False, True)
bindproc = expr.right.type._cached_literal_processor(int_dialect)
eq_(bindproc(expr.right.value), "20")
bindproc = expr.right.type._cached_literal_processor(non_int_dialect)
eq_(bindproc(expr.right.value), "5")
def test_index_bind_proc_str(self):
expr = self.test_table.c.test_column["five"]
str_dialect = self._dialect_index_fixture(True, True)
non_str_dialect = self._dialect_index_fixture(False, False)
bindproc = expr.right.type._cached_bind_processor(str_dialect)
eq_(bindproc(expr.right.value), "five10")
bindproc = expr.right.type._cached_bind_processor(non_str_dialect)
eq_(bindproc(expr.right.value), "five")
def test_index_literal_proc_str(self):
expr = self.test_table.c.test_column["five"]
str_dialect = self._dialect_index_fixture(True, True)
non_str_dialect = self._dialect_index_fixture(False, False)
bindproc = expr.right.type._cached_literal_processor(str_dialect)
eq_(bindproc(expr.right.value), "five15")
bindproc = expr.right.type._cached_literal_processor(non_str_dialect)
eq_(bindproc(expr.right.value), "'five'")
class ArrayTest(fixtures.TestBase):
def _myarray_fixture(self):
class MyArray(ARRAY):
pass
return MyArray
def test_array_index_map_dimensions(self):
col = column("x", ARRAY(Integer, dimensions=3))
is_(col[5].type._type_affinity, ARRAY)
eq_(col[5].type.dimensions, 2)
is_(col[5][6].type._type_affinity, ARRAY)
eq_(col[5][6].type.dimensions, 1)
is_(col[5][6][7].type._type_affinity, Integer)
def test_array_getitem_single_type(self):
m = MetaData()
arrtable = Table(
"arrtable",
m,
Column("intarr", ARRAY(Integer)),
Column("strarr", ARRAY(String)),
)
is_(arrtable.c.intarr[1].type._type_affinity, Integer)
is_(arrtable.c.strarr[1].type._type_affinity, String)
def test_array_getitem_slice_type(self):
m = MetaData()
arrtable = Table(
"arrtable",
m,
Column("intarr", ARRAY(Integer)),
Column("strarr", ARRAY(String)),
)
is_(arrtable.c.intarr[1:3].type._type_affinity, ARRAY)
is_(arrtable.c.strarr[1:3].type._type_affinity, ARRAY)
def test_array_getitem_slice_type_dialect_level(self):
MyArray = self._myarray_fixture()
m = MetaData()
arrtable = Table(
"arrtable",
m,
Column("intarr", MyArray(Integer)),
Column("strarr", MyArray(String)),
)
is_(arrtable.c.intarr[1:3].type._type_affinity, ARRAY)
is_(arrtable.c.strarr[1:3].type._type_affinity, ARRAY)
# but the slice returns the actual type
assert isinstance(arrtable.c.intarr[1:3].type, MyArray)
assert isinstance(arrtable.c.strarr[1:3].type, MyArray)
test_table = meta = MyCustomType = MyTypeDec = None
class ExpressionTest(
fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL
):
__dialect__ = "default"
@classmethod
def setup_class(cls):
global test_table, meta, MyCustomType, MyTypeDec
class MyCustomType(types.UserDefinedType):
def get_col_spec(self):
return "INT"
def bind_processor(self, dialect):
def process(value):
return value * 10
return process
def result_processor(self, dialect, coltype):
def process(value):
return value / 10
return process
class MyOldCustomType(MyCustomType):
def adapt_operator(self, op):
return {
operators.add: operators.sub,
operators.sub: operators.add,
}.get(op, op)
class MyTypeDec(types.TypeDecorator):
impl = String
def process_bind_param(self, value, dialect):
return "BIND_IN" + str(value)
def process_result_value(self, value, dialect):
return value + "BIND_OUT"
meta = MetaData(testing.db)
test_table = Table(
"test",
meta,
Column("id", Integer, primary_key=True),
Column("data", String(30)),
Column("atimestamp", Date),
Column("avalue", MyCustomType),
Column("bvalue", MyTypeDec(50)),
)
meta.create_all()
with testing.db.connect() as conn:
conn.execute(
test_table.insert(),
{
"id": 1,
"data": "somedata",
"atimestamp": datetime.date(2007, 10, 15),
"avalue": 25,
"bvalue": "foo",
},
)
@classmethod
def teardown_class(cls):
meta.drop_all()
def test_control(self, connection):
assert (
connection.exec_driver_sql("select avalue from test").scalar()
== 250
)
eq_(
connection.execute(test_table.select()).fetchall(),
[
(
1,
"somedata",
datetime.date(2007, 10, 15),
25,
"BIND_INfooBIND_OUT",
)
],
)
def test_bind_adapt(self, connection):
# test an untyped bind gets the left side's type
expr = test_table.c.atimestamp == bindparam("thedate")
eq_(expr.right.type._type_affinity, Date)
eq_(
connection.execute(
select(
test_table.c.id,
test_table.c.data,
test_table.c.atimestamp,
).where(expr),
{"thedate": datetime.date(2007, 10, 15)},
).fetchall(),
[(1, "somedata", datetime.date(2007, 10, 15))],
)
expr = test_table.c.avalue == bindparam("somevalue")
eq_(expr.right.type._type_affinity, MyCustomType)
eq_(
connection.execute(
test_table.select().where(expr), {"somevalue": 25}
).fetchall(),
[
(
1,
"somedata",
datetime.date(2007, 10, 15),
25,
"BIND_INfooBIND_OUT",
)
],
)
expr = test_table.c.bvalue == bindparam("somevalue")
eq_(expr.right.type._type_affinity, String)
eq_(
connection.execute(
test_table.select().where(expr), {"somevalue": "foo"}
).fetchall(),
[
(
1,
"somedata",
datetime.date(2007, 10, 15),
25,
"BIND_INfooBIND_OUT",
)
],
)
def test_grouped_bind_adapt(self):
expr = test_table.c.atimestamp == elements.Grouping(
bindparam("thedate")
)
eq_(expr.right.type._type_affinity, Date)
eq_(expr.right.element.type._type_affinity, Date)
expr = test_table.c.atimestamp == elements.Grouping(
elements.Grouping(bindparam("thedate"))
)
eq_(expr.right.type._type_affinity, Date)
eq_(expr.right.element.type._type_affinity, Date)
eq_(expr.right.element.element.type._type_affinity, Date)
def test_bind_adapt_update(self):
bp = bindparam("somevalue")
stmt = test_table.update().values(avalue=bp)
compiled = stmt.compile()
eq_(bp.type._type_affinity, types.NullType)
eq_(compiled.binds["somevalue"].type._type_affinity, MyCustomType)
def test_bind_adapt_insert(self):
bp = bindparam("somevalue")
stmt = test_table.insert().values(avalue=bp)
compiled = stmt.compile()
eq_(bp.type._type_affinity, types.NullType)
eq_(compiled.binds["somevalue"].type._type_affinity, MyCustomType)
def test_bind_adapt_expression(self):
bp = bindparam("somevalue")
stmt = test_table.c.avalue == bp
eq_(bp.type._type_affinity, types.NullType)
eq_(stmt.right.type._type_affinity, MyCustomType)
def test_literal_adapt(self):
# literals get typed based on the types dictionary, unless
# compatible with the left side type
expr = column("foo", String) == 5
eq_(expr.right.type._type_affinity, Integer)
expr = column("foo", String) == "asdf"
eq_(expr.right.type._type_affinity, String)
expr = column("foo", CHAR) == 5
eq_(expr.right.type._type_affinity, Integer)
expr = column("foo", CHAR) == "asdf"
eq_(expr.right.type.__class__, CHAR)
@testing.combinations(
(5, Integer),
(2.65, Float),
(True, Boolean),
(decimal.Decimal("2.65"), Numeric),
(datetime.date(2015, 7, 20), Date),
(datetime.time(10, 15, 20), Time),
(datetime.datetime(2015, 7, 20, 10, 15, 20), DateTime),
(datetime.timedelta(seconds=5), Interval),
(None, types.NullType),
)
def test_actual_literal_adapters(self, data, expected):
is_(literal(data).type.__class__, expected)
def test_typedec_operator_adapt(self, connection):
expr = test_table.c.bvalue + "hi"
assert expr.type.__class__ is MyTypeDec
assert expr.right.type.__class__ is MyTypeDec
eq_(
connection.execute(select(expr.label("foo"))).scalar(),
"BIND_INfooBIND_INhiBIND_OUT",
)
def test_typedec_is_adapt(self):
class CoerceNothing(TypeDecorator):
coerce_to_is_types = ()
impl = Integer
class CoerceBool(TypeDecorator):
coerce_to_is_types = (bool,)
impl = Boolean
class CoerceNone(TypeDecorator):
coerce_to_is_types = (type(None),)
impl = Integer
c1 = column("x", CoerceNothing())
c2 = column("x", CoerceBool())
c3 = column("x", CoerceNone())
self.assert_compile(
and_(c1 == None, c2 == None, c3 == None), # noqa
"x = :x_1 AND x = :x_2 AND x IS NULL",
)
self.assert_compile(
and_(c1 == True, c2 == True, c3 == True), # noqa
"x = :x_1 AND x = true AND x = :x_2",
dialect=default.DefaultDialect(supports_native_boolean=True),
)
self.assert_compile(
and_(c1 == 3, c2 == 3, c3 == 3),
"x = :x_1 AND x = :x_2 AND x = :x_3",
dialect=default.DefaultDialect(supports_native_boolean=True),
)
self.assert_compile(
and_(c1.is_(True), c2.is_(True), c3.is_(True)),
"x IS :x_1 AND x IS true AND x IS :x_2",
dialect=default.DefaultDialect(supports_native_boolean=True),
)
def test_typedec_righthand_coercion(self, connection):
class MyTypeDec(types.TypeDecorator):
impl = String
def process_bind_param(self, value, dialect):
return "BIND_IN" + str(value)
def process_result_value(self, value, dialect):
return value + "BIND_OUT"
tab = table("test", column("bvalue", MyTypeDec))
expr = tab.c.bvalue + 6
self.assert_compile(
expr, "test.bvalue || :bvalue_1", use_default_dialect=True
)
is_(expr.right.type.__class__, MyTypeDec)
is_(expr.type.__class__, MyTypeDec)
eq_(
connection.execute(select(expr.label("foo"))).scalar(),
"BIND_INfooBIND_IN6BIND_OUT",
)
def test_variant_righthand_coercion_honors_wrapped(self):
my_json_normal = JSON()
my_json_variant = JSON().with_variant(String(), "sqlite")
tab = table(
"test",
column("avalue", my_json_normal),
column("bvalue", my_json_variant),
)
expr = tab.c.avalue["foo"] == "bar"
is_(expr.right.type._type_affinity, String)
is_not(expr.right.type, my_json_normal)
expr = tab.c.bvalue["foo"] == "bar"
is_(expr.right.type._type_affinity, String)
is_not(expr.right.type, my_json_variant)
def test_variant_righthand_coercion_returns_self(self):
my_datetime_normal = DateTime()
my_datetime_variant = DateTime().with_variant(
dialects.sqlite.DATETIME(truncate_microseconds=False), "sqlite"
)
tab = table(
"test",
column("avalue", my_datetime_normal),
column("bvalue", my_datetime_variant),
)
expr = tab.c.avalue == datetime.datetime(2015, 10, 14, 15, 17, 18)
is_(expr.right.type._type_affinity, DateTime)
is_(expr.right.type, my_datetime_normal)
expr = tab.c.bvalue == datetime.datetime(2015, 10, 14, 15, 17, 18)
is_(expr.right.type, my_datetime_variant)
def test_bind_typing(self):
from sqlalchemy.sql import column
class MyFoobarType(types.UserDefinedType):
pass
class Foo(object):
pass
# unknown type + integer, right hand bind
# coerces to given type
expr = column("foo", MyFoobarType) + 5
assert expr.right.type._type_affinity is MyFoobarType
# untyped bind - it gets assigned MyFoobarType
bp = bindparam("foo")
expr = column("foo", MyFoobarType) + bp
assert bp.type._type_affinity is types.NullType # noqa
assert expr.right.type._type_affinity is MyFoobarType
expr = column("foo", MyFoobarType) + bindparam("foo", type_=Integer)
assert expr.right.type._type_affinity is types.Integer
# unknown type + unknown, right hand bind
# coerces to the left
expr = column("foo", MyFoobarType) + Foo()
assert expr.right.type._type_affinity is MyFoobarType
# including for non-commutative ops
expr = column("foo", MyFoobarType) - Foo()
assert expr.right.type._type_affinity is MyFoobarType
expr = column("foo", MyFoobarType) - datetime.date(2010, 8, 25)
assert expr.right.type._type_affinity is MyFoobarType
def test_date_coercion(self):
expr = column("bar", types.NULLTYPE) - column("foo", types.TIMESTAMP)
eq_(expr.type._type_affinity, types.NullType)
expr = func.sysdate() - column("foo", types.TIMESTAMP)
eq_(expr.type._type_affinity, types.Interval)
expr = func.current_date() - column("foo", types.TIMESTAMP)
eq_(expr.type._type_affinity, types.Interval)
def test_interval_coercion(self):
expr = column("bar", types.Interval) + column("foo", types.Date)
eq_(expr.type._type_affinity, types.DateTime)
expr = column("bar", types.Interval) * column("foo", types.Numeric)
eq_(expr.type._type_affinity, types.Interval)
@testing.combinations(
(operator.add,),
(operator.mul,),
(operator.truediv,),
(operator.sub,),
argnames="op",
id_="n",
)
@testing.combinations(
(Numeric(10, 2),), (Integer(),), argnames="other", id_="r"
)
def test_numerics_coercion(self, op, other):
expr = op(column("bar", types.Numeric(10, 2)), column("foo", other))
assert isinstance(expr.type, types.Numeric)
expr = op(column("foo", other), column("bar", types.Numeric(10, 2)))
assert isinstance(expr.type, types.Numeric)
def test_asdecimal_int_to_numeric(self):
expr = column("a", Integer) * column("b", Numeric(asdecimal=False))
is_(expr.type.asdecimal, False)
expr = column("a", Integer) * column("b", Numeric())
is_(expr.type.asdecimal, True)
expr = column("a", Integer) * column("b", Float())
is_(expr.type.asdecimal, False)
assert isinstance(expr.type, Float)
def test_asdecimal_numeric_to_int(self):
expr = column("a", Numeric(asdecimal=False)) * column("b", Integer)
is_(expr.type.asdecimal, False)
expr = column("a", Numeric()) * column("b", Integer)
is_(expr.type.asdecimal, True)
expr = column("a", Float()) * column("b", Integer)
is_(expr.type.asdecimal, False)
assert isinstance(expr.type, Float)
def test_null_comparison(self):
eq_(
str(column("a", types.NullType()) + column("b", types.NullType())),
"a + b",
)
def test_expression_typing(self):
expr = column("bar", Integer) - 3
eq_(expr.type._type_affinity, Integer)
expr = bindparam("bar") + bindparam("foo")
eq_(expr.type, types.NULLTYPE)
def test_distinct(self, connection):
s = select(distinct(test_table.c.avalue))
eq_(connection.execute(s).scalar(), 25)
s = select(test_table.c.avalue.distinct())
eq_(connection.execute(s).scalar(), 25)
assert distinct(test_table.c.data).type == test_table.c.data.type
assert test_table.c.data.distinct().type == test_table.c.data.type
def test_detect_coercion_of_builtins(self):
@inspection._self_inspects
class SomeSQLAThing(object):
def __repr__(self):
return "some_sqla_thing()"
class SomeOtherThing(object):
pass
assert_raises_message(
exc.ArgumentError,
r"SQL expression element or literal value expected, got "
r"some_sqla_thing\(\).",
lambda: column("a", String) == SomeSQLAThing(),
)
is_(bindparam("x", SomeOtherThing()).type, types.NULLTYPE)
def test_detect_coercion_not_fooled_by_mock(self):
m1 = mock.Mock()
is_(bindparam("x", m1).type, types.NULLTYPE)
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
@testing.requires.unbounded_varchar
def test_string_plain(self):
self.assert_compile(String(), "VARCHAR")
def test_string_length(self):
self.assert_compile(String(50), "VARCHAR(50)")
def test_string_collation(self):
self.assert_compile(
String(50, collation="FOO"), 'VARCHAR(50) COLLATE "FOO"'
)
def test_char_plain(self):
self.assert_compile(CHAR(), "CHAR")
def test_char_length(self):
self.assert_compile(CHAR(50), "CHAR(50)")
def test_char_collation(self):
self.assert_compile(
CHAR(50, collation="FOO"), 'CHAR(50) COLLATE "FOO"'
)
def test_text_plain(self):
self.assert_compile(Text(), "TEXT")
def test_text_length(self):
self.assert_compile(Text(50), "TEXT(50)")
def test_text_collation(self):
self.assert_compile(Text(collation="FOO"), 'TEXT COLLATE "FOO"')
def test_default_compile_pg_inet(self):
self.assert_compile(
dialects.postgresql.INET(), "INET", allow_dialect_select=True
)
def test_default_compile_pg_float(self):
self.assert_compile(
dialects.postgresql.FLOAT(), "FLOAT", allow_dialect_select=True
)
def test_default_compile_mysql_integer(self):
self.assert_compile(
dialects.mysql.INTEGER(display_width=5),
"INTEGER",
allow_dialect_select=True,
)
self.assert_compile(
dialects.mysql.INTEGER(display_width=5),
"INTEGER(5)",
dialect="mysql",
)
def test_numeric_plain(self):
self.assert_compile(types.NUMERIC(), "NUMERIC")
def test_numeric_precision(self):
self.assert_compile(types.NUMERIC(2), "NUMERIC(2)")
def test_numeric_scale(self):
self.assert_compile(types.NUMERIC(2, 4), "NUMERIC(2, 4)")
def test_decimal_plain(self):
self.assert_compile(types.DECIMAL(), "DECIMAL")
def test_decimal_precision(self):
self.assert_compile(types.DECIMAL(2), "DECIMAL(2)")
def test_decimal_scale(self):
self.assert_compile(types.DECIMAL(2, 4), "DECIMAL(2, 4)")
def test_kwarg_legacy_typecompiler(self):
from sqlalchemy.sql import compiler
class SomeTypeCompiler(compiler.GenericTypeCompiler):
# transparently decorated w/ kw decorator
def visit_VARCHAR(self, type_):
return "MYVARCHAR"
# not affected
def visit_INTEGER(self, type_, **kw):
return "MYINTEGER %s" % kw["type_expression"].name
dialect = default.DefaultDialect()
dialect.type_compiler = SomeTypeCompiler(dialect)
self.assert_compile(
ddl.CreateColumn(Column("bar", VARCHAR(50))),
"bar MYVARCHAR",
dialect=dialect,
)
self.assert_compile(
ddl.CreateColumn(Column("bar", INTEGER)),
"bar MYINTEGER bar",
dialect=dialect,
)
class TestKWArgPassThru(AssertsCompiledSQL, fixtures.TestBase):
__backend__ = True
def test_user_defined(self):
"""test that dialects pass the column through on DDL."""
class MyType(types.UserDefinedType):
def get_col_spec(self, **kw):
return "FOOB %s" % kw["type_expression"].name
m = MetaData()
t = Table("t", m, Column("bar", MyType, nullable=False))
self.assert_compile(ddl.CreateColumn(t.c.bar), "bar FOOB bar NOT NULL")
class NumericRawSQLTest(fixtures.TestBase):
"""Test what DBAPIs and dialects return without any typing
information supplied at the SQLA level.
"""
__backend__ = True
def _fixture(self, metadata, type_, data):
t = Table("t", metadata, Column("val", type_))
metadata.create_all()
with testing.db.connect() as conn:
conn.execute(t.insert(), val=data)
@testing.fails_on("sqlite", "Doesn't provide Decimal results natively")
@testing.provide_metadata
def test_decimal_fp(self, connection):
metadata = self.metadata
self._fixture(metadata, Numeric(10, 5), decimal.Decimal("45.5"))
val = connection.exec_driver_sql("select val from t").scalar()
assert isinstance(val, decimal.Decimal)
eq_(val, decimal.Decimal("45.5"))
@testing.fails_on("sqlite", "Doesn't provide Decimal results natively")
@testing.provide_metadata
def test_decimal_int(self, connection):
metadata = self.metadata
self._fixture(metadata, Numeric(10, 5), decimal.Decimal("45"))
val = connection.exec_driver_sql("select val from t").scalar()
assert isinstance(val, decimal.Decimal)
eq_(val, decimal.Decimal("45"))
@testing.provide_metadata
def test_ints(self, connection):
metadata = self.metadata
self._fixture(metadata, Integer, 45)
val = connection.exec_driver_sql("select val from t").scalar()
assert isinstance(val, util.int_types)
eq_(val, 45)
@testing.provide_metadata
def test_float(self, connection):
metadata = self.metadata
self._fixture(metadata, Float, 46.583)
val = connection.exec_driver_sql("select val from t").scalar()
assert isinstance(val, float)
# some DBAPIs have unusual float handling
if testing.against("oracle+cx_oracle", "mysql+oursql", "firebird"):
eq_(round_decimal(val, 3), 46.583)
else:
eq_(val, 46.583)
interval_table = metadata = None
class IntervalTest(fixtures.TestBase, AssertsExecutionResults):
__backend__ = True
@classmethod
def setup_class(cls):
global interval_table, metadata
metadata = MetaData(testing.db)
interval_table = Table(
"intervaltable",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("native_interval", Interval()),
Column(
"native_interval_args",
Interval(day_precision=3, second_precision=6),
),
Column("non_native_interval", Interval(native=False)),
)
metadata.create_all()
@engines.close_first
def teardown(self):
with testing.db.connect() as conn:
conn.execute(interval_table.delete())
@classmethod
def teardown_class(cls):
metadata.drop_all()
def test_non_native_adapt(self):
interval = Interval(native=False)
adapted = interval.dialect_impl(testing.db.dialect)
assert isinstance(adapted, Interval)
assert adapted.native is False
eq_(str(adapted), "DATETIME")
def test_roundtrip(self):
small_delta = datetime.timedelta(days=15, seconds=5874)
delta = datetime.timedelta(14)
with testing.db.begin() as conn:
conn.execute(
interval_table.insert(),
native_interval=small_delta,
native_interval_args=delta,
non_native_interval=delta,
)
row = conn.execute(interval_table.select()).first()
eq_(row.native_interval, small_delta)
eq_(row.native_interval_args, delta)
eq_(row.non_native_interval, delta)
def test_null(self):
with testing.db.begin() as conn:
conn.execute(
interval_table.insert(),
id=1,
native_inverval=None,
non_native_interval=None,
)
row = conn.execute(interval_table.select()).first()
eq_(row.native_interval, None)
eq_(row.native_interval_args, None)
eq_(row.non_native_interval, None)
class IntegerTest(fixtures.TestBase):
__backend__ = True
def test_integer_literal_processor(self):
typ = Integer()
eq_(typ._cached_literal_processor(testing.db.dialect)(5), "5")
assert_raises(
ValueError,
typ._cached_literal_processor(testing.db.dialect),
"notanint",
)
class BooleanTest(
fixtures.TablesTest, AssertsExecutionResults, AssertsCompiledSQL
):
"""test edge cases for booleans. Note that the main boolean test suite
is now in testing/suite/test_types.py
the default value of create_constraint was changed to False in
version 1.4 with #5367.
"""
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"boolean_table",
metadata,
Column("id", Integer, primary_key=True, autoincrement=False),
Column("value", Boolean(create_constraint=True)),
Column("unconstrained_value", Boolean()),
)
@testing.requires.enforces_check_constraints
@testing.requires.non_native_boolean_unconstrained
def test_constraint(self, connection):
assert_raises(
(exc.IntegrityError, exc.ProgrammingError, exc.OperationalError),
connection.exec_driver_sql,
"insert into boolean_table (id, value) values(1, 5)",
)
@testing.skip_if(lambda: testing.db.dialect.supports_native_boolean)
def test_unconstrained(self, connection):
connection.exec_driver_sql(
"insert into boolean_table (id, unconstrained_value)"
"values (1, 5)"
)
def test_non_native_constraint_custom_type(self):
class Foob(object):
def __init__(self, value):
self.value = value
class MyBool(TypeDecorator):
impl = Boolean(create_constraint=True)
# future method
def process_literal_param(self, value, dialect):
return value.value
def process_bind_param(self, value, dialect):
return value.value
m = MetaData()
t1 = Table("t", m, Column("x", MyBool()))
const = [c for c in t1.constraints if isinstance(c, CheckConstraint)][
0
]
self.assert_compile(
AddConstraint(const),
"ALTER TABLE t ADD CHECK (x IN (0, 1))",
dialect="sqlite",
)
@testing.skip_if(lambda: testing.db.dialect.supports_native_boolean)
def test_nonnative_processor_coerces_to_onezero(self):
boolean_table = self.tables.boolean_table
with testing.db.connect() as conn:
assert_raises_message(
exc.StatementError,
"Value 5 is not None, True, or False",
conn.execute,
boolean_table.insert(),
{"id": 1, "unconstrained_value": 5},
)
@testing.requires.non_native_boolean_unconstrained
def test_nonnative_processor_coerces_integer_to_boolean(self):
boolean_table = self.tables.boolean_table
with testing.db.connect() as conn:
conn.exec_driver_sql(
"insert into boolean_table (id, unconstrained_value) "
"values (1, 5)"
)
eq_(
conn.exec_driver_sql(
"select unconstrained_value from boolean_table"
).scalar(),
5,
)
eq_(
conn.scalar(select(boolean_table.c.unconstrained_value)),
True,
)
def test_bind_processor_coercion_native_true(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=True)
)
is_(proc(True), True)
def test_bind_processor_coercion_native_false(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=True)
)
is_(proc(False), False)
def test_bind_processor_coercion_native_none(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=True)
)
is_(proc(None), None)
def test_bind_processor_coercion_native_0(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=True)
)
is_(proc(0), False)
def test_bind_processor_coercion_native_1(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=True)
)
is_(proc(1), True)
def test_bind_processor_coercion_native_str(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=True)
)
assert_raises_message(
TypeError, "Not a boolean value: 'foo'", proc, "foo"
)
def test_bind_processor_coercion_native_int_out_of_range(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=True)
)
assert_raises_message(
ValueError, "Value 15 is not None, True, or False", proc, 15
)
def test_bind_processor_coercion_nonnative_true(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=False)
)
eq_(proc(True), 1)
def test_bind_processor_coercion_nonnative_false(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=False)
)
eq_(proc(False), 0)
def test_bind_processor_coercion_nonnative_none(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=False)
)
is_(proc(None), None)
def test_bind_processor_coercion_nonnative_0(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=False)
)
eq_(proc(0), 0)
def test_bind_processor_coercion_nonnative_1(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=False)
)
eq_(proc(1), 1)
def test_bind_processor_coercion_nonnative_str(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=False)
)
assert_raises_message(
TypeError, "Not a boolean value: 'foo'", proc, "foo"
)
def test_bind_processor_coercion_nonnative_int_out_of_range(self):
proc = Boolean().bind_processor(
mock.Mock(supports_native_boolean=False)
)
assert_raises_message(
ValueError, "Value 15 is not None, True, or False", proc, 15
)
def test_literal_processor_coercion_native_true(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=True)
)
eq_(proc(True), "true")
def test_literal_processor_coercion_native_false(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=True)
)
eq_(proc(False), "false")
def test_literal_processor_coercion_native_1(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=True)
)
eq_(proc(1), "true")
def test_literal_processor_coercion_native_0(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=True)
)
eq_(proc(0), "false")
def test_literal_processor_coercion_native_str(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=True)
)
assert_raises_message(
TypeError, "Not a boolean value: 'foo'", proc, "foo"
)
def test_literal_processor_coercion_native_int_out_of_range(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=True)
)
assert_raises_message(
ValueError, "Value 15 is not None, True, or False", proc, 15
)
def test_literal_processor_coercion_nonnative_true(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=False)
)
eq_(proc(True), "1")
def test_literal_processor_coercion_nonnative_false(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=False)
)
eq_(proc(False), "0")
def test_literal_processor_coercion_nonnative_1(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=False)
)
eq_(proc(1), "1")
def test_literal_processor_coercion_nonnative_0(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=False)
)
eq_(proc(0), "0")
def test_literal_processor_coercion_nonnative_str(self):
proc = Boolean().literal_processor(
default.DefaultDialect(supports_native_boolean=False)
)
assert_raises_message(
TypeError, "Not a boolean value: 'foo'", proc, "foo"
)
class PickleTest(fixtures.TestBase):
def test_eq_comparison(self):
p1 = PickleType()
for obj in (
{"1": "2"},
pickleable.Bar(5, 6),
pickleable.OldSchool(10, 11),
):
assert p1.compare_values(p1.copy_value(obj), obj)
assert_raises(
NotImplementedError,
p1.compare_values,
pickleable.BrokenComparable("foo"),
pickleable.BrokenComparable("foo"),
)
def test_nonmutable_comparison(self):
p1 = PickleType()
for obj in (
{"1": "2"},
pickleable.Bar(5, 6),
pickleable.OldSchool(10, 11),
):
assert p1.compare_values(p1.copy_value(obj), obj)
meta = None
class CallableTest(fixtures.TestBase):
@classmethod
def setup_class(cls):
global meta
meta = MetaData(testing.db)
@classmethod
def teardown_class(cls):
meta.drop_all()
def test_callable_as_arg(self):
ucode = util.partial(Unicode)
thing_table = Table("thing", meta, Column("name", ucode(20)))
assert isinstance(thing_table.c.name.type, Unicode)
thing_table.create()
def test_callable_as_kwarg(self):
ucode = util.partial(Unicode)
thang_table = Table(
"thang", meta, Column("name", type_=ucode(20), primary_key=True)
)
assert isinstance(thang_table.c.name.type, Unicode)
thang_table.create()
class LiteralTest(fixtures.TestBase):
__backend__ = True
@testing.combinations(
("datetime", datetime.datetime.now()),
("date", datetime.date.today()),
("time", datetime.time()),
argnames="value",
id_="ia",
)
@testing.skip_if(testing.requires.datetime_literals)
def test_render_datetime(self, value):
lit = literal(value)
assert_raises_message(
NotImplementedError,
"Don't know how to literal-quote value.*",
lit.compile,
dialect=testing.db.dialect,
compile_kwargs={"literal_binds": True},
)
| 32.058283
| 79
| 0.569323
|
d4954cce3c233d04d31a4854308e7f241f8f39c6
| 5,993
|
py
|
Python
|
qa/rpc-tests/prioritise_transaction.py
|
realcaesar/skicoinBeta
|
a35cbfda4f70cfa41daa3e80fba95d737ef64449
|
[
"MIT"
] | null | null | null |
qa/rpc-tests/prioritise_transaction.py
|
realcaesar/skicoinBeta
|
a35cbfda4f70cfa41daa3e80fba95d737ef64449
|
[
"MIT"
] | null | null | null |
qa/rpc-tests/prioritise_transaction.py
|
realcaesar/skicoinBeta
|
a35cbfda4f70cfa41daa3e80fba95d737ef64449
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test PrioritiseTransaction code
#
from test_framework.test_framework import SkicoinTestFramework
from test_framework.util import *
from test_framework.mininode import COIN, MAX_BLOCK_SIZE
class PrioritiseTransactionTest(SkicoinTestFramework):
def __init__(self):
self.txouts = gen_return_txouts()
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 1)
def setup_network(self):
self.nodes = []
self.is_network_split = False
self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-printpriority=1"]))
self.relayfee = self.nodes[0].getnetworkinfo()['relayfee']
def run_test(self):
utxo_count = 90
utxos = create_confirmed_utxos(self.relayfee, self.nodes[0], utxo_count)
base_fee = self.relayfee*100 # our transactions are smaller than 100kb
txids = []
# Create 3 batches of transactions at 3 different fee rate levels
range_size = utxo_count // 3
for i in xrange(3):
txids.append([])
start_range = i * range_size
end_range = start_range + range_size
txids[i] = create_lots_of_big_transactions(self.nodes[0], self.txouts, utxos[start_range:end_range], (i+1)*base_fee)
# Make sure that the size of each group of transactions exceeds
# MAX_BLOCK_SIZE -- otherwise the test needs to be revised to create
# more transactions.
mempool = self.nodes[0].getrawmempool(True)
sizes = [0, 0, 0]
for i in xrange(3):
for j in txids[i]:
assert(j in mempool)
sizes[i] += mempool[j]['size']
assert(sizes[i] > MAX_BLOCK_SIZE) # Fail => raise utxo_count
# add a fee delta to something in the cheapest bucket and make sure it gets mined
# also check that a different entry in the cheapest bucket is NOT mined (lower
# the priority to ensure its not mined due to priority)
self.nodes[0].prioritisetransaction(txids[0][0], 0, int(3*base_fee*COIN))
self.nodes[0].prioritisetransaction(txids[0][1], -1e15, 0)
self.nodes[0].generate(1)
mempool = self.nodes[0].getrawmempool()
print "Assert that prioritised transaction was mined"
assert(txids[0][0] not in mempool)
assert(txids[0][1] in mempool)
high_fee_tx = None
for x in txids[2]:
if x not in mempool:
high_fee_tx = x
# Something high-fee should have been mined!
assert(high_fee_tx != None)
# Add a prioritisation before a tx is in the mempool (de-prioritising a
# high-fee transaction so that it's now low fee).
self.nodes[0].prioritisetransaction(high_fee_tx, -1e15, -int(2*base_fee*COIN))
# Add everything back to mempool
self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
# Check to make sure our high fee rate tx is back in the mempool
mempool = self.nodes[0].getrawmempool()
assert(high_fee_tx in mempool)
# Now verify the modified-high feerate transaction isn't mined before
# the other high fee transactions. Keep mining until our mempool has
# decreased by all the high fee size that we calculated above.
while (self.nodes[0].getmempoolinfo()['bytes'] > sizes[0] + sizes[1]):
self.nodes[0].generate(1)
# High fee transaction should not have been mined, but other high fee rate
# transactions should have been.
mempool = self.nodes[0].getrawmempool()
print "Assert that de-prioritised transaction is still in mempool"
assert(high_fee_tx in mempool)
for x in txids[2]:
if (x != high_fee_tx):
assert(x not in mempool)
# Create a free, low priority transaction. Should be rejected.
utxo_list = self.nodes[0].listunspent()
assert(len(utxo_list) > 0)
utxo = utxo_list[0]
inputs = []
outputs = {}
inputs.append({"txid" : utxo["txid"], "vout" : utxo["vout"]})
outputs[self.nodes[0].getnewaddress()] = utxo["amount"] - self.relayfee
raw_tx = self.nodes[0].createrawtransaction(inputs, outputs)
tx_hex = self.nodes[0].signrawtransaction(raw_tx)["hex"]
txid = self.nodes[0].sendrawtransaction(tx_hex)
# A tx that spends an in-mempool tx has 0 priority, so we can use it to
# test the effect of using prioritise transaction for mempool acceptance
inputs = []
inputs.append({"txid": txid, "vout": 0})
outputs = {}
outputs[self.nodes[0].getnewaddress()] = utxo["amount"] - self.relayfee
raw_tx2 = self.nodes[0].createrawtransaction(inputs, outputs)
tx2_hex = self.nodes[0].signrawtransaction(raw_tx2)["hex"]
tx2_id = self.nodes[0].decoderawtransaction(tx2_hex)["txid"]
try:
self.nodes[0].sendrawtransaction(tx2_hex)
except JSONRPCException as exp:
assert_equal(exp.error['code'], -26) # insufficient fee
assert(tx2_id not in self.nodes[0].getrawmempool())
else:
assert(False)
# This is a less than 1000-byte transaction, so just set the fee
# to be the minimum for a 1000 byte transaction and check that it is
# accepted.
self.nodes[0].prioritisetransaction(tx2_id, 0, int(self.relayfee*COIN))
print "Assert that prioritised free transaction is accepted to mempool"
assert_equal(self.nodes[0].sendrawtransaction(tx2_hex), tx2_id)
assert(tx2_id in self.nodes[0].getrawmempool())
if __name__ == '__main__':
PrioritiseTransactionTest().main()
| 41.618056
| 128
| 0.646755
|
fbf4e74f60f2629eb8be8cca26802045f43e39e8
| 5,648
|
py
|
Python
|
smartshark/forms.py
|
benjaminLedel/serverSHARK
|
97decc03ba7bde8ad9c5f55d446d21ed5a26709c
|
[
"Apache-2.0"
] | 1
|
2019-11-09T21:18:05.000Z
|
2019-11-09T21:18:05.000Z
|
smartshark/forms.py
|
ArtyMandy/serverSHARK
|
7d3ce83c2bf310aeea7832dedbdaccd44ae7b1df
|
[
"Apache-2.0"
] | 34
|
2017-09-28T12:38:15.000Z
|
2022-01-21T06:59:01.000Z
|
smartshark/forms.py
|
midasdev711/serverSHARK-backend
|
989f242c5454aaf913734cdb5779e90408be74cb
|
[
"Apache-2.0"
] | 8
|
2018-05-23T12:46:45.000Z
|
2021-12-04T09:23:48.000Z
|
from difflib import SequenceMatcher
from django.forms import HiddenInput
from django.shortcuts import get_object_or_404
from form_utils.forms import BetterForm
from server.base import SUBSTITUTIONS
from .datacollection.pluginmanagementinterface import PluginManagementInterface
from .models import Plugin, Argument, ExecutionHistory, PluginExecution
from django import forms
from .mongohandler import handler
class ProjectForm(forms.Form):
plugins = forms.ModelMultipleChoiceField(queryset=Plugin.objects.all().filter(active=True, installed=True))
class SparkSubmitForm(forms.Form):
change_form_template = 'progressbarupload/change_form.html'
add_form_template = 'progressbarupload/change_form.html'
file = forms.FileField(label='Jar / Python File')
class_name = forms.CharField(label='Fully Qualified Class Name', max_length=300, required=False)
arguments = forms.CharField(label='Arguments', max_length=1000, required=False)
def set_argument_values(form_data):
for id_string, value in form_data.items():
if "argument" in id_string:
parts = id_string.split("_")
argument_id = parts[2]
argument = get_object_or_404(Argument, pk=argument_id)
argument.install_value = value
argument.save()
def set_argument_execution_values(form_data, plugin_executions):
for id_string, value in form_data.items():
if "argument" in id_string:
parts = id_string.split("_")
plugin_id = parts[0]
argument_id = parts[2]
for plugin_execution in plugin_executions:
if plugin_execution.plugin.id == int(plugin_id):
found_plugin_execution = plugin_execution
exe = ExecutionHistory(execution_argument=get_object_or_404(Argument, pk=argument_id),
plugin_execution=found_plugin_execution,
execution_value=value)
exe.save()
def get_form(plugins, post, type, project=None, initial_revisions=None, initial_exec_type=None):
created_fieldsets = []
plugin_fields = {}
EXEC_OPTIONS = (('all', 'Execute on all revisions'), ('error', 'Execute on all revisions with errors'),
('new', 'Execute on new revisions'), ('rev', 'Execute on following revisions:'), ('ver', 'Execute on all revisions where verification failed for one Plugin'))
# we need to get the correct pluginmanager for this information because that depends on selected queue
interface = PluginManagementInterface.find_correct_plugin_manager()
cores_per_job = interface.default_cores_per_job()
queue = interface.default_queue()
added_fields = []
if type == 'execute':
vcs_url = ''
if project:
vcs_url = handler.get_vcs_url_for_project_id(project.mongo_id)
# Add fields if there are plugins that work on revision level
rev_plugins = [plugin for plugin in plugins if plugin.plugin_type == 'rev']
if len(rev_plugins) > 0:
plugin_fields['execution'] = forms.ChoiceField(widget=forms.RadioSelect, choices=EXEC_OPTIONS, initial=initial_exec_type)
plugin_fields['revisions'] = forms.CharField(label='Revisions (comma-separated)', required=False, initial=initial_revisions, widget=forms.Textarea)
added_fields.append('execution')
added_fields.append('revisions')
repo_plugins = [plugin for plugin in plugins if plugin.plugin_type == 'repo']
# If we have revision or repository plugins, we need to ask for the repository to use
if len(rev_plugins) > 0 or len(repo_plugins) > 0:
plugin_fields['repository_url'] = forms.CharField(label='Repository URL', required=True, initial=vcs_url)
added_fields.append('repository_url')
plugin_fields['queue'] = forms.CharField(label='Default job queue', initial=queue, required=False)
added_fields.append('queue')
plugin_fields['cores_per_job'] = forms.IntegerField(label='Cores per job (HPC only)', initial=cores_per_job, required=False)
added_fields.append('cores_per_job')
created_fieldsets.append(['Basis Configuration', {'fields': added_fields}])
# Create lists for the fieldsets and a list for the fields of the form
for plugin in plugins:
arguments = []
for argument in plugin.argument_set.all().filter(type=type):
identifier = '%s_argument_%s' % (plugin.id, argument.id)
arguments.append(identifier)
initial = None
for name, value in SUBSTITUTIONS.items():
if SequenceMatcher(None, argument.name, name).ratio() > 0.8:
initial = value['name']
if argument.name == 'repository_url':
initial = vcs_url
plugin_fields[identifier] = forms.CharField(label=argument.name, required=argument.required,
initial=initial, help_text=argument.description)
created_fieldsets.append([str(plugin), {'fields': arguments}])
# Dynamically created pluginform
class PluginForm(BetterForm):
class Meta:
fieldsets = created_fieldsets
def __init__(self, *args, **kwargs):
super(PluginForm, self).__init__(*args, **kwargs)
self.fields = plugin_fields
return PluginForm(post)
| 45.918699
| 182
| 0.651204
|
803ad3e702c20f4509af84f34ed355d63bfa6362
| 543
|
py
|
Python
|
E002.py
|
mariomtzjr/asyncio
|
1908107e93393ab6ac9f909bc245f694ab353443
|
[
"MIT"
] | null | null | null |
E002.py
|
mariomtzjr/asyncio
|
1908107e93393ab6ac9f909bc245f694ab353443
|
[
"MIT"
] | null | null | null |
E002.py
|
mariomtzjr/asyncio
|
1908107e93393ab6ac9f909bc245f694ab353443
|
[
"MIT"
] | null | null | null |
# Importamos asyncio
import asyncio
# definimos la función
async def show_seconds():
while True:
for i in range(60):
print(i, 's')
await asyncio.sleep(1)
async def show_minute():
for i in range(1, 10):
await asyncio.sleep(60)
print(i, 'minuto')
loop = asyncio.get_event_loop()
asyncio.set_event_loop(loop)
# Con gather, podemos ejecutar las dos rutinas simultaneamente
loop.run_until_complete(
asyncio.gather(
show_seconds(),
show_minute()
)
)
loop.close()
| 18.724138
| 62
| 0.640884
|
55c85c1ea5be64b7eaee9892897130d22c786d9d
| 10,444
|
py
|
Python
|
tensorflow/bert-tf2/gpu_movie_reviews.py
|
Phaeton-lang/baselines
|
472c248047fbb55b5fa0e620758047b7f0a1d041
|
[
"MIT"
] | null | null | null |
tensorflow/bert-tf2/gpu_movie_reviews.py
|
Phaeton-lang/baselines
|
472c248047fbb55b5fa0e620758047b7f0a1d041
|
[
"MIT"
] | null | null | null |
tensorflow/bert-tf2/gpu_movie_reviews.py
|
Phaeton-lang/baselines
|
472c248047fbb55b5fa0e620758047b7f0a1d041
|
[
"MIT"
] | null | null | null |
import math
import datetime
from tqdm import tqdm
import pandas as pd
import numpy as np
import tensorflow as tf
import bert
from bert import BertModelLayer
from bert.loader import StockBertConfig, map_stock_config_to_params, load_stock_weights
from bert.tokenization.bert_tokenization import FullTokenizer
## Load Data!!!
from tensorflow import keras
import os
import re
import argparse
import time
parser = argparse.ArgumentParser()
parser.add_argument("--epochs", type=int,
default=2,
help='Number of epochs to run. (Default 2)')
parser.add_argument("--steps", type=int,
default=5,
help='Number of steps per epoch. (Default 5)')
parser.add_argument("--batch_size", type=int,
default=48,
help='Batch size. (Default 48)')
# LMS parameters
lms_group = parser.add_mutually_exclusive_group(required=False)
lms_group.add_argument('--lms', dest='lms', action='store_true',
help='Enable LMS')
lms_group.add_argument('--no-lms', dest='lms', action='store_false',
help='Disable LMS (Default)')
parser.set_defaults(lms=False)
args = parser.parse_args()
if args.lms:
tf.config.experimental.set_lms_enabled(True)
tf.experimental.get_peak_bytes_active(0)
# Load all files from a directory in a DataFrame.
def load_directory_data(directory):
data = {}
data["sentence"] = []
data["sentiment"] = []
for file_path in tqdm(os.listdir(directory), desc=os.path.basename(directory)):
with tf.io.gfile.GFile(os.path.join(directory, file_path), "r") as f:
data["sentence"].append(f.read())
data["sentiment"].append(re.match("\d+_(\d+)\.txt", file_path).group(1))
return pd.DataFrame.from_dict(data)
# Merge positive and negative examples, add a polarity column and shuffle.
def load_dataset(directory):
pos_df = load_directory_data(os.path.join(directory, "pos"))
neg_df = load_directory_data(os.path.join(directory, "neg"))
pos_df["polarity"] = 1
neg_df["polarity"] = 0
return pd.concat([pos_df, neg_df]).sample(frac=1).reset_index(drop=True)
# Download and process the dataset files.
def download_and_load_datasets(force_download=False):
dataset = tf.keras.utils.get_file(
fname="aclImdb.tar.gz",
origin="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz",
extract=True)
train_df = load_dataset(os.path.join(os.path.dirname(dataset),
"aclImdb", "train"))
test_df = load_dataset(os.path.join(os.path.dirname(dataset),
"aclImdb", "test"))
return train_df, test_df
import bert
from bert import BertModelLayer
from bert.loader import StockBertConfig, map_stock_config_to_params, load_stock_weights
class MovieReviewData:
DATA_COLUMN = "sentence"
LABEL_COLUMN = "polarity"
def __init__(self, tokenizer: FullTokenizer, sample_size=None, max_seq_len=1024):
self.tokenizer = tokenizer
self.sample_size = sample_size
self.max_seq_len = 0
train, test = download_and_load_datasets()
train, test = map(lambda df: df.reindex(df[MovieReviewData.DATA_COLUMN].str.len().sort_values().index),
[train, test])
if sample_size is not None:
assert sample_size % 128 == 0
train, test = train.head(sample_size), test.head(sample_size)
# train, test = map(lambda df: df.sample(sample_size), [train, test])
((self.train_x, self.train_y),
(self.test_x, self.test_y)) = map(self._prepare, [train, test])
print("max seq_len:", self.max_seq_len)
self.max_seq_len = min(self.max_seq_len, max_seq_len)
((self.train_x, self.train_x_token_types),
(self.test_x, self.test_x_token_types)) = map(self._pad,
[self.train_x, self.test_x])
def _prepare(self, df):
x, y = [], []
with tqdm(total=df.shape[0], unit_scale=True) as pbar:
for ndx, row in df.iterrows():
text, label = row[MovieReviewData.DATA_COLUMN], row[MovieReviewData.LABEL_COLUMN]
tokens = self.tokenizer.tokenize(text)
tokens = ["[CLS]"] + tokens + ["[SEP]"]
token_ids = self.tokenizer.convert_tokens_to_ids(tokens)
self.max_seq_len = max(self.max_seq_len, len(token_ids))
x.append(token_ids)
y.append(int(label))
pbar.update()
return np.array(x), np.array(y)
def _pad(self, ids):
x, t = [], []
token_type_ids = [0] * self.max_seq_len
for input_ids in ids:
input_ids = input_ids[:min(len(input_ids), self.max_seq_len - 2)]
input_ids = input_ids + [0] * (self.max_seq_len - len(input_ids))
x.append(np.array(input_ids))
t.append(token_type_ids)
return np.array(x), np.array(t)
bert_model_name="uncased_L-12_H-768_A-12"
bert_ckpt_dir = os.path.join(".model/",bert_model_name)
bert_ckpt_file = os.path.join(bert_ckpt_dir, "bert_model.ckpt")
bert_config_file = os.path.join(bert_ckpt_dir, "bert_config.json")
# perparing data
tokenizer = FullTokenizer(vocab_file=os.path.join(bert_ckpt_dir, "vocab.txt"))
data = MovieReviewData(tokenizer,
sample_size=10*128*2,#5000,
max_seq_len=128)
print(" train_x:", data.train_x.shape)
print("train_x_token_types:", data.train_x_token_types.shape)
print(" train_y:", data.train_y.shape)
print(" test_x:", data.test_x.shape)
print(" max_seq_len:", data.max_seq_len)
# train_x: (2560, 128)
#train_x_token_types: (2560, 128)
# train_y: (2560,)
# test_x: (2560, 128)
# max_seq_len: 128
def flatten_layers(root_layer):
if isinstance(root_layer, keras.layers.Layer):
yield root_layer
for layer in root_layer._layers:
for sub_layer in flatten_layers(layer):
yield sub_layer
def freeze_bert_layers(l_bert):
"""
Freezes all but LayerNorm and adapter layers - see arXiv:1902.00751.
"""
for layer in flatten_layers(l_bert):
if layer.name in ["LayerNorm", "adapter-down", "adapter-up"]:
layer.trainable = True
elif len(layer._layers) == 0:
layer.trainable = False
l_bert.embeddings_layer.trainable = False
def create_learning_rate_scheduler(max_learn_rate=5e-5,
end_learn_rate=1e-7,
warmup_epoch_count=10,
total_epoch_count=90):
def lr_scheduler(epoch):
if epoch < warmup_epoch_count:
res = (max_learn_rate/warmup_epoch_count) * (epoch + 1)
else:
res = max_learn_rate*math.exp(math.log(end_learn_rate/max_learn_rate)*(epoch-warmup_epoch_count+1)/(total_epoch_count-warmup_epoch_count+1))
return float(res)
learning_rate_scheduler = tf.keras.callbacks.LearningRateScheduler(lr_scheduler, verbose=1)
return learning_rate_scheduler
def create_model(max_seq_len, adapter_size=64):
"""Creates a classification model."""
#adapter_size = 64 # see - arXiv:1902.00751
# create the bert layer
with tf.io.gfile.GFile(bert_config_file, "r") as reader:
bc = StockBertConfig.from_json_string(reader.read())
bert_params = map_stock_config_to_params(bc)
bert_params.adapter_size = adapter_size
bert = BertModelLayer.from_params(bert_params, name="bert")
input_ids = keras.layers.Input(shape=(max_seq_len,), dtype='int32', name="input_ids")
# token_type_ids = keras.layers.Input(shape=(max_seq_len,), dtype='int32', name="token_type_ids")
# output = bert([input_ids, token_type_ids])
output = bert(input_ids)
print("bert shape:", output.shape)
cls_out = keras.layers.Lambda(lambda seq: seq[:, 0, :])(output)
cls_out = keras.layers.Dropout(0.5)(cls_out)
logits = keras.layers.Dense(units=768, activation="tanh")(cls_out)
logits = keras.layers.Dropout(0.5)(logits)
logits = keras.layers.Dense(units=2, activation="softmax")(logits)
# model = keras.Model(inputs=[input_ids, token_type_ids], outputs=logits)
# model.build(input_shape=[(None, max_seq_len), (None, max_seq_len)])
model = keras.Model(inputs=input_ids, outputs=logits)
model.build(input_shape=(None, max_seq_len))
# load the pre-trained model weights
load_stock_weights(bert, bert_ckpt_file)
# freeze weights if adapter-BERT is used
if adapter_size is not None:
freeze_bert_layers(bert)
model.compile(optimizer=keras.optimizers.Adam(),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[keras.metrics.SparseCategoricalAccuracy(name="acc")])
model.summary()
return model
adapter_size = None # use None to fine-tune all of BERT
model = create_model(data.max_seq_len, adapter_size=adapter_size)
log_dir = ".log/movie_reviews/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%s")
tensorboard_callback = keras.callbacks.TensorBoard(log_dir=log_dir)
total_epoch_count = args.epochs
# model.fit(x=(data.train_x, data.train_x_token_types), y=data.train_y,
start_time = int(round(time.time()*1000))
model.fit(x=data.train_x, y=data.train_y,
validation_split=0.1,
batch_size=args.batch_size,
steps_per_epoch=args.steps,
shuffle=True,
epochs=total_epoch_count,
callbacks=[create_learning_rate_scheduler(max_learn_rate=1e-5,
end_learn_rate=1e-7,
warmup_epoch_count=20,
total_epoch_count=total_epoch_count),
keras.callbacks.EarlyStopping(patience=20, restore_best_weights=True),
tensorboard_callback])
end_time = int(round(time.time()*1000))
throughput = args.epochs * args.batch_size / (end_time - start_time) * 1000
print('\n')
print('training throughput: {}'.format(throughput))
print('peak active bytes(MB): {}'.format(tf.experimental.get_peak_bytes_active(0)/1024.0/1024.0))
#model.save_weights('./movie_reviews.h5', overwrite=True)
#_, train_acc = model.evaluate(data.train_x, data.train_y)
#print("train acc:", train_acc)
| 40.48062
| 152
| 0.654538
|
a8aad70072f7f0b12fb0db2bc660917ba7be0b75
| 3,077
|
py
|
Python
|
mayan/apps/cabinets/urls.py
|
wan1869/dushuhu
|
934dd178e67140cffc6b9203e793fdf8bbc73a54
|
[
"Apache-2.0"
] | null | null | null |
mayan/apps/cabinets/urls.py
|
wan1869/dushuhu
|
934dd178e67140cffc6b9203e793fdf8bbc73a54
|
[
"Apache-2.0"
] | null | null | null |
mayan/apps/cabinets/urls.py
|
wan1869/dushuhu
|
934dd178e67140cffc6b9203e793fdf8bbc73a54
|
[
"Apache-2.0"
] | null | null | null |
from django.conf.urls import url
from .api_views import (
APIDocumentCabinetListView, APICabinetDocumentListView,
APICabinetDocumentView, APICabinetListView, APICabinetView
)
from .views import (
DocumentAddToCabinetView, DocumentCabinetListView,
DocumentRemoveFromCabinetView, CabinetChildAddView, CabinetCreateView,
CabinetDeleteView, CabinetDetailView, CabinetEditView, CabinetListView,CabinetListView4doc,
)
urlpatterns_cabinets = [
url(
regex=r'^cabinets/$', name='cabinet_list',
view=CabinetListView.as_view()
),
# 客户化代码,在文档管理中增加文档中心链接
url(
regex=r'^cabinets4doc/$', name='cabinet_list4doc',
view=CabinetListView4doc.as_view()
),
url(
regex=r'^cabinets/create/$', name='cabinet_create',
view=CabinetCreateView.as_view()
),
url(
regex=r'^cabinets/(?P<cabinet_id>\d+)/$', name='cabinet_view',
view=CabinetDetailView.as_view()
),
url(
regex=r'^cabinets/(?P<cabinet_id>\d+)/children/add/$',
name='cabinet_child_add', view=CabinetChildAddView.as_view()
),
url(
regex=r'^cabinets/(?P<cabinet_id>\d+)/delete/$',
name='cabinet_delete', view=CabinetDeleteView.as_view()
),
url(
regex=r'^cabinets/(?P<cabinet_id>\d+)/edit/$', name='cabinet_edit',
view=CabinetEditView.as_view()
),
]
urlpatterns_documents_cabinets = [
url(
regex=r'^documents/(?P<document_id>\d+)/cabinets/$',
name='document_cabinet_list', view=DocumentCabinetListView.as_view()
),
url(
regex=r'^documents/(?P<document_id>\d+)/cabinets/add/$',
name='document_cabinet_add', view=DocumentAddToCabinetView.as_view()
),
url(
regex=r'^documents/multiple/cabinets/add/$',
name='document_multiple_cabinet_add',
view=DocumentAddToCabinetView.as_view()
),
url(
regex=r'^documents/(?P<document_id>\d+)/cabinets/remove/$',
name='document_cabinet_remove',
view=DocumentRemoveFromCabinetView.as_view()
),
url(
regex=r'^documents/multiple/cabinets/remove/$',
name='multiple_document_cabinet_remove',
view=DocumentRemoveFromCabinetView.as_view()
)
]
urlpatterns = []
urlpatterns.extend(urlpatterns_cabinets)
urlpatterns.extend(urlpatterns_documents_cabinets)
api_urls = [
url(
regex=r'^cabinets/(?P<pk>[0-9]+)/documents/(?P<document_pk>[0-9]+)/$',
name='cabinet-document', view=APICabinetDocumentView.as_view()
),
url(
regex=r'^cabinets/(?P<pk>[0-9]+)/documents/$',
name='cabinet-document-list',
view=APICabinetDocumentListView.as_view()
),
url(
regex=r'^cabinets/(?P<pk>[0-9]+)/$', name='cabinet-detail',
view=APICabinetView.as_view()
),
url(
regex=r'^cabinets/$', name='cabinet-list',
view=APICabinetListView.as_view()
),
url(
regex=r'^documents/(?P<pk>[0-9]+)/cabinets/$',
name='document-cabinet-list',
view=APIDocumentCabinetListView.as_view()
),
]
| 31.080808
| 95
| 0.646409
|
ecb31c956ce5573dd85394d8430de0e2919c03ba
| 10,835
|
py
|
Python
|
hpcc/2020-07-24--competition-evo-arch/gen-comp-exp-phase1.py
|
amlalejini/Aagos
|
bb82da3a177fe467a912c9f44f516b445b4eba3b
|
[
"MIT"
] | null | null | null |
hpcc/2020-07-24--competition-evo-arch/gen-comp-exp-phase1.py
|
amlalejini/Aagos
|
bb82da3a177fe467a912c9f44f516b445b4eba3b
|
[
"MIT"
] | null | null | null |
hpcc/2020-07-24--competition-evo-arch/gen-comp-exp-phase1.py
|
amlalejini/Aagos
|
bb82da3a177fe467a912c9f44f516b445b4eba3b
|
[
"MIT"
] | null | null | null |
'''
Generate slurm job submission script for 2020-05-18 -- environmental change rate experiment.
See 2020-05-18--env-chg-sweep/README.md for more details.
'''
import argparse, os, sys, errno, subprocess, csv
seed_offset = 970000
default_num_replicates = 100
job_time_request = "00:20:00"
job_memory_request = "2G"
job_name = "phase1"
nk_config = {
"environment_change": [
"-CHANGE_FREQUENCY 0"
]
}
gradient_config = {
"environment_change": [
"-CHANGE_FREQUENCY 0"
]
}
shared_config = {
"paired": [
"-BIT_FLIP_PROB 0.003",
"-BIT_FLIP_PROB 0.1"
]
}
base_resub_script = \
"""#!/bin/bash
########## Define Resources Needed with SBATCH Lines ##########
#SBATCH --time=<<TIME_REQUEST>> # limit of wall clock time - how long the job will run (same as -t)
#SBATCH --array=<<ARRAY_ID_RANGE>>
#SBATCH --mem=<<MEMORY_REQUEST>> # memory required per node - amount of memory (in bytes)
#SBATCH --job-name <<JOB_NAME>> # you can give your job a name for easier identification (same as -J)
#SBATCH --account=devolab
########## Command Lines to Run ##########
EXEC=Aagos
CONFIG_DIR=<<CONFIG_DIR>>
module load GCC/7.3.0-2.30
module load OpenMPI/3.1.1
module load Python/3.7.0
<<RESUBMISSION_LOGIC>>
mkdir -p ${RUN_DIR}
cd ${RUN_DIR}
cp ${CONFIG_DIR}/Aagos.cfg .
cp ${CONFIG_DIR}/${EXEC} .
./${EXEC} ${RUN_PARAMS} > run.log
rm Aagos.cfg
rm ${EXEC}
"""
base_run_logic = \
"""
if [[ ${SLURM_ARRAY_TASK_ID} -eq <<RESUB_ID>> ]] ; then
RUN_DIR=<<RUN_DIR>>
RUN_PARAMS=<<RUN_PARAMS>>
fi
"""
'''
This is functionally equivalent to the mkdir -p [fname] bash command
'''
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
def extract_settings(run_config_path):
content = None
with open(run_config_path, "r") as fp:
content = fp.read().strip().split("\n")
header = content[0].split(",")
header_lu = {header[i].strip():i for i in range(0, len(header))}
content = content[1:]
configs = [l for l in csv.reader(content, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True)]
return {param[header_lu["parameter"]]:param[header_lu["value"]] for param in configs}
def is_run_complete(path):
# (1) Does the run directory exist?
print(f" Run dir? {os.path.exists(path)}")
if not os.path.exists(path): return False
# (2) If the run directory exists, did the run complete?
# Is there a run config file?
run_config_path = os.path.join(path, "output", "run_config.csv")
print(f" Run config? {os.path.exists(run_config_path)}")
if not os.path.exists(run_config_path): return False
# The run config file exists, extract parameters.
run_params = extract_settings(run_config_path)
final_gen = run_params["TOTAL_GENS"] # We'll look for this generation in the fitness.csv file
fitness_file_path = os.path.join(path, "output", "fitness.csv")
print(f" Fitness file? {os.path.exists(fitness_file_path)}")
if not os.path.exists(fitness_file_path): return False
fitness_contents = None
with open(fitness_file_path, "r") as fp:
fitness_contents = fp.read().strip().split("\n")
if len(fitness_contents) == 0: return False
header = fitness_contents[0].split(",")
header_lu = {header[i].strip():i for i in range(0, len(header))}
last_line = fitness_contents[-1].split(",")
print(f" len(header) == len(last_line)? {len(header) == len(last_line)}")
if len(header) != len(last_line): return False
final_fitness_update = last_line[header_lu["update"]]
print(f" {final_fitness_update} =?= {final_gen}")
if final_fitness_update != final_gen: return False
return True
def main():
parser = argparse.ArgumentParser(description="Run submission script.")
parser.add_argument("--data_dir", type=str, help="Where is the base output directory for each run?")
parser.add_argument("--config_dir", type=str, help="Where is the configuration directory for experiment?")
parser.add_argument("--replicates", type=int, default=default_num_replicates, help="How many replicates should we run of each condition?")
parser.add_argument("--query_condition_cnt", action="store_true", help="How many conditions?")
args = parser.parse_args()
data_dir = args.data_dir
config_dir = args.config_dir
num_replicates = args.replicates
# Find all environments
nk_env_dir = os.path.join(config_dir, "environments", "nk")
nk_environments = [os.path.join(nk_env_dir, d) for d in os.listdir(nk_env_dir) if ".env" in d]
nk_environments.sort(key=lambda x : int(x.split(".env")[0].split("_")[-1]))
print(f"Found {len(nk_environments)} nk environments.")
gradient_env_dir = os.path.join(config_dir, "environments", "gradient")
gradient_environments = [os.path.join(gradient_env_dir, d) for d in os.listdir(gradient_env_dir) if ".env" in d]
gradient_environments.sort(key=lambda x : int(x.split(".env")[0].split("_")[-1]))
print(f"Found {len(gradient_environments)} gradient environments.")
if len(gradient_environments) != num_replicates:
print("num_replicates =/= number gradient environments")
exit(-1)
if len(nk_environments) != num_replicates:
print("num_replicates =/= number gradient environments")
exit(-1)
# Compute all combinations of NK fitness model settings and gradient fitness settings
nk_combos = [f"{chg} {mut} -GRADIENT_MODEL 0" for chg in nk_config["environment_change"] for mut in shared_config["paired"] ]
gradient_combos = [f"{chg} {mut} -GRADIENT_MODEL 1" for chg in gradient_config["environment_change"] for mut in shared_config["paired"] ]
# Combine
combos = gradient_combos + nk_combos
if (args.query_condition_cnt):
print("Conditions", combos)
print(f"Number of conditions: {len(combos)}")
exit(0)
# Find complete/incomplete runs.
num_finished = 0
resubmissions = []
nk_run_pairings = {i:[] for i in range(len(nk_environments))}
grad_run_pairings = {i:[] for i in range(len(gradient_environments))}
for condition_id in range(0, len(combos)):
condition_params = combos[condition_id]
print(f"Processing condition: {condition_params}")
# Run N replicates of this condition.
gradient_env_id = 0
nk_env_id = 0
for i in range(1, num_replicates+1):
# Compute seed for this replicate.
seed = seed_offset + (condition_id * num_replicates) + i
run_name = f"SEED_{seed}"
run_dir = os.path.join(data_dir, run_name)
env = None
if "-GRADIENT_MODEL 0" in condition_params:
env = nk_environments[nk_env_id]
nk_run_pairings[nk_env_id].append({"seed": seed, "run_dir": run_dir, "condition": condition_params})
nk_env_id += 1
elif "-GRADIENT_MODEL 1" in condition_params:
env = gradient_environments[gradient_env_id]
grad_run_pairings[gradient_env_id].append({"seed": seed, "run_dir": run_dir, "condition": condition_params})
gradient_env_id += 1
else:
print("????")
exit(-1)
# Generate run parameters, use to name run.
run_params = condition_params + f" -SEED {seed} -LOAD_ENV_FILE {env}"
# (1) Does the run directory exist?
print(f" {run_params}")
run_complete = is_run_complete(run_dir)
print(f" finished? {run_complete}")
num_finished += int(run_complete)
if not run_complete: resubmissions.append({"run_dir": run_dir, "run_params": run_params})
print(f"Runs finished: {num_finished}")
print(f"Resubmissions: {len(resubmissions)}")
print("Generating run pairings...")
pairings_header = ["gradient_model", "env", "seed_0", "run_dir_0", "condition_0", "seed_1", "run_dir_1", "condition_1"]
pairings_content = [",".join(pairings_header)]
for env_id in grad_run_pairings:
if len(grad_run_pairings[env_id]) != 2:
print("Gradient run pairing is not 2!")
exit(-1)
info = {
"gradient_model": "1",
"seed_0": str(grad_run_pairings[env_id][0]["seed"]),
"run_dir_0": str(grad_run_pairings[env_id][0]["run_dir"]),
"seed_1": str(grad_run_pairings[env_id][1]["seed"]),
"run_dir_1": str(grad_run_pairings[env_id][1]["run_dir"]),
"env": gradient_environments[env_id],
"condition_0": str(grad_run_pairings[env_id][0]["condition"]),
"condition_1": str(grad_run_pairings[env_id][1]["condition"])
}
pairings_content.append(",".join([info[key] for key in pairings_header]))
for env_id in nk_run_pairings:
if len(nk_run_pairings[env_id]) != 2:
print("NK run pairing is not 2!")
exit(-1)
info = {
"gradient_model": "0",
"seed_0": str(nk_run_pairings[env_id][0]["seed"]),
"run_dir_0": str(nk_run_pairings[env_id][0]["run_dir"]),
"seed_1": str(nk_run_pairings[env_id][1]["seed"]),
"run_dir_1": str(nk_run_pairings[env_id][1]["run_dir"]),
"env": nk_environments[env_id],
"condition_0": str(nk_run_pairings[env_id][0]["condition"]),
"condition_1": str(nk_run_pairings[env_id][1]["condition"])
}
pairings_content.append(",".join([info[key] for key in pairings_header]))
with open("run_pairings.csv", "w") as fp:
fp.write("\n".join(pairings_content))
print("Generating resubmission script...")
if len(resubmissions) == 0: return
resub_logic = ""
array_id = 1
for resub in resubmissions:
run_params = resub["run_params"]
run_logic = base_run_logic
run_logic = run_logic.replace("<<RESUB_ID>>", str(array_id))
run_logic = run_logic.replace("<<RUN_DIR>>", resub["run_dir"])
run_logic = run_logic.replace("<<RUN_PARAMS>>", f"'{run_params}'")
resub_logic += run_logic
array_id += 1
script = base_resub_script
script = script.replace("<<TIME_REQUEST>>", job_time_request)
script = script.replace("<<ARRAY_ID_RANGE>>", f"1-{len(resubmissions)}")
script = script.replace("<<MEMORY_REQUEST>>", job_memory_request)
script = script.replace("<<JOB_NAME>>", job_name)
script = script.replace("<<CONFIG_DIR>>", config_dir)
script = script.replace("<<RESUBMISSION_LOGIC>>", resub_logic)
with open("phase1-sub.sb", "w") as fp:
fp.write(script)
if __name__ == "__main__":
main()
| 38.151408
| 142
| 0.642547
|
dc8d1deddb26172a724deaf51a0403302554d9f2
| 8,550
|
py
|
Python
|
tensorflow/python/keras/integration_test.py
|
rickyzhang82/tensorflow
|
397fdb37bc923f1f56d0224617cfd1b1dfd76d99
|
[
"Apache-2.0"
] | 3
|
2021-01-19T20:24:09.000Z
|
2021-01-19T21:40:05.000Z
|
tensorflow/python/keras/integration_test.py
|
rickyzhang82/tensorflow
|
397fdb37bc923f1f56d0224617cfd1b1dfd76d99
|
[
"Apache-2.0"
] | 1
|
2019-07-27T16:45:02.000Z
|
2019-07-27T16:45:02.000Z
|
tensorflow/python/keras/integration_test.py
|
rickyzhang82/tensorflow
|
397fdb37bc923f1f56d0224617cfd1b1dfd76d99
|
[
"Apache-2.0"
] | 2
|
2018-12-20T17:53:37.000Z
|
2018-12-27T18:49:13.000Z
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Integration tests for Keras."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python import keras
from tensorflow.python.framework import dtypes
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import testing_utils
from tensorflow.python.ops import rnn_cell
from tensorflow.python.platform import test
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes
class VectorClassificationIntegrationTest(keras_parameterized.TestCase):
def test_vector_classification(self):
np.random.seed(1337)
(x_train, y_train), _ = testing_utils.get_test_data(
train_samples=100,
test_samples=0,
input_shape=(10,),
num_classes=2)
y_train = keras.utils.to_categorical(y_train)
model = testing_utils.get_model_from_layers(
[keras.layers.Dense(16, activation='relu'),
keras.layers.Dropout(0.1),
keras.layers.Dense(y_train.shape[-1], activation='softmax')],
input_shape=x_train.shape[1:])
model.compile(loss='categorical_crossentropy',
optimizer=keras.optimizer_v2.adam.Adam(0.005),
metrics=['accuracy'],
run_eagerly=testing_utils.should_run_eagerly())
history = model.fit(x_train, y_train, epochs=10, batch_size=10,
validation_data=(x_train, y_train),
verbose=2)
self.assertGreater(history.history['val_acc'][-1], 0.7)
_, val_acc = model.evaluate(x_train, y_train)
self.assertAlmostEqual(history.history['val_acc'][-1], val_acc)
predictions = model.predict(x_train)
self.assertEqual(predictions.shape, (x_train.shape[0], 2))
def test_vector_classification_shared_model(self):
# Test that Sequential models that feature internal updates
# and internal losses can be shared.
np.random.seed(1337)
(x_train, y_train), _ = testing_utils.get_test_data(
train_samples=100,
test_samples=0,
input_shape=(10,),
num_classes=2)
y_train = keras.utils.to_categorical(y_train)
base_model = testing_utils.get_model_from_layers(
[keras.layers.Dense(16,
activation='relu',
kernel_regularizer=keras.regularizers.l2(1e-5),
bias_regularizer=keras.regularizers.l2(1e-5)),
keras.layers.BatchNormalization()],
input_shape=x_train.shape[1:])
x = keras.layers.Input(x_train.shape[1:])
y = base_model(x)
y = keras.layers.Dense(y_train.shape[-1], activation='softmax')(y)
model = keras.models.Model(x, y)
model.compile(loss='categorical_crossentropy',
optimizer=keras.optimizer_v2.adam.Adam(0.005),
metrics=['accuracy'],
run_eagerly=testing_utils.should_run_eagerly())
if not testing_utils.should_run_eagerly():
self.assertEqual(len(model.losses), 2)
self.assertEqual(len(model.updates), 2)
history = model.fit(x_train, y_train, epochs=10, batch_size=10,
validation_data=(x_train, y_train),
verbose=2)
self.assertGreater(history.history['val_acc'][-1], 0.7)
_, val_acc = model.evaluate(x_train, y_train)
self.assertAlmostEqual(history.history['val_acc'][-1], val_acc)
predictions = model.predict(x_train)
self.assertEqual(predictions.shape, (x_train.shape[0], 2))
# See b/122473407
@keras_parameterized.run_all_keras_modes(always_skip_v1=True)
class TimeseriesClassificationIntegrationTest(keras_parameterized.TestCase):
@keras_parameterized.run_with_all_model_types
def test_timeseries_classification(self):
np.random.seed(1337)
(x_train, y_train), _ = testing_utils.get_test_data(
train_samples=100,
test_samples=0,
input_shape=(4, 10),
num_classes=2)
y_train = keras.utils.to_categorical(y_train)
layers = [
keras.layers.LSTM(5, return_sequences=True),
keras.layers.GRU(y_train.shape[-1], activation='softmax')
]
model = testing_utils.get_model_from_layers(
layers, input_shape=x_train.shape[1:])
model.compile(loss='categorical_crossentropy',
optimizer=keras.optimizer_v2.adam.Adam(0.005),
metrics=['accuracy'],
run_eagerly=testing_utils.should_run_eagerly())
history = model.fit(x_train, y_train, epochs=15, batch_size=10,
validation_data=(x_train, y_train),
verbose=2)
self.assertGreater(history.history['val_acc'][-1], 0.7)
_, val_acc = model.evaluate(x_train, y_train)
self.assertAlmostEqual(history.history['val_acc'][-1], val_acc)
predictions = model.predict(x_train)
self.assertEqual(predictions.shape, (x_train.shape[0], 2))
def test_timeseries_classification_sequential_tf_rnn(self):
np.random.seed(1337)
(x_train, y_train), _ = testing_utils.get_test_data(
train_samples=100,
test_samples=0,
input_shape=(4, 10),
num_classes=2)
y_train = keras.utils.to_categorical(y_train)
model = keras.models.Sequential()
model.add(keras.layers.RNN(rnn_cell.LSTMCell(5), return_sequences=True,
input_shape=x_train.shape[1:]))
model.add(keras.layers.RNN(rnn_cell.GRUCell(y_train.shape[-1],
activation='softmax',
dtype=dtypes.float32)))
model.compile(loss='categorical_crossentropy',
optimizer=keras.optimizer_v2.adam.Adam(0.005),
metrics=['accuracy'],
run_eagerly=testing_utils.should_run_eagerly())
history = model.fit(x_train, y_train, epochs=15, batch_size=10,
validation_data=(x_train, y_train),
verbose=2)
self.assertGreater(history.history['val_acc'][-1], 0.7)
_, val_acc = model.evaluate(x_train, y_train)
self.assertAlmostEqual(history.history['val_acc'][-1], val_acc)
predictions = model.predict(x_train)
self.assertEqual(predictions.shape, (x_train.shape[0], 2))
@keras_parameterized.run_with_all_model_types
@keras_parameterized.run_all_keras_modes
class ImageClassificationIntegrationTest(keras_parameterized.TestCase):
def test_image_classification(self):
np.random.seed(1337)
(x_train, y_train), _ = testing_utils.get_test_data(
train_samples=100,
test_samples=0,
input_shape=(10, 10, 3),
num_classes=2)
y_train = keras.utils.to_categorical(y_train)
layers = [
keras.layers.Conv2D(4, 3, padding='same', activation='relu'),
keras.layers.Conv2D(8, 3, padding='same'),
keras.layers.BatchNormalization(),
keras.layers.Conv2D(8, 3, padding='same'),
keras.layers.Flatten(),
keras.layers.Dense(y_train.shape[-1], activation='softmax')
]
model = testing_utils.get_model_from_layers(
layers, input_shape=x_train.shape[1:])
model.compile(loss='categorical_crossentropy',
optimizer=keras.optimizer_v2.adam.Adam(0.005),
metrics=['accuracy'],
run_eagerly=testing_utils.should_run_eagerly())
history = model.fit(x_train, y_train, epochs=10, batch_size=10,
validation_data=(x_train, y_train),
verbose=2)
self.assertGreater(history.history['val_acc'][-1], 0.7)
_, val_acc = model.evaluate(x_train, y_train)
self.assertAlmostEqual(history.history['val_acc'][-1], val_acc)
predictions = model.predict(x_train)
self.assertEqual(predictions.shape, (x_train.shape[0], 2))
if __name__ == '__main__':
test.main()
| 42.326733
| 80
| 0.665146
|
32a9fe7827bd8b2600e34ec80f2ecda3c3239d45
| 3,008
|
py
|
Python
|
universal_landmark_detection/model/datasets/hand.py
|
MIRACLE-Center/YOLO_Universal_Anatomical_Landmark_Detection
|
23ec0b921e6c15d040f36650fd862059745edc33
|
[
"MIT"
] | 9
|
2021-12-17T06:43:58.000Z
|
2022-03-23T13:42:05.000Z
|
universal_landmark_detection/model/datasets/hand.py
|
MIRACLE-Center/YOLO_Universal_Anatomical_Landmark_Detection
|
23ec0b921e6c15d040f36650fd862059745edc33
|
[
"MIT"
] | 3
|
2022-01-01T08:41:29.000Z
|
2022-03-29T18:23:40.000Z
|
universal_landmark_detection/model/datasets/hand.py
|
MIRACLE-Center/YOLO_Universal_Anatomical_Landmark_Detection
|
23ec0b921e6c15d040f36650fd862059745edc33
|
[
"MIT"
] | 3
|
2022-01-04T04:21:43.000Z
|
2022-02-08T08:59:16.000Z
|
import os
from PIL import Image
import numpy as np
import pandas as pd
import torch
import torch.utils.data as data
from ..utils import gaussianHeatmap, transformer
class Hand(data.Dataset):
def __init__(self, prefix, phase, transform_params=dict(), sigma=10, num_landmark=19, size=[1000, 1400],use_background_channel=False):
self.transform = transformer(transform_params)
self.size = tuple(size)
self.num_landmark = num_landmark
self.pth_Image = os.path.join(prefix, 'jpg')
self.use_background_channel = use_background_channel
self.labels = pd.read_csv(os.path.join(
prefix, 'all.csv'), header=None, index_col=0)
# file index
index_set = set(self.labels.index)
files = [i[:-4] for i in sorted(os.listdir(self.pth_Image))]
files = [i for i in files if int(i) in index_set]
n = len(files)
train_num = 550 # round(n*0.7)
val_num = 59 # round(n*0.1)
test_num = n - train_num - val_num
if phase == 'train':
self.indexes = files[:train_num]
elif phase == 'validate':
self.indexes = files[train_num:-test_num]
elif phase == 'test':
self.indexes = files[-test_num:]
else:
raise Exception("Unknown phase: {phase}".fomrat(phase=phase))
self.genHeatmap = gaussianHeatmap(sigma, dim=len(size))
def __getitem__(self, index):
name = self.indexes[index]
ret = {'name': name}
img, origin_size = self.readImage(
os.path.join(self.pth_Image, name+'.jpg'))
points = self.readLandmark(name, origin_size)
li = [self.genHeatmap(point, self.size) for point in points]
if self.use_background_channel:
sm = sum(li)
sm[sm>1]=1
li.append(1-sm)
gt = np.array(li)
img, gt = self.transform(img, gt)
ret['input'] = torch.FloatTensor(img)
ret['gt'] = torch.FloatTensor(gt)
return ret
def __len__(self):
return len(self.indexes)
def readLandmark(self, name, origin_size):
li = list(self.labels.loc[int(name), :])
r1, r2 = [i/j for i, j in zip(self.size, origin_size)]
points = [tuple([round(li[i]*r1), round(li[i+1]*r2)])
for i in range(0, len(li), 2)]
return points
def readImage(self, path):
'''Read image from path and return a numpy.ndarray in shape of cxwxh
'''
img = Image.open(path)
origin_size = img.size
# resize, width x height, channel=1
img = img.resize(self.size)
arr = np.array(img)
# channel x width x height: 1 x width x height
arr = np.expand_dims(np.transpose(arr, (1, 0)), 0).astype(np.float)
# conveting to float is important, otherwise big bug occurs
for i in range(arr.shape[0]):
arr[i] = (arr[i]-arr[i].mean())/(arr[i].std()+1e-20)
return arr, origin_size
| 34.181818
| 138
| 0.591423
|
394b73f1c5425012fe96e683ac6789140f861614
| 6,222
|
py
|
Python
|
tests/test_users.py
|
lfaraone/grouper
|
7df5eda8003a0b4a9ba7f0dcb044ae1e4710b171
|
[
"Apache-2.0"
] | null | null | null |
tests/test_users.py
|
lfaraone/grouper
|
7df5eda8003a0b4a9ba7f0dcb044ae1e4710b171
|
[
"Apache-2.0"
] | 1
|
2016-02-18T18:55:29.000Z
|
2016-02-18T18:55:29.000Z
|
tests/test_users.py
|
lfaraone/grouper
|
7df5eda8003a0b4a9ba7f0dcb044ae1e4710b171
|
[
"Apache-2.0"
] | null | null | null |
from urllib import urlencode
import pytest
from tornado.httpclient import HTTPError
from fixtures import fe_app as app
from fixtures import standard_graph, graph, users, groups, session, permissions # noqa
from grouper.constants import USER_ADMIN
from grouper.models.user_token import UserToken
from grouper.user_metadata import set_user_metadata, get_user_metadata
from grouper.user_token import add_new_user_token, disable_user_token
from url_util import url
from util import get_groups, grant_permission
from grouper.models.permission import Permission
def test_basic_metadata(standard_graph, session, users, groups, permissions): # noqa
""" Test basic metadata functionality. """
graph = standard_graph # noqa
user_id = users["zorkian@a.co"].id
assert len(get_user_metadata(session, users["zorkian@a.co"].id)) == 0, "No metadata yet"
# Test setting "foo" to 1 works, and we get "1" back (metadata is defined as strings)
set_user_metadata(session, user_id, "foo", 1)
md = get_user_metadata(session, user_id)
assert len(md) == 1, "One metadata item"
assert [d.data_value for d in md if d.data_key == "foo"] == ["1"], "foo is 1"
set_user_metadata(session, user_id, "bar", "test string")
md = get_user_metadata(session, user_id)
assert len(md) == 2, "Two metadata items"
assert [d.data_value for d in md if d.data_key == "bar"] == ["test string"], \
"bar is test string"
set_user_metadata(session, user_id, "foo", "test2")
md = get_user_metadata(session, user_id)
assert len(md) == 2, "Two metadata items"
assert [d.data_value for d in md if d.data_key == "foo"] == ["test2"], "foo is test2"
set_user_metadata(session, user_id, "foo", None)
md = get_user_metadata(session, user_id)
assert len(md) == 1, "One metadata item"
assert [d.data_value for d in md if d.data_key == "foo"] == [], "foo is not found"
set_user_metadata(session, user_id, "baz", None)
md = get_user_metadata(session, user_id)
assert len(md) == 1, "One metadata item"
def test_usertokens(standard_graph, session, users, groups, permissions): # noqa
user = users["zorkian@a.co"]
assert len(user.tokens) == 0
tok, secret = add_new_user_token(session, UserToken(user=user, name="Foo"))
assert len(user.tokens) == 1
assert tok.check_secret(secret)
assert tok.check_secret("invalid") == False
assert tok.enabled == True
disable_user_token(session, tok)
assert tok.enabled == False
assert user.tokens[0].enabled == False
assert UserToken.get(session, name="Foo", user=user).enabled == False
assert tok.check_secret(secret) == False
@pytest.mark.gen_test
def test_user_tok_acls(session, graph, users, user_admin_perm_to_auditors, http_client, base_url):
role_user = "role@a.co"
admin = "zorkian@a.co"
pleb = "gary@a.co"
# admin creating token for role user
fe_url = url(base_url, "/users/{}/tokens/add".format(role_user))
resp = yield http_client.fetch(fe_url, method="POST",
headers={"X-Grouper-User": admin}, body=urlencode({"name": "foo"}))
assert resp.code == 200
with pytest.raises(HTTPError):
# non-admin creating token for role user
resp = yield http_client.fetch(fe_url, method="POST",
headers={"X-Grouper-User": pleb}, body=urlencode({"name": "foo2"}))
fe_url = url(base_url, "/users/{}/tokens/add".format(pleb))
with pytest.raises(HTTPError):
# admin creating token for normal (non-role) user
resp = yield http_client.fetch(fe_url, method="POST",
headers={"X-Grouper-User": admin}, body=urlencode({"name": "foo3"}))
@pytest.fixture
def user_admin_perm_to_auditors(session, groups):
"""Adds a USER_ADMIN permission to the "auditors" group"""
user_admin_perm, is_new = Permission.get_or_create(session, name=USER_ADMIN,
description="grouper.admin.users permission")
session.commit()
grant_permission(groups["auditors"], user_admin_perm)
@pytest.mark.gen_test
def test_graph_disable(session, graph, users, groups, user_admin_perm_to_auditors,
http_client, base_url):
graph.update_from_db(session)
old_users = graph.users
assert sorted(old_users) == sorted(users.keys())
# disable a user
username = u"oliver@a.co"
fe_url = url(base_url, "/users/{}/disable".format(username))
resp = yield http_client.fetch(fe_url, method="POST",
headers={"X-Grouper-User": "zorkian@a.co"}, body=urlencode({}))
assert resp.code == 200
graph.update_from_db(session)
assert len(graph.users) == (len(old_users) - 1), 'disabled user removed from graph'
assert username not in graph.users
@pytest.mark.gen_test
def test_user_disable(session, graph, users, user_admin_perm_to_auditors, http_client, base_url):
username = u"oliver@a.co"
old_groups = sorted(get_groups(graph, username))
# disable user
fe_url = url(base_url, "/users/{}/disable".format(username))
resp = yield http_client.fetch(fe_url, method="POST",
headers={"X-Grouper-User": "zorkian@a.co"}, body=urlencode({}))
assert resp.code == 200
# enable user, PRESERVE groups
fe_url = url(base_url, "/users/{}/enable".format(username))
resp = yield http_client.fetch(fe_url, method="POST",
headers={"X-Grouper-User": "zorkian@a.co"},
body=urlencode({"preserve_membership": "true"}))
assert resp.code == 200
graph.update_from_db(session)
assert old_groups == sorted(get_groups(graph, username)), 'nothing should be removed'
# disable and enable, PURGE groups
fe_url = url(base_url, "/users/{}/disable".format(username))
resp = yield http_client.fetch(fe_url, method="POST",
headers={"X-Grouper-User": "zorkian@a.co"}, body=urlencode({}))
assert resp.code == 200
fe_url = url(base_url, "/users/{}/enable".format(username))
resp = yield http_client.fetch(fe_url, method="POST",
headers={"X-Grouper-User": "zorkian@a.co"}, body=urlencode({}))
assert resp.code == 200
graph.update_from_db(session)
assert len(get_groups(graph, username)) == 0, 'all group membership should be removed'
| 39.630573
| 98
| 0.687239
|
cd3465a60f6867e2c73f83b2dc2f84913000174a
| 4,800
|
py
|
Python
|
satori/tests/test_utils.py
|
mgeisler/satori
|
dea382bae1cd043189589c0f7d4c20b4b6725ab5
|
[
"Apache-2.0"
] | 1
|
2015-01-18T19:56:28.000Z
|
2015-01-18T19:56:28.000Z
|
satori/tests/test_utils.py
|
samstav/satori
|
239fa1e3c7aac78599145c670576f0ac76a41a89
|
[
"Apache-2.0"
] | null | null | null |
satori/tests/test_utils.py
|
samstav/satori
|
239fa1e3c7aac78599145c670576f0ac76a41a89
|
[
"Apache-2.0"
] | null | null | null |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Tests for utils module."""
import datetime
import time
import unittest
import mock
from satori import utils
class SomeTZ(datetime.tzinfo):
"""A random timezone."""
def utcoffset(self, dt):
return datetime.timedelta(minutes=45)
def tzname(self, dt):
return "STZ"
def dst(self, dt):
return datetime.timedelta(0)
class TestTimeUtils(unittest.TestCase):
"""Test time formatting functions."""
def test_get_formatted_time_string(self):
some_time = time.gmtime(0)
with mock.patch.object(utils.time, 'gmtime') as mock_gmt:
mock_gmt.return_value = some_time
result = utils.get_time_string()
self.assertEqual(result, "1970-01-01 00:00:00 +0000")
def test_get_formatted_time_string_time_struct(self):
result = utils.get_time_string(time_obj=time.gmtime(0))
self.assertEqual(result, "1970-01-01 00:00:00 +0000")
def test_get_formatted_time_string_datetime(self):
result = utils.get_time_string(
time_obj=datetime.datetime(1970, 2, 1, 1, 2, 3, 0))
self.assertEqual(result, "1970-02-01 01:02:03 +0000")
def test_get_formatted_time_string_datetime_tz(self):
result = utils.get_time_string(
time_obj=datetime.datetime(1970, 2, 1, 1, 2, 3, 0, SomeTZ()))
self.assertEqual(result, "1970-02-01 01:47:03 +0000")
def test_parse_time_string(self):
result = utils.parse_time_string("1970-02-01 01:02:03 +0000")
self.assertEqual(result, datetime.datetime(1970, 2, 1, 1, 2, 3, 0))
def test_parse_time_string_with_tz(self):
result = utils.parse_time_string("1970-02-01 01:02:03 +1000")
self.assertEqual(result, datetime.datetime(1970, 2, 1, 11, 2, 3, 0))
class TestGetSource(unittest.TestCase):
def setUp(self):
self.function_signature = "def get_my_source_oneline_docstring(self):"
self.function_oneline_docstring = '"""A beautiful docstring."""'
self.function_multiline_docstring = ('"""A beautiful docstring.\n\n'
'Is a terrible thing to '
'waste.\n"""')
self.function_body = ['the_problem = "not the problem"',
'return the_problem']
def get_my_source_oneline_docstring(self):
"""A beautiful docstring."""
the_problem = "not the problem"
return the_problem
def get_my_source_multiline_docstring(self):
"""A beautiful docstring.
Is a terrible thing to waste.
"""
the_problem = "not the problem"
return the_problem
def test_get_source(self):
nab = utils.get_source_body(self.get_my_source_oneline_docstring)
self.assertEqual("\n".join(self.function_body), nab)
def test_get_source_with_docstring(self):
nab = utils.get_source_body(self.get_my_source_oneline_docstring,
with_docstring=True)
copy = self.function_oneline_docstring + "\n" + "\n".join(
self.function_body)
self.assertEqual(copy, nab)
def test_get_source_with_multiline_docstring(self):
nab = utils.get_source_body(self.get_my_source_multiline_docstring,
with_docstring=True)
copy = (self.function_multiline_docstring + "\n" + "\n".join(
self.function_body))
self.assertEqual(copy, nab)
def test_get_definition(self):
nab = utils.get_source_definition(
self.get_my_source_oneline_docstring)
copy = "%s\n \n %s" % (self.function_signature,
"\n ".join(self.function_body))
self.assertEqual(copy, nab)
def test_get_definition_with_docstring(self):
nab = utils.get_source_definition(
self.get_my_source_oneline_docstring, with_docstring=True)
copy = "%s\n %s\n %s" % (self.function_signature,
self.function_oneline_docstring,
"\n ".join(self.function_body))
self.assertEqual(copy, nab)
if __name__ == '__main__':
unittest.main()
| 36.363636
| 78
| 0.634583
|
be08c4d857c93ce32a9059bd93ff1c2e44b33cb2
| 4,664
|
py
|
Python
|
arknights_mower/ocr/ocrspace.py
|
yuanyan3060/arknights-mower
|
599b96e02590a435dc50bdef450b45c851654c4f
|
[
"MIT"
] | 1
|
2021-09-11T04:11:15.000Z
|
2021-09-11T04:11:15.000Z
|
arknights_mower/ocr/ocrspace.py
|
yuanyan3060/arknights-mower
|
599b96e02590a435dc50bdef450b45c851654c4f
|
[
"MIT"
] | null | null | null |
arknights_mower/ocr/ocrspace.py
|
yuanyan3060/arknights-mower
|
599b96e02590a435dc50bdef450b45c851654c4f
|
[
"MIT"
] | null | null | null |
import traceback
import cv2
import numpy
import base64
import requests
from .utils import fix
from ..utils.log import logger
from ..utils.recognize import RecognizeError
class Language:
Arabic = 'ara'
Bulgarian = 'bul'
Chinese_Simplified = 'chs'
Chinese_Traditional = 'cht'
Croatian = 'hrv'
Danish = 'dan'
Dutch = 'dut'
English = 'eng'
Finnish = 'fin'
French = 'fre'
German = 'ger'
Greek = 'gre'
Hungarian = 'hun'
Korean = 'kor'
Italian = 'ita'
Japanese = 'jpn'
Norwegian = 'nor'
Polish = 'pol'
Portuguese = 'por'
Russian = 'rus'
Slovenian = 'slv'
Spanish = 'spa'
Swedish = 'swe'
Turkish = 'tur'
class API:
def __init__(
self,
endpoint='https://api.ocr.space/parse/image',
api_key='helloworld',
language=Language.Chinese_Simplified,
**kwargs,
):
"""
:param endpoint: API endpoint to contact
:param api_key: API key string
:param language: document language
:param **kwargs: other settings to API
"""
self.timeout = (5, 10)
self.endpoint = endpoint
self.payload = {
'isOverlayRequired': True,
'apikey': api_key,
'language': language,
**kwargs
}
def _parse(self, raw):
logger.debug(raw)
if type(raw) == str:
raise RecognizeError(raw)
if raw['IsErroredOnProcessing']:
raise RecognizeError(raw['ErrorMessage'][0])
if raw['ParsedResults'][0].get('TextOverlay') is None:
raise RecognizeError('No Result')
# ret = []
# for x in raw['ParsedResults'][0]['TextOverlay']['Lines']:
# left, right, up, down = 1e30, 0, 1e30, 0
# for w in x['Words']:
# left = min(left, w['Left'])
# right = max(right, w['Left'] + w['Width'])
# up = min(up, w['Top'])
# down = max(down, w['Top'] + w['Height'])
# ret.append([x['LineText'], [(left + right) / 2, (up + down) / 2]])
# return ret
ret = [x['LineText'] for x in raw['ParsedResults'][0]['TextOverlay']['Lines']]
return ret
def ocr_file(self, fp):
"""
Process image from a local path.
:param fp: A path or pointer to your file
:return: Result in JSON format
"""
with (open(fp, 'rb') if type(fp) == str else fp) as f:
r = requests.post(
self.endpoint,
files={'filename': f},
data=self.payload,
timeout=self.timeout,
)
return self._parse(r.json())
def ocr_url(self, url):
"""
Process an image at a given URL.
:param url: Image url
:return: Result in JSON format.
"""
data = self.payload
data['url'] = url
r = requests.post(
self.endpoint,
data=data,
timeout=self.timeout,
)
return self._parse(r.json())
def ocr_base64(self, base64image):
"""
Process an image given as base64.
:param base64image: Image represented as Base64
:return: Result in JSON format.
"""
data = self.payload
data['base64Image'] = base64image
r = requests.post(
self.endpoint,
data=data,
timeout=self.timeout,
)
return self._parse(r.json())
def ocr_image(self, image: numpy.ndarray):
data = self.payload
data['base64Image'] = 'data:image/jpg;base64,' + \
base64.b64encode(cv2.imencode('.jpg', image)[1].tobytes()).decode()
retry_times = 1
while True:
try:
r = requests.post(
self.endpoint,
data=data,
timeout=self.timeout,
)
break
except Exception as e:
logger.warning(e)
logger.debug(traceback.format_exc())
retry_times -= 1
if retry_times > 0:
logger.warning('重试中……')
else:
logger.warning('无网络或网络故障,无法连接到 OCR Space')
return []
try:
return self._parse(r.json())
except Exception as e:
logger.debug(e)
return []
def predict(self, image, scope):
ret = self.ocr_image(image[scope[0][1]:scope[2][1], scope[0][0]:scope[2][0]])
if len(ret) == 0:
return None
return fix(ret[0])
| 28.790123
| 86
| 0.504503
|
9c43e57c69a8dde6e1723760c856ba762bdba52f
| 138
|
py
|
Python
|
class2/e1c_test_my_func.py
|
ktbyers/pynet_wantonik
|
601bce26142b6741202c2bdafb9e0d0cec1b3c78
|
[
"Apache-2.0"
] | 2
|
2017-05-11T12:05:15.000Z
|
2021-07-15T18:13:19.000Z
|
class2/e1c_test_my_func.py
|
ktbyers/pynet_wantonik
|
601bce26142b6741202c2bdafb9e0d0cec1b3c78
|
[
"Apache-2.0"
] | null | null | null |
class2/e1c_test_my_func.py
|
ktbyers/pynet_wantonik
|
601bce26142b6741202c2bdafb9e0d0cec1b3c78
|
[
"Apache-2.0"
] | 1
|
2017-05-11T12:05:18.000Z
|
2017-05-11T12:05:18.000Z
|
#!/usr/bin/env python
## This script imports my_func function from e1c_my_func.py module
import e1c_my_func
print e1c_my_func.hello_func
| 23
| 66
| 0.818841
|
1c1b133b5ebe6d5e32e17d6537d02dfc87301d52
| 111,932
|
py
|
Python
|
src/sentry/south_migrations/0308_auto__add_versiondsymfile__add_unique_versiondsymfile_dsym_file_versio.py
|
uandco/sentry
|
5b8d45cb71c6617dac8e64265848623fbfce9c99
|
[
"BSD-3-Clause"
] | 2
|
2019-03-04T12:45:54.000Z
|
2019-03-04T12:45:55.000Z
|
src/sentry/south_migrations/0308_auto__add_versiondsymfile__add_unique_versiondsymfile_dsym_file_versio.py
|
uandco/sentry
|
5b8d45cb71c6617dac8e64265848623fbfce9c99
|
[
"BSD-3-Clause"
] | 196
|
2019-06-10T08:34:10.000Z
|
2022-02-22T01:26:13.000Z
|
src/sentry/south_migrations/0308_auto__add_versiondsymfile__add_unique_versiondsymfile_dsym_file_versio.py
|
uandco/sentry
|
5b8d45cb71c6617dac8e64265848623fbfce9c99
|
[
"BSD-3-Clause"
] | 1
|
2017-02-09T06:36:57.000Z
|
2017-02-09T06:36:57.000Z
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'VersionDSymFile'
db.create_table(
'sentry_versiondsymfile', (
(
'id', self.gf('sentry.db.models.fields.bounded.BoundedBigAutoField')(
primary_key=True
)
), (
'dsym_file', self.gf('sentry.db.models.fields.foreignkey.FlexibleForeignKey')(
to=orm['sentry.ProjectDSymFile'], null=True
)
), (
'dsym_app', self.gf('sentry.db.models.fields.foreignkey.FlexibleForeignKey')(
to=orm['sentry.DSymApp']
)
), ('version', self.gf('django.db.models.fields.CharField')(max_length=32)),
('build', self.gf('django.db.models.fields.CharField')(max_length=32, null=True)), (
'date_added',
self.gf('django.db.models.fields.DateTimeField')()
),
)
)
db.send_create_signal('sentry', ['VersionDSymFile'])
# Adding unique constraint on 'VersionDSymFile', fields ['dsym_file', 'version', 'build']
db.create_unique('sentry_versiondsymfile', ['dsym_file_id', 'version', 'build'])
# Adding model 'DSymApp'
db.create_table(
'sentry_dsymapp', (
(
'id', self.gf('sentry.db.models.fields.bounded.BoundedBigAutoField')(
primary_key=True
)
), (
'project', self.gf('sentry.db.models.fields.foreignkey.FlexibleForeignKey')(
to=orm['sentry.Project']
)
), ('app_id', self.gf('django.db.models.fields.CharField')(max_length=64)),
('sync_id', self.gf('django.db.models.fields.CharField')(max_length=64, null=True)),
('data', self.gf('sentry.db.models.fields.jsonfield.JSONField')(default={})), (
'platform',
self.gf('sentry.db.models.fields.bounded.BoundedPositiveIntegerField')(
default=0
)
), (
'last_synced',
self.gf('django.db.models.fields.DateTimeField')()
), (
'date_added',
self.gf('django.db.models.fields.DateTimeField')()
),
)
)
db.send_create_signal('sentry', ['DSymApp'])
# Adding unique constraint on 'DSymApp', fields ['project', 'platform', 'app_id']
db.create_unique('sentry_dsymapp', ['project_id', 'platform', 'app_id'])
def backwards(self, orm):
# Removing unique constraint on 'DSymApp', fields ['project', 'platform', 'app_id']
db.delete_unique('sentry_dsymapp', ['project_id', 'platform', 'app_id'])
# Removing unique constraint on 'VersionDSymFile', fields ['dsym_file', 'version', 'build']
db.delete_unique('sentry_versiondsymfile', ['dsym_file_id', 'version', 'build'])
# Deleting model 'VersionDSymFile'
db.delete_table('sentry_versiondsymfile')
# Deleting model 'DSymApp'
db.delete_table('sentry_dsymapp')
models = {
'sentry.activity': {
'Meta': {
'object_name': 'Activity'
},
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {
'null': 'True'
}),
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'null': 'True'
}
)
},
'sentry.apiapplication': {
'Meta': {
'object_name': 'ApiApplication'
},
'allowed_origins':
('django.db.models.fields.TextField', [], {
'null': 'True',
'blank': 'True'
}),
'client_id': (
'django.db.models.fields.CharField', [], {
'default': "'6949fb4996184c5abf84d6e2206deb2028847544b25745dcb59f9788f860cd4b'",
'unique': 'True',
'max_length': '64'
}
),
'client_secret': (
'sentry.db.models.fields.encrypted.EncryptedTextField', [], {
'default': "'120099c387964b1c826925621112bec1d8dbb441c0f24233b2487fa1350c03d7'"
}
),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'homepage_url':
('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': (
'django.db.models.fields.CharField', [], {
'default': "'Transitive Clemente'",
'max_length': '64',
'blank': 'True'
}
),
'owner': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
),
'privacy_url':
('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
}),
'redirect_uris': ('django.db.models.fields.TextField', [], {}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'terms_url':
('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
})
},
'sentry.apiauthorization': {
'Meta': {
'unique_together': "(('user', 'application'),)",
'object_name': 'ApiAuthorization'
},
'application': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiApplication']",
'null': 'True'
}
),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'scope_list': (
'sentry.db.models.fields.array.ArrayField', [], {
'of': ('django.db.models.fields.TextField', [], {})
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.apigrant': {
'Meta': {
'object_name': 'ApiGrant'
},
'application': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiApplication']"
}
),
'code': (
'django.db.models.fields.CharField', [], {
'default': "'c52f5a5dc7dd41448dc017bd251144dc'",
'max_length': '64',
'db_index': 'True'
}
),
'expires_at': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime(2017, 3, 23, 0, 0)',
'db_index': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'redirect_uri': ('django.db.models.fields.CharField', [], {
'max_length': '255'
}),
'scope_list': (
'sentry.db.models.fields.array.ArrayField', [], {
'of': ('django.db.models.fields.TextField', [], {})
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.apikey': {
'Meta': {
'object_name': 'ApiKey'
},
'allowed_origins':
('django.db.models.fields.TextField', [], {
'null': 'True',
'blank': 'True'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '32'
}),
'label': (
'django.db.models.fields.CharField', [], {
'default': "'Default'",
'max_length': '64',
'blank': 'True'
}
),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'key_set'",
'to': "orm['sentry.Organization']"
}
),
'scope_list': (
'sentry.db.models.fields.array.ArrayField', [], {
'of': ('django.db.models.fields.TextField', [], {})
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
)
},
'sentry.apitoken': {
'Meta': {
'object_name': 'ApiToken'
},
'application': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiApplication']",
'null': 'True'
}
),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'expires_at': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime(2017, 4, 22, 0, 0)',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'refresh_token': (
'django.db.models.fields.CharField', [], {
'default': "'4f556f8dc184403fa0cd07e85a1a388204ca73f817294a0a9652081c86929bca'",
'max_length': '64',
'unique': 'True',
'null': 'True'
}
),
'scope_list': (
'sentry.db.models.fields.array.ArrayField', [], {
'of': ('django.db.models.fields.TextField', [], {})
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'token': (
'django.db.models.fields.CharField', [], {
'default': "'da4ff55914c148c1b652ef734ac727adc0fc7dc596a2445199009467c7d51337'",
'unique': 'True',
'max_length': '64'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.auditlogentry': {
'Meta': {
'object_name': 'AuditLogEntry'
},
'actor': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'blank': 'True',
'related_name': "'audit_actors'",
'null': 'True',
'to': "orm['sentry.User']"
}
),
'actor_key': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiKey']",
'null': 'True',
'blank': 'True'
}
),
'actor_label': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True',
'blank': 'True'
}
),
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}),
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ip_address': (
'django.db.models.fields.GenericIPAddressField', [], {
'max_length': '39',
'null': 'True'
}
),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'target_object':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'target_user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'blank': 'True',
'related_name': "'audit_targets'",
'null': 'True',
'to': "orm['sentry.User']"
}
)
},
'sentry.authenticator': {
'Meta': {
'unique_together': "(('user', 'type'),)",
'object_name': 'Authenticator',
'db_table': "'auth_authenticator'"
},
'config': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {}),
'created_at':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {
'primary_key': 'True'
}),
'last_used_at': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.authidentity': {
'Meta': {
'unique_together': "(('auth_provider', 'ident'), ('auth_provider', 'user'))",
'object_name': 'AuthIdentity'
},
'auth_provider': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.AuthProvider']"
}
),
'data': ('sentry.db.models.fields.encrypted.EncryptedJsonField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'last_synced':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'last_verified':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.authprovider': {
'Meta': {
'object_name': 'AuthProvider'
},
'config':
('sentry.db.models.fields.encrypted.EncryptedJsonField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'default_global_access':
('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'default_role':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '50'
}),
'default_teams': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.Team']",
'symmetrical': 'False',
'blank': 'True'
}
),
'flags': ('django.db.models.fields.BigIntegerField', [], {
'default': '0'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_sync': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']",
'unique': 'True'
}
),
'provider': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'sync_time':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
})
},
'sentry.broadcast': {
'Meta': {
'object_name': 'Broadcast'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'date_expires': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime(2017, 3, 30, 0, 0)',
'null': 'True',
'blank': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_active':
('django.db.models.fields.BooleanField', [], {
'default': 'True',
'db_index': 'True'
}),
'link': (
'django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True',
'blank': 'True'
}
),
'message': ('django.db.models.fields.CharField', [], {
'max_length': '256'
}),
'title': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'upstream_id': (
'django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True',
'blank': 'True'
}
)
},
'sentry.broadcastseen': {
'Meta': {
'unique_together': "(('broadcast', 'user'),)",
'object_name': 'BroadcastSeen'
},
'broadcast': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Broadcast']"
}
),
'date_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.commit': {
'Meta': {
'unique_together': "(('repository_id', 'key'),)",
'object_name': 'Commit',
'index_together': "(('repository_id', 'date_added'),)"
},
'author': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.CommitAuthor']",
'null': 'True'
}
),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'message': ('django.db.models.fields.TextField', [], {
'null': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'repository_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.commitauthor': {
'Meta': {
'unique_together': "(('organization_id', 'email'),)",
'object_name': 'CommitAuthor'
},
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name':
('django.db.models.fields.CharField', [], {
'max_length': '128',
'null': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'sentry.commitfilechange': {
'Meta': {
'unique_together': "(('commit', 'filename'),)",
'object_name': 'CommitFileChange'
},
'commit': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Commit']"
}
),
'filename': ('django.db.models.fields.CharField', [], {
'max_length': '255'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'type': ('django.db.models.fields.CharField', [], {
'max_length': '1'
})
},
'sentry.counter': {
'Meta': {
'object_name': 'Counter',
'db_table': "'sentry_projectcounter'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'unique': 'True'
}
),
'value': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.deploy': {
'Meta': {
'object_name': 'Deploy'
},
'date_finished':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'date_started':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'blank': 'True'
}),
'environment_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True',
'blank': 'True'
}
),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
),
'url': (
'django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True',
'blank': 'True'
}
)
},
'sentry.dsymapp': {
'Meta': {
'unique_together': "(('project', 'platform', 'app_id'),)",
'object_name': 'DSymApp'
},
'app_id': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'data': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_synced':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'platform':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'sync_id':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
})
},
'sentry.dsymbundle': {
'Meta': {
'object_name': 'DSymBundle'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymObject']"
}
),
'sdk': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymSDK']"
}
)
},
'sentry.dsymobject': {
'Meta': {
'object_name': 'DSymObject'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_path': ('django.db.models.fields.TextField', [], {
'db_index': 'True'
}),
'uuid':
('django.db.models.fields.CharField', [], {
'max_length': '36',
'db_index': 'True'
}),
'vmaddr':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'vmsize':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
})
},
'sentry.dsymsdk': {
'Meta': {
'object_name':
'DSymSDK',
'index_together':
"[('version_major', 'version_minor', 'version_patchlevel', 'version_build')]"
},
'dsym_type':
('django.db.models.fields.CharField', [], {
'max_length': '20',
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'sdk_name': ('django.db.models.fields.CharField', [], {
'max_length': '20'
}),
'version_build': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'version_major': ('django.db.models.fields.IntegerField', [], {}),
'version_minor': ('django.db.models.fields.IntegerField', [], {}),
'version_patchlevel': ('django.db.models.fields.IntegerField', [], {})
},
'sentry.dsymsymbol': {
'Meta': {
'unique_together': "[('object', 'address')]",
'object_name': 'DSymSymbol'
},
'address':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymObject']"
}
),
'symbol': ('django.db.models.fields.TextField', [], {})
},
'sentry.environment': {
'Meta': {
'unique_together': "(('project_id', 'name'),)",
'object_name': 'Environment'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'organization_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'project_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'projects': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.Project']",
'through': "orm['sentry.EnvironmentProject']",
'symmetrical': 'False'
}
)
},
'sentry.environmentproject': {
'Meta': {
'unique_together': "(('project', 'environment'),)",
'object_name': 'EnvironmentProject'
},
'environment': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Environment']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
)
},
'sentry.event': {
'Meta': {
'unique_together': "(('project_id', 'event_id'),)",
'object_name': 'Event',
'db_table': "'sentry_message'",
'index_together': "(('group_id', 'datetime'),)"
},
'data':
('sentry.db.models.fields.node.NodeField', [], {
'null': 'True',
'blank': 'True'
}),
'datetime': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'event_id': (
'django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True',
'db_column': "'message_id'"
}
),
'group_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'message': ('django.db.models.fields.TextField', [], {}),
'platform':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'time_spent':
('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'null': 'True'
})
},
'sentry.eventmapping': {
'Meta': {
'unique_together': "(('project_id', 'event_id'),)",
'object_name': 'EventMapping'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event_id': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'group_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.eventprocessingissue': {
'Meta': {
'unique_together': "(('raw_event', 'processing_issue'),)",
'object_name': 'EventProcessingIssue'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'processing_issue': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ProcessingIssue']"
}
),
'raw_event': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.RawEvent']"
}
)
},
'sentry.eventtag': {
'Meta': {
'unique_together':
"(('event_id', 'key_id', 'value_id'),)",
'object_name':
'EventTag',
'index_together':
"(('project_id', 'key_id', 'value_id'), ('group_id', 'key_id', 'value_id'))"
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'value_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.eventuser': {
'Meta': {
'unique_together':
"(('project', 'ident'), ('project', 'hash'))",
'object_name':
'EventUser',
'index_together':
"(('project', 'email'), ('project', 'username'), ('project', 'ip_address'))"
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'email':
('django.db.models.fields.EmailField', [], {
'max_length': '75',
'null': 'True'
}),
'hash': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident':
('django.db.models.fields.CharField', [], {
'max_length': '128',
'null': 'True'
}),
'ip_address': (
'django.db.models.fields.GenericIPAddressField', [], {
'max_length': '39',
'null': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'username':
('django.db.models.fields.CharField', [], {
'max_length': '128',
'null': 'True'
})
},
'sentry.file': {
'Meta': {
'object_name': 'File'
},
'blob': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'legacy_blob'",
'null': 'True',
'to': "orm['sentry.FileBlob']"
}
),
'blobs': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.FileBlob']",
'through': "orm['sentry.FileBlobIndex']",
'symmetrical': 'False'
}
),
'checksum':
('django.db.models.fields.CharField', [], {
'max_length': '40',
'null': 'True'
}),
'headers': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'path': ('django.db.models.fields.TextField', [], {
'null': 'True'
}),
'size':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'timestamp': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'type': ('django.db.models.fields.CharField', [], {
'max_length': '64'
})
},
'sentry.fileblob': {
'Meta': {
'object_name': 'FileBlob'
},
'checksum':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '40'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'path': ('django.db.models.fields.TextField', [], {
'null': 'True'
}),
'size':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'timestamp': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
)
},
'sentry.fileblobindex': {
'Meta': {
'unique_together': "(('file', 'blob', 'offset'),)",
'object_name': 'FileBlobIndex'
},
'blob': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.FileBlob']"
}
),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'offset': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.globaldsymfile': {
'Meta': {
'object_name': 'GlobalDSymFile'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_name': ('django.db.models.fields.TextField', [], {}),
'uuid':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '36'
})
},
'sentry.group': {
'Meta': {
'unique_together': "(('project', 'short_id'),)",
'object_name': 'Group',
'db_table': "'sentry_groupedmessage'",
'index_together': "(('project', 'first_release'),)"
},
'active_at':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'db_index': 'True'
}),
'culprit': (
'django.db.models.fields.CharField', [], {
'max_length': '200',
'null': 'True',
'db_column': "'view'",
'blank': 'True'
}
),
'data': (
'sentry.db.models.fields.gzippeddict.GzippedDictField', [], {
'null': 'True',
'blank': 'True'
}
),
'first_release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']",
'null': 'True',
'on_delete': 'models.PROTECT'
}
),
'first_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_public': (
'django.db.models.fields.NullBooleanField', [], {
'default': 'False',
'null': 'True',
'blank': 'True'
}
),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'level': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '40',
'db_index': 'True',
'blank': 'True'
}
),
'logger': (
'django.db.models.fields.CharField', [], {
'default': "''",
'max_length': '64',
'db_index': 'True',
'blank': 'True'
}
),
'message': ('django.db.models.fields.TextField', [], {}),
'num_comments': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'null': 'True'
}
),
'platform':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'resolved_at':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'db_index': 'True'
}),
'score': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'default': '0'
}),
'short_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'time_spent_count':
('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'default': '0'
}),
'time_spent_total':
('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'default': '0'
}),
'times_seen': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '1',
'db_index': 'True'
}
)
},
'sentry.groupassignee': {
'Meta': {
'object_name': 'GroupAssignee',
'db_table': "'sentry_groupasignee'"
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'assignee_set'",
'unique': 'True',
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'assignee_set'",
'to': "orm['sentry.Project']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'sentry_assignee_set'",
'to': "orm['sentry.User']"
}
)
},
'sentry.groupbookmark': {
'Meta': {
'unique_together': "(('project', 'user', 'group'),)",
'object_name': 'GroupBookmark'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'bookmark_set'",
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'bookmark_set'",
'to': "orm['sentry.Project']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'sentry_bookmark_set'",
'to': "orm['sentry.User']"
}
)
},
'sentry.groupcommitresolution': {
'Meta': {
'unique_together': "(('group_id', 'commit_id'),)",
'object_name': 'GroupCommitResolution'
},
'commit_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'datetime': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'group_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
})
},
'sentry.groupemailthread': {
'Meta': {
'unique_together': "(('email', 'group'), ('email', 'msgid'))",
'object_name': 'GroupEmailThread'
},
'date': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'groupemail_set'",
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'msgid': ('django.db.models.fields.CharField', [], {
'max_length': '100'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'groupemail_set'",
'to': "orm['sentry.Project']"
}
)
},
'sentry.grouphash': {
'Meta': {
'unique_together': "(('project', 'hash'),)",
'object_name': 'GroupHash'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'null': 'True'
}
),
'hash': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
)
},
'sentry.groupmeta': {
'Meta': {
'unique_together': "(('group', 'key'),)",
'object_name': 'GroupMeta'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'value': ('django.db.models.fields.TextField', [], {})
},
'sentry.groupredirect': {
'Meta': {
'object_name': 'GroupRedirect'
},
'group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'previous_group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'unique': 'True'
})
},
'sentry.grouprelease': {
'Meta': {
'unique_together': "(('group_id', 'release_id', 'environment'),)",
'object_name': 'GroupRelease'
},
'environment':
('django.db.models.fields.CharField', [], {
'default': "''",
'max_length': '64'
}),
'first_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'sentry.groupresolution': {
'Meta': {
'object_name': 'GroupResolution'
},
'datetime': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'unique': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
),
'status':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.grouprulestatus': {
'Meta': {
'unique_together': "(('rule', 'group'),)",
'object_name': 'GroupRuleStatus'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_active': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'rule': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Rule']"
}
),
'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {
'default': '0'
})
},
'sentry.groupseen': {
'Meta': {
'unique_together': "(('user', 'group'),)",
'object_name': 'GroupSeen'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'db_index': 'False'
}
)
},
'sentry.groupsnooze': {
'Meta': {
'object_name': 'GroupSnooze'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'unique': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'until': ('django.db.models.fields.DateTimeField', [], {})
},
'sentry.groupsubscription': {
'Meta': {
'unique_together': "(('group', 'user'),)",
'object_name': 'GroupSubscription'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'subscription_set'",
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_active': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'subscription_set'",
'to': "orm['sentry.Project']"
}
),
'reason':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.grouptagkey': {
'Meta': {
'unique_together': "(('project', 'group', 'key'),)",
'object_name': 'GroupTagKey'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'values_seen':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.grouptagvalue': {
'Meta': {
'unique_together': "(('group', 'key', 'value'),)",
'object_name': 'GroupTagValue',
'db_table': "'sentry_messagefiltervalue'",
'index_together': "(('project', 'key', 'value', 'last_seen'),)"
},
'first_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True',
'db_index': 'True'
}
),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'grouptag'",
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True',
'db_index': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'grouptag'",
'null': 'True',
'to': "orm['sentry.Project']"
}
),
'times_seen':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'value': ('django.db.models.fields.CharField', [], {
'max_length': '200'
})
},
'sentry.lostpasswordhash': {
'Meta': {
'object_name': 'LostPasswordHash'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'hash': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'unique': 'True'
}
)
},
'sentry.option': {
'Meta': {
'object_name': 'Option'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '64'
}),
'last_updated':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'value': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {})
},
'sentry.organization': {
'Meta': {
'object_name': 'Organization'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'default_role':
('django.db.models.fields.CharField', [], {
'default': "'member'",
'max_length': '32'
}),
'flags': ('django.db.models.fields.BigIntegerField', [], {
'default': '1'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'members': (
'django.db.models.fields.related.ManyToManyField', [], {
'related_name': "'org_memberships'",
'symmetrical': 'False',
'through': "orm['sentry.OrganizationMember']",
'to': "orm['sentry.User']"
}
),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'slug':
('django.db.models.fields.SlugField', [], {
'unique': 'True',
'max_length': '50'
}),
'status':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.organizationaccessrequest': {
'Meta': {
'unique_together': "(('team', 'member'),)",
'object_name': 'OrganizationAccessRequest'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'member': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.OrganizationMember']"
}
),
'team': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Team']"
}
)
},
'sentry.organizationavatar': {
'Meta': {
'object_name': 'OrganizationAvatar'
},
'avatar_type':
('django.db.models.fields.PositiveSmallIntegerField', [], {
'default': '0'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']",
'unique': 'True',
'null': 'True',
'on_delete': 'models.SET_NULL'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': (
'django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '32',
'db_index': 'True'
}
),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'avatar'",
'unique': 'True',
'to': "orm['sentry.Organization']"
}
)
},
'sentry.organizationmember': {
'Meta': {
'unique_together': "(('organization', 'user'), ('organization', 'email'))",
'object_name': 'OrganizationMember'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email': (
'django.db.models.fields.EmailField', [], {
'max_length': '75',
'null': 'True',
'blank': 'True'
}
),
'flags': ('django.db.models.fields.BigIntegerField', [], {
'default': '0'
}),
'has_global_access': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'member_set'",
'to': "orm['sentry.Organization']"
}
),
'role':
('django.db.models.fields.CharField', [], {
'default': "'member'",
'max_length': '32'
}),
'teams': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.Team']",
'symmetrical': 'False',
'through': "orm['sentry.OrganizationMemberTeam']",
'blank': 'True'
}
),
'token': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'unique': 'True',
'null': 'True',
'blank': 'True'
}
),
'type': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '50',
'blank': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'blank': 'True',
'related_name': "'sentry_orgmember_set'",
'null': 'True',
'to': "orm['sentry.User']"
}
)
},
'sentry.organizationmemberteam': {
'Meta': {
'unique_together': "(('team', 'organizationmember'),)",
'object_name': 'OrganizationMemberTeam',
'db_table': "'sentry_organizationmember_teams'"
},
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {
'primary_key': 'True'
}),
'is_active': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'organizationmember': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.OrganizationMember']"
}
),
'team': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Team']"
}
)
},
'sentry.organizationonboardingtask': {
'Meta': {
'unique_together': "(('organization', 'task'),)",
'object_name': 'OrganizationOnboardingTask'
},
'data': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_completed':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'task': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'null': 'True'
}
)
},
'sentry.organizationoption': {
'Meta': {
'unique_together': "(('organization', 'key'),)",
'object_name': 'OrganizationOption',
'db_table': "'sentry_organizationoptions'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'value': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {})
},
'sentry.processingissue': {
'Meta': {
'unique_together': "(('project', 'checksum', 'type'),)",
'object_name': 'ProcessingIssue'
},
'checksum':
('django.db.models.fields.CharField', [], {
'max_length': '40',
'db_index': 'True'
}),
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}),
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'type': ('django.db.models.fields.CharField', [], {
'max_length': '30'
})
},
'sentry.project': {
'Meta': {
'unique_together': "(('team', 'slug'), ('organization', 'slug'))",
'object_name': 'Project'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'first_event': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'flags':
('django.db.models.fields.BigIntegerField', [], {
'default': '0',
'null': 'True'
}),
'forced_color': (
'django.db.models.fields.CharField', [], {
'max_length': '6',
'null': 'True',
'blank': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '200'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'public': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'slug': ('django.db.models.fields.SlugField', [], {
'max_length': '50',
'null': 'True'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'team': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Team']"
}
)
},
'sentry.projectbookmark': {
'Meta': {
'unique_together': "(('project_id', 'user'),)",
'object_name': 'ProjectBookmark'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.projectdsymfile': {
'Meta': {
'unique_together': "(('project', 'uuid'),)",
'object_name': 'ProjectDSymFile'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_name': ('django.db.models.fields.TextField', [], {}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'uuid': ('django.db.models.fields.CharField', [], {
'max_length': '36'
})
},
'sentry.projectkey': {
'Meta': {
'object_name': 'ProjectKey'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'label': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True',
'blank': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'key_set'",
'to': "orm['sentry.Project']"
}
),
'public_key': (
'django.db.models.fields.CharField', [], {
'max_length': '32',
'unique': 'True',
'null': 'True'
}
),
'roles': ('django.db.models.fields.BigIntegerField', [], {
'default': '1'
}),
'secret_key': (
'django.db.models.fields.CharField', [], {
'max_length': '32',
'unique': 'True',
'null': 'True'
}
),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
)
},
'sentry.projectoption': {
'Meta': {
'unique_together': "(('project', 'key'),)",
'object_name': 'ProjectOption',
'db_table': "'sentry_projectoptions'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'value': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {})
},
'sentry.projectplatform': {
'Meta': {
'unique_together': "(('project_id', 'platform'),)",
'object_name': 'ProjectPlatform'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'platform': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.rawevent': {
'Meta': {
'unique_together': "(('project', 'event_id'),)",
'object_name': 'RawEvent'
},
'data':
('sentry.db.models.fields.node.NodeField', [], {
'null': 'True',
'blank': 'True'
}),
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event_id':
('django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
)
},
'sentry.release': {
'Meta': {
'unique_together': "(('organization', 'version'),)",
'object_name': 'Release'
},
'data': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'date_released':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'blank': 'True'
}),
'date_started':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'blank': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'new_groups':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'owner': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'null': 'True',
'blank': 'True'
}
),
'project_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'projects': (
'django.db.models.fields.related.ManyToManyField', [], {
'related_name': "'releases'",
'symmetrical': 'False',
'through': "orm['sentry.ReleaseProject']",
'to': "orm['sentry.Project']"
}
),
'ref': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True',
'blank': 'True'
}
),
'url': (
'django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True',
'blank': 'True'
}
),
'version': ('django.db.models.fields.CharField', [], {
'max_length': '64'
})
},
'sentry.releasecommit': {
'Meta': {
'unique_together': "(('release', 'commit'), ('release', 'order'))",
'object_name': 'ReleaseCommit'
},
'commit': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Commit']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'order': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True',
'db_index': 'True'
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.releaseenvironment': {
'Meta': {
'unique_together': "(('project_id', 'release_id', 'environment_id'),)",
'object_name': 'ReleaseEnvironment',
'db_table': "'sentry_environmentrelease'"
},
'environment_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'first_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True',
'db_index': 'True'
}
),
'release_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'sentry.releasefile': {
'Meta': {
'unique_together': "(('release', 'ident'),)",
'object_name': 'ReleaseFile'
},
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'name': ('django.db.models.fields.TextField', [], {}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'project_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.releaseproject': {
'Meta': {
'unique_together': "(('project', 'release'),)",
'object_name': 'ReleaseProject',
'db_table': "'sentry_release_project'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'new_groups': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'null': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.repository': {
'Meta': {
'unique_together':
"(('organization_id', 'name'), ('organization_id', 'provider', 'external_id'))",
'object_name':
'Repository'
},
'config': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'external_id':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '200'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'provider':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'url': ('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
})
},
'sentry.reprocessingreport': {
'Meta': {
'unique_together': "(('project', 'event_id'),)",
'object_name': 'ReprocessingReport'
},
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event_id':
('django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
)
},
'sentry.rule': {
'Meta': {
'object_name': 'Rule'
},
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'label': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
)
},
'sentry.savedsearch': {
'Meta': {
'unique_together': "(('project', 'name'),)",
'object_name': 'SavedSearch'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_default': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'query': ('django.db.models.fields.TextField', [], {})
},
'sentry.savedsearchuserdefault': {
'Meta': {
'unique_together': "(('project', 'user'),)",
'object_name': 'SavedSearchUserDefault',
'db_table': "'sentry_savedsearch_userdefault'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'savedsearch': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.SavedSearch']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.tagkey': {
'Meta': {
'unique_together': "(('project', 'key'),)",
'object_name': 'TagKey',
'db_table': "'sentry_filterkey'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'label':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'status':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'values_seen':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.tagvalue': {
'Meta': {
'unique_together': "(('project', 'key', 'value'),)",
'object_name': 'TagValue',
'db_table': "'sentry_filtervalue'"
},
'data': (
'sentry.db.models.fields.gzippeddict.GzippedDictField', [], {
'null': 'True',
'blank': 'True'
}
),
'first_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True',
'db_index': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True',
'db_index': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'times_seen':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'value': ('django.db.models.fields.CharField', [], {
'max_length': '200'
})
},
'sentry.team': {
'Meta': {
'unique_together': "(('organization', 'slug'),)",
'object_name': 'Team'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'slug': ('django.db.models.fields.SlugField', [], {
'max_length': '50'
}),
'status':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.user': {
'Meta': {
'object_name': 'User',
'db_table': "'auth_user'"
},
'date_joined':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email':
('django.db.models.fields.EmailField', [], {
'max_length': '75',
'blank': 'True'
}),
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {
'primary_key': 'True'
}),
'is_active': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'is_managed': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'is_password_expired':
('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'is_staff': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'last_login':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'last_password_change': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'name': (
'django.db.models.fields.CharField', [], {
'max_length': '200',
'db_column': "'first_name'",
'blank': 'True'
}
),
'password': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'session_nonce':
('django.db.models.fields.CharField', [], {
'max_length': '12',
'null': 'True'
}),
'username':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '128'
})
},
'sentry.useravatar': {
'Meta': {
'object_name': 'UserAvatar'
},
'avatar_type':
('django.db.models.fields.PositiveSmallIntegerField', [], {
'default': '0'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']",
'unique': 'True',
'null': 'True',
'on_delete': 'models.SET_NULL'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': (
'django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '32',
'db_index': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'avatar'",
'unique': 'True',
'to': "orm['sentry.User']"
}
)
},
'sentry.useremail': {
'Meta': {
'unique_together': "(('user', 'email'),)",
'object_name': 'UserEmail'
},
'date_hash_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_verified': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'emails'",
'to': "orm['sentry.User']"
}
),
'validation_hash': (
'django.db.models.fields.CharField', [], {
'default': "u'MJgpqztt1JFwT0a7mqP7bJys66oGvuWt'",
'max_length': '32'
}
)
},
'sentry.useroption': {
'Meta': {
'unique_together': "(('user', 'project', 'key'),)",
'object_name': 'UserOption'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
),
'value': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {})
},
'sentry.userreport': {
'Meta': {
'unique_together': "(('project', 'event_id'),)",
'object_name': 'UserReport',
'index_together': "(('project', 'event_id'), ('project', 'date_added'))"
},
'comments': ('django.db.models.fields.TextField', [], {}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'event_id': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
)
},
'sentry.versiondsymfile': {
'Meta': {
'unique_together': "(('dsym_file', 'version', 'build'),)",
'object_name': 'VersionDSymFile'
},
'build':
('django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'dsym_app': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymApp']"
}
),
'dsym_file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ProjectDSymFile']",
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'version': ('django.db.models.fields.CharField', [], {
'max_length': '32'
})
}
}
complete_apps = ['sentry']
| 37.01455
| 100
| 0.405496
|
720fd9ee5cae6400f85316ea774854b4d0d8884b
| 436
|
py
|
Python
|
Backend/events/models.py
|
afrlv1/TestWorkEvents
|
d023ce3ecadcead99134e5be536c7610d2b05970
|
[
"MIT"
] | null | null | null |
Backend/events/models.py
|
afrlv1/TestWorkEvents
|
d023ce3ecadcead99134e5be536c7610d2b05970
|
[
"MIT"
] | null | null | null |
Backend/events/models.py
|
afrlv1/TestWorkEvents
|
d023ce3ecadcead99134e5be536c7610d2b05970
|
[
"MIT"
] | null | null | null |
from django.db import models
class Event(models.Model):
day_event = models.DateField(u'Day of the event', help_text=u'Day of the event')
title = models.CharField(u'Title', max_length=255, help_text=u'Title', blank=True, null=True)
body = models.TextField(u'Textual Event', help_text=u'Textual Event', blank=True, null=True)
class Meta:
verbose_name = u'Scheduling'
verbose_name_plural = u'Scheduling'
| 36.333333
| 97
| 0.711009
|
92759cd2bf8ac797b3fa4f368027c9f7ffaaac48
| 1,634
|
py
|
Python
|
tests/src/SI/MAP/click_on_anydistrict_and_download_csv.py
|
sreenivas8084/cQube
|
3352a13f41679d707979e287d1880f0723b27510
|
[
"MIT"
] | null | null | null |
tests/src/SI/MAP/click_on_anydistrict_and_download_csv.py
|
sreenivas8084/cQube
|
3352a13f41679d707979e287d1880f0723b27510
|
[
"MIT"
] | 2
|
2022-02-01T00:55:12.000Z
|
2022-03-29T22:29:09.000Z
|
tests/src/SI/MAP/click_on_anydistrict_and_download_csv.py
|
SreenivasNimmagadda/cQube
|
3352a13f41679d707979e287d1880f0723b27510
|
[
"MIT"
] | null | null | null |
import csv
import os
import re
import time
from Data.parameters import Data
from filenames import file_extention
from get_dir import pwd
from reuse_func import GetData
class download_icon():
def __init__(self,driver):
self.driver = driver
def test_donwload(self):
self.p =GetData()
cal = pwd()
count = 0
self.fname = file_extention()
self.driver.find_element_by_xpath(Data.hyper_link).click()
self.p.page_loading(self.driver)
self.driver.find_element_by_id(Data.home).click()
time.sleep(2)
self.p.navigate_to_school_infrastructure_map()
self.p.page_loading(self.driver)
self.driver.find_element_by_id(Data.Download).click()
time.sleep(3)
self.filename = cal.get_download_dir() + '/' + self.fname.scmap_district()+self.p.get_current_date()+'.csv'
self.p.page_loading(self.driver)
if not os.path.isfile(self.filename):
print("Districtwise csv is not downloaded")
count = count + 1
else:
with open(self.filename) as fin:
csv_reader = csv.reader(fin, delimiter=',')
header = next(csv_reader)
schools = 0
for row in csv.reader(fin):
schools += int(row[0])
school = self.driver.find_element_by_id("schools").text
sc = re.sub('\D', "", school)
if int(sc) != int(schools):
print("school count mismatched")
count = count + 1
os.remove(self.filename)
return count
| 32.039216
| 115
| 0.589351
|
538d5202942d2613aada1adbaf6f6ebe94a23521
| 197,163
|
py
|
Python
|
python/mxnet/ndarray/numpy/_op.py
|
guanxinq/incubator-mxnet
|
634f95e2431ec107f0e5182a60db27e3a7dd9545
|
[
"Apache-2.0"
] | null | null | null |
python/mxnet/ndarray/numpy/_op.py
|
guanxinq/incubator-mxnet
|
634f95e2431ec107f0e5182a60db27e3a7dd9545
|
[
"Apache-2.0"
] | null | null | null |
python/mxnet/ndarray/numpy/_op.py
|
guanxinq/incubator-mxnet
|
634f95e2431ec107f0e5182a60db27e3a7dd9545
|
[
"Apache-2.0"
] | 1
|
2019-02-26T19:25:11.000Z
|
2019-02-26T19:25:11.000Z
|
# pylint: disable=C0302
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=unused-argument
"""Namespace for numpy operators used in Gluon dispatched by F=ndarray."""
from __future__ import absolute_import
import numpy as _np
from ...base import numeric_types, integer_types
from ...util import _sanity_check_params, set_module
from ...util import wrap_np_unary_func, wrap_np_binary_func
from ...context import current_context
from . import _internal as _npi
from ..ndarray import NDArray
__all__ = ['shape', 'zeros', 'zeros_like', 'ones', 'ones_like', 'full', 'full_like',
'add', 'subtract', 'multiply', 'divide', 'mod', 'remainder', 'power',
'arctan2', 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'log10', 'sqrt', 'cbrt', 'abs',
'absolute', 'exp', 'expm1', 'arcsin', 'arccos', 'arctan', 'sign', 'log', 'degrees', 'log2',
'log1p', 'rint', 'radians', 'reciprocal', 'square', 'negative', 'fix', 'ceil', 'floor',
'trunc', 'logical_not', 'arcsinh', 'arccosh', 'arctanh', 'argsort', 'tensordot', 'histogram', 'eye',
'linspace', 'logspace', 'expand_dims', 'tile', 'arange', 'split', 'vsplit', 'concatenate', 'append',
'stack', 'vstack', 'column_stack', 'dstack', 'average', 'mean', 'maximum', 'minimum', 'swapaxes', 'clip',
'argmax', 'argmin', 'std', 'var', 'indices', 'copysign', 'ravel', 'unravel_index', 'hanning', 'hamming',
'blackman', 'flip', 'around', 'hypot', 'bitwise_xor', 'bitwise_or', 'rad2deg', 'deg2rad', 'unique', 'lcm',
'tril', 'identity', 'take', 'ldexp', 'vdot', 'inner', 'outer', 'equal', 'not_equal', 'greater', 'less',
'greater_equal', 'less_equal', 'hsplit', 'rot90', 'einsum', 'true_divide', 'nonzero', 'shares_memory',
'may_share_memory', 'diff', 'resize', 'nan_to_num', 'where']
@set_module('mxnet.ndarray.numpy')
def shape(a):
"""
Return the shape of an array.
Parameters
----------
a : array_like
Input array.
Returns
-------
shape : tuple of ints
The elements of the shape tuple give the lengths of the
corresponding array dimensions.
See Also
--------
ndarray.shape : Equivalent array method.
Examples
--------
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
"""
return a.shape
@set_module('mxnet.ndarray.numpy')
def zeros(shape, dtype=_np.float32, order='C', ctx=None): # pylint: disable=redefined-outer-name
"""Return a new array of given shape and type, filled with zeros.
This function currently only supports storing multi-dimensional data
in row-major (C-style).
Parameters
----------
shape : int or tuple of int
The shape of the empty array.
dtype : str or numpy.dtype, optional
An optional value type. Default is `numpy.float32`. Note that this
behavior is different from NumPy's `zeros` function where `float64`
is the default value, because `float32` is considered as the default
data type in deep learning.
order : {'C'}, optional, default: 'C'
How to store multi-dimensional data in memory, currently only row-major
(C-style) is supported.
ctx : Context, optional
An optional device context (default is the current default context).
Returns
-------
out : ndarray
Array of zeros with the given shape, dtype, and ctx.
"""
if order != 'C':
raise NotImplementedError
if ctx is None:
ctx = current_context()
dtype = _np.float32 if dtype is None else dtype
return _npi.zeros(shape=shape, ctx=ctx, dtype=dtype)
@set_module('mxnet.ndarray.numpy')
def ones(shape, dtype=_np.float32, order='C', ctx=None): # pylint: disable=redefined-outer-name
"""Return a new array of given shape and type, filled with ones.
This function currently only supports storing multi-dimensional data
in row-major (C-style).
Parameters
----------
shape : int or tuple of int
The shape of the empty array.
dtype : str or numpy.dtype, optional
An optional value type. Default is `numpy.float32`. Note that this
behavior is different from NumPy's `ones` function where `float64`
is the default value, because `float32` is considered as the default
data type in deep learning.
order : {'C'}, optional, default: 'C'
How to store multi-dimensional data in memory, currently only row-major
(C-style) is supported.
ctx : Context, optional
An optional device context (default is the current default context).
Returns
-------
out : ndarray
Array of ones with the given shape, dtype, and ctx.
"""
if order != 'C':
raise NotImplementedError
if ctx is None:
ctx = current_context()
dtype = _np.float32 if dtype is None else dtype
return _npi.ones(shape=shape, ctx=ctx, dtype=dtype)
# pylint: disable=too-many-arguments, redefined-outer-name
@set_module('mxnet.ndarray.numpy')
def zeros_like(a, dtype=None, order='C', ctx=None, out=None):
"""
Return an array of zeros with the same shape and type as a given array.
Parameters
----------
a : ndarray
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
Temporarily do not support boolean type.
order : {'C'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. Currently only supports C order.
ctx: to specify the device, e.g. the i-th GPU.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
out : ndarray
Array of zeros with the same shape and type as a.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full : Return a new array of given shape filled with value.
Examples
--------
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0., 1., 2.],
[3., 4., 5.]])
>>> np.zeros_like(x)
array([[0., 0., 0.],
[0., 0., 0.]])
>>> np.zeros_like(x, int)
array([[0, 0, 0],
[0, 0, 0]], dtype=int64)
>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1., 2.], dtype=float64)
>>> np.zeros_like(y)
array([0., 0., 0.], dtype=float64)
"""
return _npi.full_like(a, fill_value=0, dtype=dtype, ctx=None, out=None)
@set_module('mxnet.ndarray.numpy')
def ones_like(a, dtype=None, order='C', ctx=None, out=None):
"""
Return an array of ones with the same shape and type as a given array.
Parameters
----------
a : ndarray
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
Temporarily do not support boolean type.
order : {'C'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. Currently only supports C order.
ctx: to specify the device, e.g. the i-th GPU.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
out : ndarray
Array of ones with the same shape and type as a.
See Also
--------
empty_like : Return an empty array with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full_like : Return a new array with shape of input filled with value.
ones : Return a new array setting values to one.
Examples
--------
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0., 1., 2.],
[3., 4., 5.]])
>>> np.ones_like(x)
array([[1., 1., 1.],
[1., 1., 1.]])
>>> np.ones_like(x, int)
array([[1, 1, 1],
[1, 1, 1]], dtype=int64)
>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1., 2.], dtype=float64)
>>> np.ones_like(y)
array([1., 1., 1.], dtype=float64)
"""
return _npi.full_like(a, fill_value=1, dtype=dtype, ctx=None, out=None)
@set_module('mxnet.ndarray.numpy')
def full(shape, fill_value, dtype=None, order='C', ctx=None, out=None): # pylint: disable=too-many-arguments
"""
Return a new array of given shape and type, filled with `fill_value`.
Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
fill_value : scalar
Fill value.
dtype : data-type, optional
The desired data-type for the array. The default, `None`, means
`np.array(fill_value).dtype`.
order : {'C'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. Currently only supports C order.
ctx: to specify the device, e.g. the i-th GPU.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
out : ndarray
Array of `fill_value` with the given shape, dtype, and order.
Notes
-----
This function differs from the original `numpy.full
https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html`_ in
the following way(s):
- Have an additional `ctx` argument to specify the device
- Have an additional `out` argument
- Currently does not support `order` selection
See Also
--------
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.
Examples
--------
>>> np.full((2, 2), 10)
array([[10., 10.],
[10., 10.]])
>>> np.full((2, 2), 2, dtype=np.int32, ctx=mx.cpu(0))
array([[2, 2],
[2, 2]], dtype=int32)
"""
if order != 'C':
raise NotImplementedError
if ctx is None:
ctx = current_context()
dtype = _np.float32 if dtype is None else dtype
return _npi.full(shape=shape, value=fill_value, ctx=ctx, dtype=dtype, out=out)
# pylint: enable=too-many-arguments, redefined-outer-name
@set_module('mxnet.ndarray.numpy')
def full_like(a, fill_value, dtype=None, order='C', ctx=None, out=None): # pylint: disable=too-many-arguments
"""
Return a full array with the same shape and type as a given array.
Parameters
----------
a : ndarray
The shape and data-type of `a` define these same attributes of
the returned array.
fill_value : scalar
Fill value.
dtype : data-type, optional
Overrides the data type of the result.
Temporarily do not support boolean type.
order : {'C'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. Currently only supports C order.
ctx: to specify the device, e.g. the i-th GPU.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
out : ndarray
Array of `fill_value` with the same shape and type as `a`.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full : Return a new array of given shape filled with value.
Examples
--------
>>> x = np.arange(6, dtype=int)
>>> np.full_like(x, 1)
array([1, 1, 1, 1, 1, 1], dtype=int64)
>>> np.full_like(x, 0.1)
array([0, 0, 0, 0, 0, 0], dtype=int64)
>>> np.full_like(x, 0.1, dtype=np.float64)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1], dtype=float64)
>>> np.full_like(x, np.nan, dtype=np.double)
array([nan, nan, nan, nan, nan, nan], dtype=float64)
>>> y = np.arange(6, dtype=np.float32)
>>> np.full_like(y, 0.1)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
"""
if order != 'C':
raise NotImplementedError
if ctx is None:
ctx = current_context()
return _npi.full_like(a, fill_value=fill_value, dtype=dtype, ctx=ctx, out=out)
@set_module('mxnet.ndarray.numpy')
def arange(start, stop=None, step=1, dtype=None, ctx=None):
"""Return evenly spaced values within a given interval.
Values are generated within the half-open interval ``[start, stop)``
(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range` function, but returns an ndarray rather than a list.
Parameters
----------
start : number, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : number
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : number, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype
The type of the output array. The default is `float32`.
Returns
-------
arange : ndarray
Array of evenly spaced values.
For floating point arguments, the length of the result is
``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.
"""
if dtype is None:
dtype = 'float32'
if ctx is None:
ctx = current_context()
if stop is None:
stop = start
start = 0
if step is None:
step = 1
if start is None and stop is None:
raise ValueError('start and stop cannot be both None')
if step == 0:
raise ZeroDivisionError('step cannot be 0')
return _npi.arange(start=start, stop=stop, step=step, dtype=dtype, ctx=ctx)
@set_module('mxnet.ndarray.numpy')
def identity(n, dtype=None, ctx=None):
"""
Return the identity array.
The identity array is a square array with ones on
the main diagonal.
Parameters
----------
n : int
Number of rows (and columns) in `n` x `n` output.
dtype : data-type, optional
Data-type of the output. Defaults to ``numpy.float32``.
ctx : Context, optional
An optional device context (default is the current default context).
Returns
-------
out : ndarray
`n` x `n` array with its main diagonal set to one,
and all other elements 0.
Examples
--------
>>> np.identity(3)
>>> np.identity(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
"""
if not isinstance(n, int):
raise TypeError("Input 'n' should be an integer")
if n < 0:
raise ValueError("Input 'n' cannot be negative")
if ctx is None:
ctx = current_context()
dtype = _np.float32 if dtype is None else dtype
return _npi.identity(shape=(n, n), ctx=ctx, dtype=dtype)
# pylint: disable=redefined-outer-name
@set_module('mxnet.ndarray.numpy')
def take(a, indices, axis=None, mode='raise', out=None):
r"""
Take elements from an array along an axis.
When axis is not None, this function does the same thing as "fancy"
indexing (indexing arrays using arrays); however, it can be easier to use
if you need elements along a given axis. A call such as
``np.take(arr, indices, axis=3)`` is equivalent to
``arr[:,:,:,indices,...]``.
Explained without fancy indexing, this is equivalent to the following use
of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
indices::
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
Nj = indices.shape
for ii in ndindex(Ni):
for jj in ndindex(Nj):
for kk in ndindex(Nk):
out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
Parameters
----------
a : ndarray
The source array.
indices : ndarray
The indices of the values to extract. Also allow scalars for indices.
axis : int, optional
The axis over which to select values. By default, the flattened
input array is used.
out : ndarray, optional
If provided, the result will be placed in this array. It should
be of the appropriate shape and dtype.
mode : {'clip', 'wrap'}, optional
Specifies how out-of-bounds indices will behave.
* 'clip' -- clip to the range (default)
* 'wrap' -- wrap around
'clip' mode means that all indices that are too large are replaced
by the index that addresses the last element along that axis. Note
that this disables indexing with negative numbers.
Returns
-------
out : ndarray
The returned array has the same type as `a`.
Notes
-----
This function differs from the original `numpy.take
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html>`_ in
the following way(s):
- Only ndarray or scalar ndarray is accepted as valid input.
Examples
--------
>>> a = np.array([4, 3, 5, 7, 6, 8])
>>> indices = np.array([0, 1, 4])
>>> np.take(a, indices)
array([4., 3., 6.])
In this example for `a` is an ndarray, "fancy" indexing can be used.
>>> a[indices]
array([4., 3., 6.])
If `indices` is not one dimensional, the output also has these dimensions.
>>> np.take(a, np.array([[0, 1], [2, 3]]))
array([[4., 3.],
[5., 7.]])
"""
if mode not in ('wrap', 'clip', 'raise'):
raise NotImplementedError(
"function take does not support mode '{}'".format(mode))
if axis is None:
return _npi.take(_npi.reshape(a, -1), indices, 0, mode, out)
else:
return _npi.take(a, indices, axis, mode, out)
# pylint: enable=redefined-outer-name
#pylint: disable= too-many-arguments, no-member, protected-access
def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None, out=None):
""" Helper function for element-wise operation.
The function will perform numpy-like broadcasting if needed and call different functions.
Parameters
--------
lhs : ndarray or numeric value
Left-hand side operand.
rhs : ndarray or numeric value
Right-hand operand,
fn_array : function
Function to be called if both lhs and rhs are of ``ndarray`` type.
fn_scalar : function
Function to be called if both lhs and rhs are numeric values.
lfn_scalar : function
Function to be called if lhs is ``ndarray`` while rhs is numeric value
rfn_scalar : function
Function to be called if lhs is numeric value while rhs is ``ndarray``;
if none is provided, then the function is commutative, so rfn_scalar is equal to lfn_scalar
Returns
--------
mxnet.numpy.ndarray or scalar
result array or scalar
"""
from ...numpy import ndarray
if isinstance(lhs, numeric_types):
if isinstance(rhs, numeric_types):
return fn_scalar(lhs, rhs, out=out)
else:
if rfn_scalar is None:
# commutative function
return lfn_scalar(rhs, float(lhs), out=out)
else:
return rfn_scalar(rhs, float(lhs), out=out)
elif isinstance(rhs, numeric_types):
return lfn_scalar(lhs, float(rhs), out=out)
elif isinstance(rhs, ndarray):
return fn_array(lhs, rhs, out=out)
else:
raise TypeError('type {} not supported'.format(str(type(rhs))))
#pylint: enable= too-many-arguments, no-member, protected-access
@set_module('mxnet.ndarray.numpy')
def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None):
"""
Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional
outputs in addition to the unique elements:
* the indices of the input array that give the unique values
* the indices of the unique array that reconstruct the input array
* the number of times each unique value comes up in the input array
Parameters
----------
ar : ndarray
Input array. Unless `axis` is specified, this will be flattened if it
is not already 1-D.
return_index : bool, optional
If True, also return the indices of `ar` (along the specified axis,
if provided, or in the flattened array) that result in the unique array.
return_inverse : bool, optional
If True, also return the indices of the unique array (for the specified
axis, if provided) that can be used to reconstruct `ar`.
return_counts : bool, optional
If True, also return the number of times each unique item appears
in `ar`.
axis : int or None, optional
The axis to operate on. If None, `ar` will be flattened. If an integer,
the subarrays indexed by the given axis will be flattened and treated
as the elements of a 1-D array with the dimension of the given axis,
see the notes for more details. The default is None.
Returns
-------
unique : ndarray
The sorted unique values.
unique_indices : ndarray, optional
The indices of the first occurrences of the unique values in the
original array. Only provided if `return_index` is True.
unique_inverse : ndarray, optional
The indices to reconstruct the original array from the
unique array. Only provided if `return_inverse` is True.
unique_counts : ndarray, optional
The number of times each of the unique values comes up in the
original array. Only provided if `return_counts` is True.
Notes
-----
When an axis is specified the subarrays indexed by the axis are sorted.
This is done by making the specified axis the first dimension of the array
and then flattening the subarrays in C order. The flattened subarrays are
then viewed as a structured type with each element given a label, with the
effect that we end up with a 1-D array of structured types that can be
treated in the same way as any other 1-D array. The result is that the
flattened subarrays are sorted in lexicographic order starting with the
first element.
This function differs from the original `numpy.unique
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html>`_ in
the following aspects:
- Only support ndarray as input.
- Object arrays or structured arrays are not supported.
Examples
--------
>>> np.unique(np.array([1, 1, 2, 2, 3, 3]))
array([1., 2., 3.])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1., 2., 3.])
Return the unique rows of a 2D array
>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
>>> np.unique(a, axis=0)
array([[1., 0., 0.],
[2., 3., 4.]])
Return the indices of the original array that give the unique values:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array([1., 2., 3., 4., 6.])
>>> indices
array([0, 1, 5, 3, 2], dtype=int64)
>>> a[indices]
array([1., 2., 3., 4., 6.])
Reconstruct the input array from the unique values:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_inverse=True)
>>> u
array([1., 2., 3., 4., 6.])
>>> indices
array([0, 1, 4, 3, 1, 2, 1], dtype=int64)
>>> u[indices]
array([1., 2., 6., 4., 2., 3., 2.])
"""
ret = _npi.unique(ar, return_index, return_inverse, return_counts, axis)
if isinstance(ret, list):
return tuple(ret)
else:
return ret
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def add(x1, x2, out=None, **kwargs):
"""
Add arguments element-wise.
Parameters
----------
x1, x2 : ndarrays or scalar values
The arrays to be added. If x1.shape != x2.shape, they must be broadcastable to
a common shape (which may be the shape of one or the other).
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
add : ndarray or scalar
The sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.
Notes
-----
This operator now supports automatic type promotion. The resulting type will be determined
according to the following rules:
* If both inputs are of floating number types, the output is the more precise type.
* If only one of the inputs is floating number type, the result is that type.
* If both inputs are of integer types (including boolean), not supported yet.
"""
return _ufunc_helper(x1, x2, _npi.add, _np.add, _npi.add_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def subtract(x1, x2, out=None, **kwargs):
"""
Subtract arguments element-wise.
Parameters
----------
x1, x2 : ndarrays or scalar values
The arrays to be subtracted from each other. If x1.shape != x2.shape,
they must be broadcastable to a common shape (which may be the shape
of one or the other).
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
subtract : ndarray or scalar
The difference of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.
Notes
-----
This operator now supports automatic type promotion. The resulting type will be determined
according to the following rules:
* If both inputs are of floating number types, the output is the more precise type.
* If only one of the inputs is floating number type, the result is that type.
* If both inputs are of integer types (including boolean), not supported yet.
"""
return _ufunc_helper(x1, x2, _npi.subtract, _np.subtract, _npi.subtract_scalar,
_npi.rsubtract_scalar, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def multiply(x1, x2, out=None, **kwargs):
"""
Multiply arguments element-wise.
Parameters
----------
x1, x2 : ndarrays or scalar values
The arrays to be multiplied. If x1.shape != x2.shape, they must be broadcastable to
a common shape (which may be the shape of one or the other).
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
out : ndarray or scalar
The multiplication of x1 and x2, element-wise. This is a scalar if both x1 and x2
are scalars.
Notes
-----
This operator now supports automatic type promotion. The resulting type will be determined
according to the following rules:
* If both inputs are of floating number types, the output is the more precise type.
* If only one of the inputs is floating number type, the result is that type.
* If both inputs are of integer types (including boolean), not supported yet.
"""
return _ufunc_helper(x1, x2, _npi.multiply, _np.multiply, _npi.multiply_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def divide(x1, x2, out=None, **kwargs):
"""
Returns a true division of the inputs, element-wise.
Parameters
----------
x1 : ndarray or scalar
Dividend array.
x2 : ndarray or scalar
Divisor array.
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
out : ndarray or scalar
This is a scalar if both x1 and x2 are scalars.
Notes
-----
This operator now supports automatic type promotion. The resulting type will be determined
according to the following rules:
* If both inputs are of floating number types, the output is the more precise type.
* If only one of the inputs is floating number type, the result is that type.
* If both inputs are of integer types (including boolean), the output is of float32 type.
"""
return _ufunc_helper(x1, x2, _npi.true_divide, _np.divide, _npi.true_divide_scalar,
_npi.rtrue_divide_scalar, out)
@set_module('mxnet.ndarray.numpy')
def true_divide(x1, x2, out=None):
"""Returns a true division of the inputs, element-wise.
Instead of the Python traditional 'floor division', this returns a true
division. True division adjusts the output type to present the best
answer, regardless of input types.
Parameters
----------
x1 : ndarray or scalar
Dividend array.
x2 : ndarray or scalar
Divisor array.
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
out : ndarray or scalar
This is a scalar if both x1 and x2 are scalars.
Notes
-----
This operator now supports automatic type promotion. The resulting type will be determined
according to the following rules:
* If both inputs are of floating number types, the output is the more precise type.
* If only one of the inputs is floating number type, the result is that type.
* If both inputs are of integer types (including boolean), the output is of float32 type.
"""
return _ufunc_helper(x1, x2, _npi.true_divide, _np.divide, _npi.true_divide_scalar,
_npi.rtrue_divide_scalar, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def mod(x1, x2, out=None, **kwargs):
"""
Return element-wise remainder of division.
Parameters
----------
x1 : ndarray or scalar
Dividend array.
x2 : ndarray or scalar
Divisor array.
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
out : ndarray or scalar
This is a scalar if both x1 and x2 are scalars.
"""
return _ufunc_helper(x1, x2, _npi.mod, _np.mod, _npi.mod_scalar, _npi.rmod_scalar, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def remainder(x1, x2, out=None):
"""
Return element-wise remainder of division.
Parameters
----------
x1 : ndarray or scalar
Dividend array.
x2 : ndarray or scalar
Divisor array.
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
out : ndarray or scalar
This is a scalar if both x1 and x2 are scalars.
"""
return _ufunc_helper(x1, x2, _npi.mod, _np.mod, _npi.mod_scalar, _npi.rmod_scalar, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def power(x1, x2, out=None, **kwargs):
"""
First array elements raised to powers from second array, element-wise.
Parameters
----------
x1 : ndarray or scalar
The bases.
x2 : ndarray or scalar
The exponent.
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
out : ndarray or scalar
The bases in x1 raised to the exponents in x2.
This is a scalar if both x1 and x2 are scalars.
"""
return _ufunc_helper(x1, x2, _npi.power, _np.power, _npi.power_scalar, _npi.rpower_scalar, out)
@set_module('mxnet.ndarray.numpy')
def argsort(a, axis=-1, kind=None, order=None):
"""
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified
by the `kind` keyword. It returns an array of indices of the same shape as
`a` that index data along the given axis in sorted order.
Parameters
----------
a : ndarray
Array to sort.
axis : int or None, optional
Axis along which to sort. The default is -1 (the last axis). If None,
the flattened array is used.
kind : string, optional
This argument can take any string, but it does not have any effect on the
final result.
order : str or list of str, optional
Not supported yet, will raise NotImplementedError if not None.
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified `axis`.
If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
More generally, ``np.take_along_axis(a, index_array, axis=axis)``
always yields the sorted `a`, irrespective of dimensionality.
Notes
-----
This operator does not support different sorting algorithms.
Examples
--------
One dimensional array:
>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])
Two-dimensional array:
>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
[2, 2]])
>>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
>>> ind
array([[0, 1],
[1, 0]])
>>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
array([[0, 2],
[2, 3]])
>>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
>>> ind
array([[0, 1],
[0, 1]])
>>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
array([[0, 3],
[2, 2]])
Indices of the sorted elements of a N-dimensional array:
>>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
>>> ind
(array([0, 1, 1, 0]), array([0, 0, 1, 1]))
>>> x[ind] # same as np.sort(x, axis=None)
array([0, 2, 2, 3])
"""
if order is not None:
raise NotImplementedError("order not supported here")
return _npi.argsort(data=a, axis=axis, is_ascend=True, dtype='int64')
@set_module('mxnet.ndarray.numpy')
def tensordot(a, b, axes=2):
r"""
tensordot(a, b, axes=2)
Compute tensor dot product along specified axes for arrays >= 1-D.
Given two tensors (arrays of dimension greater than or equal to one),
`a` and `b`, and an ndarray object containing two ndarray
objects, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s
elements (components) over the axes specified by ``a_axes`` and
``b_axes``. The third argument can be a single non-negative
integer_like scalar, ``N``; if it is such, then the last ``N``
dimensions of `a` and the first ``N`` dimensions of `b` are summed
over.
Parameters
----------
a, b : ndarray, len(shape) >= 1
Tensors to "dot".
axes : int or (2,) ndarray
* integer_like
If an int N, sum over the last N axes of `a` and the first N axes
of `b` in order. The sizes of the corresponding axes must match.
* (2,) ndarray
Or, a list of axes to be summed over, first sequence applying to `a`,
second to `b`. Both elements ndarray must be of the same length.
See Also
--------
dot, einsum
Notes
-----
Three common use cases are:
* ``axes = 0`` : tensor product :math:`a\otimes b`
* ``axes = 1`` : tensor dot product :math:`a\cdot b`
* ``axes = 2`` : (default) tensor double contraction :math:`a:b`
When `axes` is integer_like, the sequence for evaluation will be: first
the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and
Nth axis in `b` last.
When there is more than one axis to sum over - and they are not the last
(first) axes of `a` (`b`) - the argument `axes` should consist of
two sequences of the same length, with the first axis to sum over given
first in both sequences, the second axis second, and so forth.
Examples
--------
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5, 2)
>>> c
array([[ 4400., 4730.],
[ 4532., 4874.],
[ 4664., 5018.],
[ 4796., 5162.],
[ 4928., 5306.]])
"""
if _np.isscalar(axes):
return _npi.tensordot_int_axes(a, b, axes)
if len(axes) != 2:
raise ValueError('Axes must consist of two arrays.')
a_axes_summed, b_axes_summed = axes
if _np.isscalar(a_axes_summed):
a_axes_summed = (a_axes_summed,)
if _np.isscalar(b_axes_summed):
b_axes_summed = (b_axes_summed,)
if len(a_axes_summed) != len(b_axes_summed):
raise ValueError('Axes length mismatch')
return _npi.tensordot(a, b, a_axes_summed, b_axes_summed)
@set_module('mxnet.ndarray.numpy')
def histogram(a, bins=10, range=None, normed=None, weights=None, density=None): # pylint: disable=too-many-arguments
"""
Compute the histogram of a set of data.
Parameters
----------
a : ndarray
Input data. The histogram is computed over the flattened array.
bins : int or NDArray
If `bins` is an int, it defines the number of equal-width
bins in the given range (10, by default). If `bins` is a
sequence, it defines a monotonically increasing array of bin edges,
including the rightmost edge, allowing for non-uniform bin widths.
.. versionadded:: 1.11.0
If `bins` is a string, it defines the method used to calculate the
optimal bin width, as defined by `histogram_bin_edges`.
range : (float, float)
The lower and upper range of the bins. Required when `bins` is an integer.
Values outside the range are ignored. The first element of the range must
be less than or equal to the second.
normed : bool, optional
Not supported yet, coming soon.
weights : array_like, optional
Not supported yet, coming soon.
density : bool, optional
Not supported yet, coming soon.
"""
if normed is True:
raise NotImplementedError("normed is not supported yet...")
if weights is not None:
raise NotImplementedError("weights is not supported yet...")
if density is True:
raise NotImplementedError("density is not supported yet...")
if isinstance(bins, numeric_types):
if range is None:
raise NotImplementedError("automatic range is not supported yet...")
return _npi.histogram(a, bin_cnt=bins, range=range)
if isinstance(bins, (list, tuple)):
raise NotImplementedError("array_like bins is not supported yet...")
if isinstance(bins, str):
raise NotImplementedError("string bins is not supported yet...")
if isinstance(bins, NDArray):
return _npi.histogram(a, bins=bins)
raise ValueError("np.histogram fails with", locals())
@set_module('mxnet.ndarray.numpy')
def eye(N, M=None, k=0, dtype=_np.float32, **kwargs):
"""
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to N.
k : int, optional
Index of the diagonal: 0 (the default) refers to the main diagonal,
a positive value refers to an upper diagonal,
and a negative value to a lower diagonal.
dtype : data-type, optional
Data-type of the returned array.
Returns
-------
I : ndarray of shape (N,M)
An array where all elements are equal to zero,
except for the k-th diagonal, whose values are equal to one.
"""
_sanity_check_params('eye', ['order'], kwargs)
ctx = kwargs.pop('ctx', current_context())
if ctx is None:
ctx = current_context()
return _npi.eye(N, M, k, ctx, dtype)
@set_module('mxnet.ndarray.numpy')
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, ctx=None): # pylint: disable=too-many-arguments
r"""
Return evenly spaced numbers over a specified interval.
Returns num evenly spaced samples, calculated over the interval [start, stop].
The endpoint of the interval can optionally be excluded.
Parameters
----------
start : real number
The starting value of the sequence.
stop : real number
The end value of the sequence, unless endpoint is set to False. In
that case, the sequence consists of all but the last of num + 1
evenly spaced samples, so that stop is excluded. Note that the step
size changes when endpoint is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
If True, stop is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (samples, step), where step is the spacing between samples.
dtype : dtype, optional
The type of the output array. If dtype is not given, infer the data
type from the other input arguments.
axis : int, optional
The axis in the result to store the samples. Relevant only if start or
stop are array-like. By default (0), the samples will be along a new
axis inserted at the beginning. Use -1 to get an axis at the end.
Returns
-------
samples : ndarray
There are num equally spaced samples in the closed interval
`[start, stop]` or the half-open interval `[start, stop)`
(depending on whether endpoint is True or False).
step : float, optional
Only returned if retstep is True
Size of spacing between samples.
See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
number of samples).
Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([2. , 2.25, 2.5 , 2.75, 3. ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1.asnumpy(), y.asnumpy(), 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2.asnumpy(), (y + 0.5).asnumpy(), 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
Notes
-----
This function differs from the original `numpy.linspace
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html>`_ in
the following aspects:
- `start` and `stop` do not support list, numpy ndarray and mxnet ndarray
- axis could only be 0
- There could be an additional `ctx` argument to specify the device, e.g. the i-th
GPU.
"""
if isinstance(start, (list, _np.ndarray, NDArray)) or \
isinstance(stop, (list, _np.ndarray, NDArray)):
raise NotImplementedError('start and stop only support int')
if axis != 0:
raise NotImplementedError("the function only support axis 0")
if ctx is None:
ctx = current_context()
if retstep:
step = (stop - start) / (num - 1)
return _npi.linspace(start=start, stop=stop, num=num, endpoint=endpoint, ctx=ctx, dtype=dtype), step
else:
return _npi.linspace(start=start, stop=stop, num=num, endpoint=endpoint, ctx=ctx, dtype=dtype)
@set_module('mxnet.ndarray.numpy')
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0, ctx=None): # pylint: disable=too-many-arguments
r"""Return numbers spaced evenly on a log scale.
In linear space, the sequence starts at ``base ** start``
(`base` to the power of `start`) and ends with ``base ** stop``
(see `endpoint` below).
Non-scalar `start` and `stop` are now supported.
Parameters
----------
start : int or float
``base ** start`` is the starting value of the sequence.
stop : int or float
``base ** stop`` is the final value of the sequence, unless `endpoint`
is False. In that case, ``num + 1`` values are spaced over the
interval in log-space, of which all but the last (a sequence of
length `num`) are returned.
num : integer, optional
Number of samples to generate. Default is 50.
endpoint : boolean, optional
If true, `stop` is the last sample. Otherwise, it is not included.
Default is True.
base : float, optional
The base of the log space. The step size between the elements in
``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
Default is 10.0.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
axis : int, optional
The axis in the result to store the samples. Relevant only if start
or stop are array-like. By default (0), the samples will be along a
new axis inserted at the beginning. Now, axis only support axis = 0.
ctx : Context, optional
An optional device context (default is the current default context).
Returns
-------
samples : ndarray
`num` samples, equally spaced on a log scale.
See Also
--------
arange : Similar to linspace, with the step size specified instead of the
number of samples. Note that, when used with a float endpoint, the
endpoint may or may not be included.
linspace : Similar to logspace, but with the samples uniformly distributed
in linear space, instead of log space.
Notes
-----
Logspace is equivalent to the code. Now wo only support axis = 0.
>>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
...
>>> power(base, y).astype(dtype)
...
Examples
--------
>>> np.logspace(2.0, 3.0, num=4)
array([ 100. , 215.44347, 464.15887, 1000. ])
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
array([100. , 177.82794, 316.22775, 562.3413 ])
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
array([4. , 5.0396843, 6.349604 , 8. ])
>>> np.logspace(2.0, 3.0, num=4, base=2.0, dtype=np.int32)
array([4, 5, 6, 8], dtype=int32)
>>> np.logspace(2.0, 3.0, num=4, ctx=npx.gpu(0))
array([ 100. , 215.44347, 464.15887, 1000. ], ctx=gpu(0))
"""
if isinstance(start, (list, tuple, _np.ndarray, NDArray)) or \
isinstance(stop, (list, tuple, _np.ndarray, NDArray)):
raise NotImplementedError('start and stop only support int and float')
if axis != 0:
raise NotImplementedError("the function only support axis 0")
if ctx is None:
ctx = current_context()
return _npi.logspace(start=start, stop=stop, num=num, endpoint=endpoint, base=base, ctx=ctx, dtype=dtype)
@set_module('mxnet.ndarray.numpy')
def expand_dims(a, axis):
"""Expand the shape of an array.
Insert a new axis that will appear at the `axis` position in the expanded
Parameters
----------
a : ndarray
Input array.
axis : int
Position in the expanded axes where the new axis is placed.
Returns
-------
res : ndarray
Output array. The number of dimensions is one greater than that of
the input array.
"""
return _npi.expand_dims(a, axis)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def lcm(x1, x2, out=None, **kwargs):
"""
Returns the lowest common multiple of ``|x1|`` and ``|x2|``
Parameters
----------
x1, x2 : ndarrays or scalar values
The arrays for computing lowest common multiple. If x1.shape != x2.shape,
they must be broadcastable to a common shape (which may be the shape of
one or the other).
out : ndarray or None, optional
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
y : ndarray or scalar
The lowest common multiple of the absolute value of the inputs
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
gcd : The greatest common divisor
Examples
--------
>>> np.lcm(12, 20)
60
>>> np.lcm(np.arange(6, dtype=int), 20)
array([ 0, 20, 20, 60, 20, 20], dtype=int64)
"""
return _ufunc_helper(x1, x2, _npi.lcm, _np.lcm, _npi.lcm_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
def tril(m, k=0):
r"""
Lower triangle of an array.
Return a copy of an array with elements above the `k`-th diagonal zeroed.
Parameters
----------
m : ndarray, shape (M, N)
Input array.
k : int, optional
Diagonal above which to zero elements. `k = 0` (the default) is the
main diagonal, `k < 0` is below it and `k > 0` is above.
Returns
-------
tril : ndarray, shape (M, N)
Lower triangle of `m`, of same shape and data-type as `m`.
See Also
--------
triu : same thing, only for the upper triangle
Examples
--------
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
>>> np.tril(a, -1)
array([[ 0., 0., 0.],
[ 4., 0., 0.],
[ 7., 8., 0.],
[10., 11., 12.]])
"""
return _npi.tril(m, k)
def _unary_func_helper(x, fn_array, fn_scalar, out=None, **kwargs):
"""Helper function for unary operators.
Parameters
----------
x : ndarray or scalar
Input of the unary operator.
fn_array : function
Function to be called if x is of ``ndarray`` type.
fn_scalar : function
Function to be called if x is a Python scalar.
out : ndarray
The buffer ndarray for storing the result of the unary function.
Returns
-------
out : mxnet.numpy.ndarray or scalar
Result array or scalar.
"""
if isinstance(x, numeric_types):
return fn_scalar(x, **kwargs)
elif isinstance(x, NDArray):
return fn_array(x, out=out, **kwargs)
else:
raise TypeError('type {} not supported'.format(str(type(x))))
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def sin(x, out=None, **kwargs):
r"""
Trigonometric sine, element-wise.
Parameters
----------
x : ndarray or scalar
Angle, in radians (:math:`2 \pi` rad equals 360 degrees).
out : ndarray or None
A location into which the result is stored. If provided, it
must have a shape that the inputs broadcast to. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output is the same as that of the input if the input is an ndarray.
Returns
-------
y : ndarray or scalar
The sine of each element of x. This is a scalar if `x` is a scalar.
Notes
----
This function only supports input type of float.
Examples
--------
>>> np.sin(np.pi/2.)
1.0
>>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.)
array([0. , 0.5 , 0.70710677, 0.86602545, 1. ])
"""
return _unary_func_helper(x, _npi.sin, _np.sin, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def cos(x, out=None, **kwargs):
r"""
Cosine, element-wise.
Parameters
----------
x : ndarray or scalar
Angle, in radians (:math:`2 \pi` rad equals 360 degrees).
out : ndarray or None
A location into which the result is stored. If provided, it
must have a shape that the inputs broadcast to. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output is the same as that of the input if the input is an ndarray.
Returns
-------
y : ndarray or scalar
The corresponding cosine values. This is a scalar if x is a scalar.
Notes
----
This function only supports input type of float.
Examples
--------
>>> np.cos(np.array([0, np.pi/2, np.pi]))
array([ 1.000000e+00, -4.371139e-08, -1.000000e+00])
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='f')
>>> out2 = np.cos(np.array([0.1]), out1)
>>> out2 is out1
True
"""
return _unary_func_helper(x, _npi.cos, _np.cos, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def sinh(x, out=None, **kwargs):
"""
Hyperbolic sine, element-wise.
Equivalent to ``1/2 * (np.exp(x) - np.exp(-x))`` or ``-1j * np.sin(1j*x)``.
Parameters
----------
x : ndarray or scalar
Input array or scalar.
out : ndarray or None
A location into which the result is stored. If provided, it
must have a shape that the inputs broadcast to. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output is the same as that of the input if the input is an ndarray.
Returns
-------
y : ndarray or scalar
The corresponding hyperbolic sine values. This is a scalar if `x` is a scalar.
Notes
----
This function only supports input type of float.
Examples
--------
>>> np.sinh(0)
0.0
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='f')
>>> out2 = np.sinh(np.array([0.1]), out1)
>>> out2 is out1
True
"""
return _unary_func_helper(x, _npi.sinh, _np.sinh, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def cosh(x, out=None, **kwargs):
"""
Hyperbolic cosine, element-wise.
Equivalent to ``1/2 * (np.exp(x) + np.exp(-x))`` and ``np.cos(1j*x)``.
Parameters
----------
x : ndarray or scalar
Input array or scalar.
out : ndarray or None
A location into which the result is stored. If provided, it
must have a shape that the inputs broadcast to. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output is the same as that of the input if the input is an ndarray.
Returns
-------
y : ndarray or scalar
The corresponding hyperbolic cosine values. This is a scalar if `x` is a scalar.
Notes
----
This function only supports input type of float.
Examples
--------
>>> np.cosh(0)
1.0
"""
return _unary_func_helper(x, _npi.cosh, _np.cosh, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def tanh(x, out=None, **kwargs):
"""
Compute hyperbolic tangent element-wise.
Equivalent to ``np.sinh(x)/np.cosh(x)``.
Parameters
----------
x : ndarray or scalar.
Input array.
out : ndarray or None
A location into which the result is stored. If provided, it
must have a shape that the inputs fill into. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output and input must be the same.
Returns
-------
y : ndarray or scalar
The corresponding hyperbolic tangent values.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
- input x does not support complex computation (like imaginary number)
>>> np.tanh(np.pi*1j)
TypeError: type <type 'complex'> not supported
Examples
--------
>>> np.tanh(np.array[0, np.pi]))
array([0. , 0.9962721])
>>> np.tanh(np.pi)
0.99627207622075
>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out1 = np.array(1)
>>> out2 = np.tanh(np.array(0.1), out1)
>>> out2 is out1
True
"""
return _unary_func_helper(x, _npi.tanh, _np.tanh, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def log10(x, out=None, **kwargs):
"""
Return the base 10 logarithm of the input array, element-wise.
Parameters
----------
x : ndarray or scalar
Input array or scalar.
out : ndarray or None
A location into which t'absolute', he result is stored. If provided, it
must have a shape that the inputs broadcast to. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output is the same as that of the input if the input is an ndarray.
Returns
-------
y : ndarray or scalar
The logarithm to the base 10 of `x`, element-wise. NaNs are
returned where x is negative. This is a scalar if `x` is a scalar.
Notes
----
This function only supports input type of float.
Examples
--------
>>> np.log10(np.array([1e-15, -3.]))
array([-15., nan])
"""
return _unary_func_helper(x, _npi.log10, _np.log10, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def sqrt(x, out=None, **kwargs):
"""
Return the non-negative square-root of an array, element-wise.
Parameters
----------
x : ndarray or scalar
The values whose square-roots are required.
out : ndarray, or None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
y : ndarray or scalar
An array of the same shape as `x`, containing the positive
square-root of each element in `x`. This is a scalar if `x` is a scalar.
Notes
----
This function only supports input type of float.
Examples
--------
>>> np.sqrt(np.array([1,4,9]))
array([1., 2., 3.])
>>> np.sqrt(np.array([4, -1, _np.inf]))
array([ 2., nan, inf])
"""
return _unary_func_helper(x, _npi.sqrt, _np.sqrt, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def cbrt(x, out=None, **kwargs):
r"""
Return the cube-root of an array, element-wise.
Parameters
----------
x : ndarray
The values whose cube-roots are required.
out : ndarray, optional
A location into which the result is stored. If provided, it must have a shape that the
inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
Returns
----------
y : ndarray
An array of the same shape as x, containing the cube cube-root of each element in x.
If out was provided, y is a reference to it. This is a scalar if x is a scalar.
Examples
----------
>>> np.cbrt([1,8,27])
array([ 1., 2., 3.])
"""
return _unary_func_helper(x, _npi.cbrt, _np.cbrt, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def abs(x, out=None, **kwargs):
r"""
Calculate the absolute value element-wise.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
absolute : ndarray
An ndarray containing the absolute value of
each element in `x`. This is a scalar if `x` is a scalar.
Examples
--------
>>> x = np.array([-1.2, 1.2])
>>> np.abs(x)
array([1.2, 1.2])
"""
return _unary_func_helper(x, _npi.abs, _np.abs, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def absolute(x, out=None, **kwargs):
r"""
Calculate the absolute value element-wise.
np.abs is a shorthand for this function.
Parameters
----------
x : ndarray
Input array.
out : ndarray, optional
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
Returns
----------
absolute : ndarray
An ndarray containing the absolute value of each element in x.
Examples
----------
>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2, 1.2])
"""
return _unary_func_helper(x, _npi.absolute, _np.absolute, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def sign(x, out=None, **kwargs):
r"""
Returns an element-wise indication of the sign of a number.
The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. Only supports real number.
Parameters
----------
x : ndarray or a scalar
Input values.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
y : ndarray
The sign of `x`.
This is a scalar if `x` is a scalar.
Note
-------
- Only supports real number as input elements.
- Input type does not support Python native iterables(list, tuple, ...).
- ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
Examples
--------
>>> a = np.array([-5., 4.5])
>>> np.sign(a)
array([-1., 1.])
>>> # Use scalars as inputs:
>>> np.sign(4.0)
1.0
>>> np.sign(0)
0
>>> # Use ``out`` parameter:
>>> b = np.zeros((2, ))
>>> np.sign(a, out=b)
array([-1., 1.])
>>> b
array([-1., 1.])
"""
return _unary_func_helper(x, _npi.sign, _np.sign, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def exp(x, out=None, **kwargs):
r"""
Calculate the exponential of all elements in the input array.
Parameters
----------
x : ndarray or scalar
Input values.
out : ndarray or None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array, element-wise exponential of `x`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> np.exp(1)
2.718281828459045
>>> x = np.array([-1, 1, -2, 2])
>>> np.exp(x)
array([0.36787945, 2.7182817 , 0.13533528, 7.389056 ])
"""
return _unary_func_helper(x, _npi.exp, _np.exp, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def expm1(x, out=None, **kwargs):
r"""
Calculate `exp(x) - 1` of all elements in the input array.
Parameters
----------
x : ndarray or scalar
Input values.
out : ndarray or None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array, element-wise exponential minus one: `out = exp(x) - 1`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> np.expm1(1)
1.718281828459045
>>> x = np.array([-1, 1, -2, 2])
>>> np.expm1(x)
array([-0.63212056, 1.71828183, -0.86466472, 6.3890561])
"""
return _unary_func_helper(x, _npi.expm1, _np.expm1, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def arcsin(x, out=None, **kwargs):
r"""
Inverse sine, element-wise.
Parameters
----------
x : ndarray or scalar
`y`-coordinate on the unit circle.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape as the input.
If not provided or None, a freshly-allocated array is returned.
Returns
-------
angle : ndarray or scalar
Output array is same shape and type as x. This is a scalar if x is a scalar.
The inverse sine of each element in `x`, in radians and in the
closed interval ``[-pi/2, pi/2]``.
Examples
--------
>>> np.arcsin(1) # pi/2
1.5707963267948966
>>> np.arcsin(-1) # -pi/2
-1.5707963267948966
>>> np.arcsin(0)
0.0
Notes
-----
`arcsin` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that :math:`sin(z) = x`. The convention is to
return the angle `z` whose real part lies in [-pi/2, pi/2].
For real-valued input data types, *arcsin* always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
The inverse sine is also known as `asin` or sin^{-1}.
The output `ndarray` has the same `ctx` as the input `ndarray`.
This function differs from the original `numpy.arcsin
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.arcsin.html>`_ in
the following aspects:
- Only support ndarray or scalar now.
- `where` argument is not supported.
- Complex input is not supported.
References
----------
Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,
10th printing, New York: Dover, 1964, pp. 79ff.
http://www.math.sfu.ca/~cbm/aands/
"""
return _unary_func_helper(x, _npi.arcsin, _np.arcsin, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def arccos(x, out=None, **kwargs):
r"""
Trigonometric inverse cosine, element-wise.
The inverse of cos so that, if y = cos(x), then x = arccos(y).
Parameters
----------
x : ndarray
x-coordinate on the unit circle. For real arguments, the domain is [-1, 1].
out : ndarray, optional
A location into which the result is stored. If provided, it must have a shape that
the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
Returns
----------
angle : ndarray
The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi].
This is a scalar if x is a scalar.
See also
----------
cos, arctan, arcsin
Notes
----------
arccos is a multivalued function: for each x there are infinitely many numbers z such that
cos(z) = x. The convention is to return the angle z whose real part lies in [0, pi].
For real-valued input data types, arccos always returns real output.
For each value that cannot be expressed as a real number or infinity, it yields nan and sets
the invalid floating point error flag.
The inverse cos is also known as acos or cos^-1.
Examples
----------
>>> np.arccos([1, -1])
array([ 0. , 3.14159265])
"""
return _unary_func_helper(x, _npi.arccos, _np.arccos, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def arctan(x, out=None, **kwargs):
r"""
Trigonometric inverse tangent, element-wise.
The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``.
Parameters
----------
x : ndarray or scalar
Input values.
out : ndarray or None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Out has the same shape as `x`. It lies is in
``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``).
This is a scalar if `x` is a scalar.
Notes
-----
`arctan` is a multi-valued function: for each `x` there are infinitely
many numbers `z` such that tan(`z`) = `x`. The convention is to return
the angle `z` whose real part lies in [-pi/2, pi/2].
For real-valued input data types, `arctan` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, we do not have support for them yet.
The inverse tangent is also known as `atan` or tan^{-1}.
Examples
--------
>>> x = np.array([0, 1])
>>> np.arctan(x)
array([0. , 0.7853982])
>>> np.pi/4
0.7853981633974483
"""
return _unary_func_helper(x, _npi.arctan, _np.arctan, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def log(x, out=None, **kwargs):
"""
Natural logarithm, element-wise.
The natural logarithm `log` is the inverse of the exponential function,
so that `log(exp(x)) = x`. The natural logarithm is logarithm in base
`e`.
Parameters
----------
x : ndarray
Input value. Elements must be of real value.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
y : ndarray
The natural logarithm of `x`, element-wise.
This is a scalar if `x` is a scalar.
Notes
-----
Currently only supports data of real values and ``inf`` as input. Returns data of real value, ``inf``, ``-inf`` and
``nan`` according to the input.
This function differs from the original `numpy.log
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html>`_ in
the following aspects:
- Does not support complex number for now
- Input type does not support Python native iterables(list, tuple, ...).
- ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
Examples
--------
>>> a = np.array([1, np.exp(1), np.exp(2), 0], dtype=np.float64)
>>> np.log(a)
array([ 0., 1., 2., -inf], dtype=float64)
>>> # Using default float32 dtype may lead to slightly different behavior:
>>> a = np.array([1, np.exp(1), np.exp(2), 0], dtype=np.float32)
>>> np.log(a)
array([ 0., 0.99999994, 2., -inf])
>>> np.log(1)
0.0
"""
return _unary_func_helper(x, _npi.log, _np.log, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def degrees(x, out=None, **kwargs):
"""
Convert angles from radians to degrees.
Parameters
----------
x : ndarray
Input value. Elements must be of real value.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
y : ndarray
The corresponding degree values; if `out` was supplied this is a
reference to it.
This is a scalar if `x` is a scalar.
Notes
-------
This function differs from the original `numpy.degrees
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.degrees.html>`_ in
the following aspects:
- Input type does not support Python native iterables(list, tuple, ...). Only ndarray is supported.
- ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
Examples
--------
>>> rad = np.arange(12.) * np.pi / 6
>>> np.degrees(rad)
array([ 0., 30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330.])
>>> # Use specified ``out`` ndarray:
>>> out = np.zeros((rad.shape))
>>> np.degrees(rad, out)
array([ 0., 30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330.])
>>> out
array([ 0., 30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330.])
"""
return _unary_func_helper(x, _npi.degrees, _np.degrees, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def rad2deg(x, out=None, **kwargs):
r"""
Convert angles from radians to degrees.
Parameters
----------
x : ndarray or scalar
Angles in degrees.
out : ndarray or None, optional
A location into which the result is stored. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
y : ndarray or scalar
The corresponding angle in radians.
This is a scalar if `x` is a scalar.
Notes
-----
"rad2deg(x)" is "x *180 / pi".
This function differs from the original numpy.arange in the following aspects:
- Only support float32 and float64.
- `out` must be in the same size of input.
Examples
--------
>>> np.rad2deg(np.pi/2)
90.0
"""
return _unary_func_helper(x, _npi.rad2deg, _np.rad2deg, out=out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def rint(x, out=None, **kwargs):
"""
Round elements of the array to the nearest integer.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None
A location into which the result is stored.
If provided, it must have the same shape and type as the input.
If not provided or None, a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array is same shape and type as x. This is a scalar if x is a scalar.
Notes
-----
This function differs from the original `numpy.rint
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.rint.html>`_ in
the following way(s):
- only ndarray or scalar is accpted as valid input, tuple of ndarray is not supported
- broadcasting to `out` of different shape is currently not supported
- when input is plain python numerics, the result will not be stored in the `out` param
Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.rint(a)
array([-2., -2., -0., 0., 1., 2., 2.])
"""
return _unary_func_helper(x, _npi.rint, _np.rint, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def log2(x, out=None, **kwargs):
"""
Base-2 logarithm of x.
Parameters
----------
x : ndarray or scalar
Input values.
out : ndarray or None
A location into which the result is stored.
If provided, it must have the same shape and type as the input.
If not provided or None, a freshly-allocated array is returned.
Returns
-------
y : ndarray
The logarithm base two of `x`, element-wise.
This is a scalar if `x` is a scalar.
Notes
-----
This function differs from the original `numpy.log2
<https://www.google.com/search?q=numpy+log2>`_ in
the following way(s):
- only ndarray or scalar is accpted as valid input, tuple of ndarray is not supported
- broadcasting to `out` of different shape is currently not supported
- when input is plain python numerics, the result will not be stored in the `out` param
Examples
--------
>>> x = np.array([0, 1, 2, 2**4])
>>> np.log2(x)
array([-inf, 0., 1., 4.])
"""
return _unary_func_helper(x, _npi.log2, _np.log2, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def log1p(x, out=None, **kwargs):
"""
Return the natural logarithm of one plus the input array, element-wise.
Calculates ``log(1 + x)``.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None
A location into which the result is stored. If provided, it
must have a shape that the inputs fill into. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output and input must be the same.
Returns
-------
y : ndarray or scalar
Natural logarithm of 1 + x, element-wise. This is a scalar
if x is a scalar.
Notes
-----
For real-valued input, `log1p` is accurate also for `x` so small
that `1 + x == 1` in floating-point accuracy.
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `exp(z) = 1 + x`. The convention is to return
the `z` whose imaginary part lies in `[-pi, pi]`.
For real-valued input data types, `log1p` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
cannot support complex-valued input.
Examples
--------
>>> np.log1p(1e-99)
1e-99
>>> a = np.array([3, 4, 5])
>>> np.log1p(a)
array([1.3862944, 1.609438 , 1.7917595])
"""
return _unary_func_helper(x, _npi.log1p, _np.log1p, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def radians(x, out=None, **kwargs):
"""
Convert angles from degrees to radians.
Parameters
----------
x : ndarray or scalar
Input array in degrees.
out : ndarray or None
A location into which the result is stored.
If provided, it must have the same shape and type as the input.
If not provided or None, a freshly-allocated array is returned.
Returns
-------
y : ndarray
The corresponding radian values. This is a scalar if x is a scalar.
Notes
-----
This function differs from the original `numpy.radians
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.radians.html>`_ in
the following way(s):
- only ndarray or scalar is accpted as valid input, tuple of ndarray is not supported
- broadcasting to `out` of different shape is currently not supported
- when input is plain python numerics, the result will not be stored in the `out` param
Examples
--------
>>> deg = np.arange(12.) * 30.
>>> np.radians(deg)
array([0. , 0.5235988, 1.0471976, 1.5707964, 2.0943952, 2.6179938,
3.1415927, 3.6651914, 4.1887903, 4.712389 , 5.2359877, 5.7595863],
dtype=float32)
"""
return _unary_func_helper(x, _npi.radians, _np.radians, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def deg2rad(x, out=None, **kwargs):
r"""
Convert angles from degrees to radians.
Parameters
----------
x : ndarray or scalar
Angles in degrees.
out : ndarray or None, optional
A location into which the result is stored. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
y : ndarray or scalar
The corresponding angle in radians.
This is a scalar if `x` is a scalar.
Notes
-----
"deg2rad(x)" is "x * pi / 180".
This function differs from the original numpy.arange in the following aspects:
- Only support float32 and float64.
- `out` must be in the same size of input.
Examples
--------
>>> np.deg2rad(180)
3.1415927
"""
return _unary_func_helper(x, _npi.deg2rad, _np.deg2rad, out=out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def reciprocal(x, out=None, **kwargs):
r"""
Return the reciprocal of the argument, element-wise.
Calculates ``1/x``.
Parameters
----------
x : ndarray or scalar
The values whose reciprocals are required.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape as the input.
If not provided or None, a freshly-allocated array is returned.
Returns
-------
y : ndarray or scalar
Output array is same shape and type as x. This is a scalar if x is a scalar.
Examples
--------
>>> np.reciprocal(2.)
0.5
>>> x = np.array([1, 2., 3.33])
>>> np.reciprocal(x)
array([1. , 0.5 , 0.3003003])
Notes
-----
.. note::
This function is not designed to work with integers.
For integer arguments with absolute value larger than 1 the result is
always zero because of the way Python handles integer division. For
integer zero the result is an overflow.
The output `ndarray` has the same `ctx` as the input `ndarray`.
This function differs from the original `numpy.reciprocal
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.reciprocal.html>`_ in
the following aspects:
- Only support ndarray and scalar now.
- `where` argument is not supported.
"""
return _unary_func_helper(x, _npi.reciprocal, _np.reciprocal, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def square(x, out=None, **kwargs):
r"""
Return the element-wise square of the input.
Parameters
----------
x : ndarray or scalar
The values whose squares are required.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape as the input.
If not provided or None, a freshly-allocated array is returned.
Returns
-------
y : ndarray or scalar
Output array is same shape and type as x. This is a scalar if x is a scalar.
Examples
--------
>>> np.square(2.)
4.0
>>> x = np.array([1, 2., -1])
>>> np.square(x)
array([1., 4., 1.])
Notes
-----
The output `ndarray` has the same `ctx` as the input `ndarray`.
This function differs from the original `numpy.square
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.square.html>`_ in
the following aspects:
- Only support ndarray and scalar now.
- `where` argument is not supported.
- Complex input is not supported.
"""
return _unary_func_helper(x, _npi.square, _np.square, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def negative(x, out=None, **kwargs):
r"""
Numerical negative, element-wise.
Parameters:
------------
x : ndarray or scalar
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored.
Returns:
---------
y : ndarray or scalar
Returned array or scalar: y = -x. This is a scalar if x is a scalar.
Examples:
---------
>>> np.negative(1)
-1
"""
return _unary_func_helper(x, _npi.negative, _np.negative, out=out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def fix(x, out=None, **kwargs):
r"""
Round an array of floats element-wise to nearest integer towards zero.
The rounded values are returned as floats.
Parameters:
----------
x : ndarray
An array of floats to be rounded
out : ndarray, optional
Output array
Returns:
-------
y : ndarray of floats
Examples
---------
>>> np.fix(3.14)
3
"""
return _unary_func_helper(x, _npi.fix, _np.fix, out=out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def tan(x, out=None, **kwargs):
r"""
Compute tangent element-wise.
Equivalent to np.sin(x)/np.cos(x) element-wise.
Parameters:
----------
x : ndarray
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided,
it must have a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a keyword argument)
must have length equal to the number of outputs.
where : ndarray, optional
Values of True indicate to calculate the ufunc at that position,
values of False indicate to leave the value in the output alone.
Returns:
-------
y : ndarray
The corresponding tangent values. This is a scalar if x is a scalar.
Examples:
---------
>>> np.tan(0.5)
0.5463024898437905
"""
return _unary_func_helper(x, _npi.tan, _np.tan, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def ceil(x, out=None, **kwargs):
r"""
Return the ceiling of the input, element-wise.
The ceil of the ndarray `x` is the smallest integer `i`, such that
`i >= x`. It is often denoted as :math:`\lceil x \rceil`.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None
A location into which the result is stored. If provided, it
must have a same shape that the inputs fill into. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output and input must be the same.
Returns
-------
y : ndarray or scalar
The ceiling of each element in `x`, with `float` dtype.
This is a scalar if `x` is a scalar.
Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.ceil(a)
array([-1., -1., -0., 1., 2., 2., 2.])
>>> #if you use parameter out, x and out must be ndarray.
>>> a = np.array(1)
>>> np.ceil(np.array(3.5), a)
array(4.)
>>> a
array(4.)
"""
return _unary_func_helper(x, _npi.ceil, _np.ceil, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def floor(x, out=None, **kwargs):
r"""
Return the floor of the input, element-wise.
The floor of the ndarray `x` is the largest integer `i`, such that
`i <= x`. It is often denoted as :math:`\lfloor x \rfloor`.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None
A location into which the result is stored. If provided, it
must have a same shape that the inputs fill into. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output and input must be the same.
Returns
-------
y : ndarray or scalar
The floor of each element in `x`, with `float` dtype.
This is a scalar if `x` is a scalar.
Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.floor(a)
array([-2., -2., -1., 0., 1., 1., 2.])
>>> #if you use parameter out, x and out must be ndarray.
>>> a = np.array(1)
>>> np.floor(np.array(3.5), a)
array(3.)
>>> a
array(3.)
"""
return _unary_func_helper(x, _npi.floor, _np.floor, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def trunc(x, out=None, **kwargs):
r"""
Return the truncated value of the input, element-wise.
The truncated value of the scalar `x` is the nearest integer `i` which
is closer to zero than `x` is. In short, the fractional part of the
signed number `x` is discarded.
Parameters
----------
x : ndarray or scalar
Input data.
out : ndarray or None, optional
A location into which the result is stored.
Returns
-------
y : ndarray or scalar
The truncated value of each element in `x`.
This is a scalar if `x` is a scalar.
Notes
-----
This function differs from the original numpy.trunc in the following aspects:
- Do not support `where`, a parameter in numpy which indicates where to calculate.
- Cannot cast type automatically. Dtype of `out` must be same as the expected one.
- Cannot broadcast automatically. Shape of `out` must be same as the expected one.
- If `x` is plain python numeric, the result won't be stored in out.
Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0., 0., 1., 1., 2.])
"""
return _unary_func_helper(x, _npi.trunc, _np.trunc, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def logical_not(x, out=None, **kwargs):
r"""
Compute the truth value of NOT x element-wise.
Parameters
----------
x : ndarray or scalar
Logical NOT is applied to the elements of `x`.
out : ndarray or None, optional
A location into which the result is stored.
Returns
-------
y : bool or ndarray of bool
Boolean result with the same shape as `x` of the NOT operation
on elements of `x`.
This is a scalar if `x` is a scalar.
Notes
-----
This function differs from the original numpy.logical_not in the following aspects:
- Do not support `where`, a parameter in numpy which indicates where to calculate.
- Cannot cast type automatically. Dtype of `out` must be same as the expected one.
- Cannot broadcast automatically. Shape of `out` must be same as the expected one.
- If `x` is plain python numeric, the result won't be stored in out.
Examples
--------
>>> x= np.array([True, False, 0, 1])
>>> np.logical_not(x)
array([False, True, True, False])
>>> x = np.arange(5)
>>> np.logical_not(x<3)
array([False, False, False, True, True])
"""
return _unary_func_helper(x, _npi.logical_not, _np.logical_not, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def arcsinh(x, out=None, **kwargs):
r"""
Inverse hyperbolic sine, element-wise.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None, optional
A location into which the result is stored.
Returns
-------
arcsinh : ndarray
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
Notes
-----
`arcsinh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `sinh(z) = x`.
For real-valued input data types, `arcsinh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
This function differs from the original numpy.arcsinh in the following aspects:
- Do not support `where`, a parameter in numpy which indicates where to calculate.
- Do not support complex-valued input.
- Cannot cast type automatically. DType of `out` must be same as the expected one.
- Cannot broadcast automatically. Shape of `out` must be same as the expected one.
- If `x` is plain python numeric, the result won't be stored in out.
Examples
--------
>>> a = np.array([3.2, 5.0])
>>> np.arcsinh(a)
array([1.8309381, 2.2924316])
>>> np.arcsinh(1)
0.0
"""
return _unary_func_helper(x, _npi.arcsinh, _np.arcsinh, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def arccosh(x, out=None, **kwargs):
r"""
Inverse hyperbolic cosine, element-wise.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None, optional
A location into which the result is stored.
Returns
-------
arccosh : ndarray
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
Notes
-----
`arccosh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `cosh(z) = x`.
For real-valued input data types, `arccosh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
This function differs from the original numpy.arccosh in the following aspects:
- Do not support `where`, a parameter in numpy which indicates where to calculate.
- Do not support complex-valued input.
- Cannot cast type automatically. Dtype of `out` must be same as the expected one.
- Cannot broadcast automatically. Shape of `out` must be same as the expected one.
- If `x` is plain python numeric, the result won't be stored in out.
Examples
--------
>>> a = np.array([3.2, 5.0])
>>> np.arccosh(a)
array([1.8309381, 2.2924316])
>>> np.arccosh(1)
0.0
"""
return _unary_func_helper(x, _npi.arccosh, _np.arccosh, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
@wrap_np_unary_func
def arctanh(x, out=None, **kwargs):
r"""
Inverse hyperbolic tangent, element-wise.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None, optional
A location into which the result is stored.
Returns
-------
arctanh : ndarray
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
Notes
-----
`arctanh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `tanh(z) = x`.
For real-valued input data types, `arctanh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
This function differs from the original numpy.arctanh in the following aspects:
- Do not support `where`, a parameter in numpy which indicates where to calculate.
- Do not support complex-valued input.
- Cannot cast type automatically. Dtype of `out` must be same as the expected one.
- Cannot broadcast automatically. Shape of `out` must be same as the expected one.
- If `x` is plain python numeric, the result won't be stored in out.
Examples
--------
>>> a = np.array([0.0, -0.5])
>>> np.arctanh(a)
array([0., -0.54930615])
>>> np.arctanh(0.0)
0.0
"""
return _unary_func_helper(x, _npi.arctanh, _np.arctanh, out=out, **kwargs)
@set_module('mxnet.ndarray.numpy')
def tile(A, reps):
r"""
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
or shape (1, 1, 3) for 3-D replication. If this is not the desired
behavior, promote `A` to d-dimensions manually before calling this
function.
If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
(1, 1, 2, 2).
Parameters
----------
A : ndarray or scalar
An input array or a scalar to repeat.
reps : a single integer or tuple of integers
The number of repetitions of `A` along each axis.
Returns
-------
c : ndarray
The tiled output array.
Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0., 1., 2., 0., 1., 2.])
>>> np.tile(a, (2, 2))
array([[0., 1., 2., 0., 1., 2.],
[0., 1., 2., 0., 1., 2.]])
>>> np.tile(a, (2, 1, 2))
array([[[0., 1., 2., 0., 1., 2.]],
[[0., 1., 2., 0., 1., 2.]]])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1., 2., 1., 2.],
[3., 4., 3., 4.]])
>>> np.(b, (2, 1))
array([[1., 2.],
[3., 4.],
[1., 2.],
[3., 4.]])
>>> c = np.array([1,2,3,4])
>>> np.tile(c,(4,1))
array([[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.]])
Scalar as input:
>>> np.tile(2, 3)
array([2, 2, 2]) # repeating integer `2`
"""
return _unary_func_helper(A, _npi.tile, _np.tile, reps=reps)
# pylint: disable=redefined-outer-name
@set_module('mxnet.ndarray.numpy')
def split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1-D python tuple, list or set.
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split is not possible,
an error is raised.
If `indices_or_sections` is a 1-D array of sorted integers, the entries
indicate where along `axis` the array is split. For example,
``[2, 3]`` would, for ``axis=0``, result in
- ary[:2]
- ary[2:3]
- ary[3:]
If an index exceeds the dimension of the array along `axis`,
an empty sub-array is returned correspondingly.
axis : int, optional
The axis along which to split, default is 0.
Returns
-------
sub-arrays : list of ndarrays
A list of sub-arrays.
Raises
------
ValueError
If `indices_or_sections` is given as an integer, but
a split does not result in equal division.
"""
axis_size = ary.shape[axis]
if isinstance(indices_or_sections, integer_types):
sections = indices_or_sections
if axis_size % sections:
raise ValueError('array split does not result in an equal division')
section_size = int(axis_size / sections)
indices = [i * section_size for i in range(sections)]
elif isinstance(indices_or_sections, (list, set, tuple)):
indices = [0] + list(indices_or_sections)
else:
raise ValueError('indices_or_sections must be either int, or tuple / list / set of ints')
ret = _npi.split(ary, indices, axis, False)
assert isinstance(ret, list), 'Output of split should be list,' \
' got a return type {}'.format(type(ret))
return ret
# pylint: enable=redefined-outer-name
# pylint: disable=redefined-outer-name
@set_module('mxnet.ndarray.numpy')
def hsplit(ary, indices_or_sections):
"""Split an array into multiple sub-arrays horizontally (column-wise).
This is equivalent to ``split`` with ``axis=0`` if ``ary`` has one
dimension, and otherwise that with ``axis=1``.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int, list of ints or tuple of ints.
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split is not possible,
an error is raised.
If `indices_or_sections` is a list of sorted integers, the entries
indicate where along `axis` the array is split.
If an index exceeds the dimension of the array along `axis`,
it will raises errors. so index must less than or euqal to
the dimension of the array along axis.
Returns
-------
sub-arrays : list of ndarrays
A list of sub-arrays.
Notes
------
- If `indices_or_sections` is given as an integer, but a split
does not result in equal division.It will raises ValueErrors.
- If indices_or_sections is an integer, and the number is 1, it will
raises an error. Because single output from split is not supported yet...
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[10., 11.],
[14., 15.]])]
>>> np.hsplit(x, [3, 6])
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
[12., 13., 14.]]),
array([[ 3.],
[ 7.],
[11.],
[15.]]),
array([], shape=(4, 0), dtype=float32)]
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.hsplit(x, 2)
[array([[[ 0., 1.]],
[[ 4., 5.]]]),
array([[[ 2., 3.]],
[[ 6., 7.]]])]
If ``ary`` has one dimension, 'axis' = 0.
>>> x = np.arange(4)
array([0., 1., 2., 3.])
>>> np.hsplit(x, 2)
[array([0., 1.]), array([2., 3.])]
If you want to produce an empty sub-array, you can see an example.
>>> np.hsplit(x, [2, 2])
[array([0., 1.]), array([], dtype=float32), array([2., 3.])]
"""
axis = 1
if len(ary.shape) == 1:
axis = 0
axis_size = ary.shape[axis]
if isinstance(indices_or_sections, integer_types):
sections = indices_or_sections
if axis_size % sections:
raise ValueError('array hsplit does not result in an equal division')
section_size = int(axis_size / sections)
indices = [i * section_size for i in range(sections)]
elif isinstance(indices_or_sections, (list, set, tuple)):
indices = [0] + list(indices_or_sections)
else:
raise ValueError('indices_or_sections must either int or tuple of ints')
ret = _npi.hsplit(ary, indices, axis, False)
return ret
# pylint: enable=redefined-outer-name
@set_module('mxnet.ndarray.numpy')
def vsplit(ary, indices_or_sections):
r"""
vsplit(ary, indices_or_sections)
Split an array into multiple sub-arrays vertically (row-wise).
``vsplit`` is equivalent to ``split`` with `axis=0` (default): the array is always split
along the first axis regardless of the array dimension.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1 - D Python tuple, list or set.
If `indices_or_sections` is an integer, N, the array will be divided into N equal arrays
along axis 0. If such a split is not possible, an error is raised.
If `indices_or_sections` is a 1-D array of sorted integers, the entries indicate where
along axis 0 the array is split. For example, ``[2, 3]`` would result in
- ary[:2]
- ary[2:3]
- ary[3:]
If an index exceeds the dimension of the array along axis 0, an error will be thrown.
Returns
-------
sub-arrays : list of ndarrays
A list of sub-arrays.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Notes
-------
This function differs from the original `numpy.degrees
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.degrees.html>`_ in
the following aspects:
- Currently parameter ``indices_or_sections`` does not support ndarray, but supports scalar,
tuple and list.
- In ``indices_or_sections``, if an index exceeds the dimension of the array along axis 0,
an error will be thrown.
Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.vsplit(x, 2)
[array([[0., 1., 2., 3.],
[4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.],
[12., 13., 14., 15.]])]
With a higher dimensional array the split is still along the first axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.vsplit(x, 2)
[array([[[0., 1.],
[2., 3.]]]), array([[[4., 5.],
[6., 7.]]])]
"""
return split(ary, indices_or_sections, 0)
@set_module('mxnet.ndarray.numpy')
def concatenate(seq, axis=0, out=None):
"""
Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of ndarray
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
Returns
-------
res : ndarray
The concatenated array.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1., 2.],
[3., 4.],
[5., 6.]])
>>> np.concatenate((a, b), axis=None)
array([1., 2., 3., 4., 5., 6.])
>>> np.concatenate((a, b.T), axis=1)
array([[1., 2., 5.],
[3., 4., 6.]])
"""
return _npi.concatenate(*seq, axis=axis, out=out)
@set_module('mxnet.ndarray.numpy')
def append(arr, values, axis=None): # pylint: disable=redefined-outer-name
"""
Append values to the end of an array.
Parameters
----------
arr : ndarray
Values are appended to a copy of this array.
values : ndarray
These values are appended to a copy of `arr`. It must be of the
correct shape (the same shape as `arr`, excluding `axis`). If
`axis` is not specified, `values` can be any shape and will be
flattened before use.
axis : int, optional
The axis along which `values` are appended. If `axis` is not
given, both `arr` and `values` are flattened before use.
Returns
-------
append : ndarray
A copy of `arr` with `values` appended to `axis`. Note that
`append` does not occur in-place: a new array is allocated and
filled. If `axis` is None, `out` is a flattened array.
Examples
--------
>>> np.append(np.array([1, 2, 3]), np.array([[4, 5, 6],[7, 8, 9]]))
array([1., 2., 3., 4., 5., 6., 7., 8., 9.])
When `axis` is specified, `values` must have the correct shape.
>>> np.append(np.array([[1, 2, 3], [4, 5, 6]]), np.array([[7, 8, 9]]), axis=0)
array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
"""
return _npi.concatenate(arr, values, axis=axis, out=None)
@set_module('mxnet.ndarray.numpy')
def stack(arrays, axis=0, out=None):
"""Join a sequence of arrays along a new axis.
The axis parameter specifies the index of the new axis in the dimensions of the result.
For example, if `axis=0` it will be the first dimension and if `axis=-1` it will be the last dimension.
Parameters
----------
arrays : sequence of ndarray
Each array must have the same shape.
axis : int, optional
The axis in the result array along which the input arrays are stacked.
out : ndarray, optional
If provided, the destination to place the result. The shape must be correct,
matching that of what stack would have returned if no out argument were specified.
Returns
-------
stacked : ndarray
The stacked array has one more dimension than the input arrays."""
def get_list(arrays):
if not hasattr(arrays, '__getitem__') and hasattr(arrays, '__iter__'):
raise ValueError("expected iterable for arrays but got {}".format(type(arrays)))
return [arr for arr in arrays]
arrays = get_list(arrays)
return _npi.stack(*arrays, axis=axis, out=out)
@set_module('mxnet.ndarray.numpy')
def vstack(arrays, out=None):
r"""Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays
of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
`vsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate` and `stack`
provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the first axis.
1-D arrays must have the same length.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 2-D.
Examples
--------
>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a, b))
array([[1., 2., 3.],
[2., 3., 4.]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> np.vstack((a, b))
array([[1.],
[2.],
[3.],
[2.],
[3.],
[4.]])
"""
def get_list(arrays):
if not hasattr(arrays, '__getitem__') and hasattr(arrays, '__iter__'):
raise ValueError("expected iterable for arrays but got {}".format(type(arrays)))
return [arr for arr in arrays]
arrays = get_list(arrays)
return _npi.vstack(*arrays)
@set_module('mxnet.ndarray.numpy')
def column_stack(tup):
"""
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Returns
--------
stacked : 2-D array
The array formed by stacking the given arrays.
See Also
--------
stack, hstack, vstack, concatenate
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1., 2.],
[2., 3.],
[3., 4.]])
"""
return _npi.column_stack(*tup)
@set_module('mxnet.ndarray.numpy')
def dstack(arrays):
"""
Stack arrays in sequence depth wise (along third axis).
This is equivalent to concatenation along the third axis after 2-D arrays
of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
`(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
`dsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of arrays
The arrays must have the same shape along all but the third axis.
1-D or 2-D arrays must have the same shape.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 3-D.
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
"""
return _npi.dstack(*arrays)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def maximum(x1, x2, out=None, **kwargs):
"""
Returns element-wise maximum of the input arrays with broadcasting.
Parameters
----------
x1, x2 : scalar or mxnet.numpy.ndarray
The arrays holding the elements to be compared. They must have the same shape,
or shapes that can be broadcast to a single shape.
Returns
-------
out : mxnet.numpy.ndarray or scalar
The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars."""
return _ufunc_helper(x1, x2, _npi.maximum, _np.maximum, _npi.maximum_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def minimum(x1, x2, out=None, **kwargs):
"""
Returns element-wise minimum of the input arrays with broadcasting.
Parameters
----------
x1, x2 : scalar or mxnet.numpy.ndarray
The arrays holding the elements to be compared. They must have the same shape,
or shapes that can be broadcast to a single shape.
Returns
-------
out : mxnet.numpy.ndarray or scalar
The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars."""
return _ufunc_helper(x1, x2, _npi.minimum, _np.minimum, _npi.minimum_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
def swapaxes(a, axis1, axis2):
"""Interchange two axes of an array.
Parameters
----------
a : ndarray
Input array.
axis1 : int
First axis.
axis2 : int
Second axis.
Returns
-------
a_swapped : ndarray
Swapped array. This is always a copy of the input array.
"""
return _npi.swapaxes(a, dim1=axis1, dim2=axis2)
@set_module('mxnet.ndarray.numpy')
def clip(a, a_min, a_max, out=None):
"""clip(a, a_min, a_max, out=None)
Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to
the interval edges. For example, if an interval of ``[0, 1]``
is specified, values smaller than 0 become 0, and values larger
than 1 become 1.
Parameters
----------
a : ndarray
Array containing elements to clip.
a_min : scalar or `None`
Minimum value. If `None`, clipping is not performed on lower
interval edge. Not more than one of `a_min` and `a_max` may be
`None`.
a_max : scalar or `None`
Maximum value. If `None`, clipping is not performed on upper
interval edge. Not more than one of `a_min` and `a_max` may be
`None`.
out : ndarray, optional
The results will be placed in this array. It may be the input
array for in-place clipping. `out` must be of the right shape
to hold the output. Its type is preserved.
Returns
-------
clipped_array : ndarray
An array with the elements of `a`, but where values
< `a_min` are replaced with `a_min`, and those > `a_max`
with `a_max`.
Notes
-----
ndarray `a_min` and `a_max` are not supported.
Examples
--------
>>> a = np.arange(10)
>>> np.clip(a, 1, 8)
array([1., 1., 2., 3., 4., 5., 6., 7., 8., 8.], dtype=float32)
>>> a
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)
>>> np.clip(a, 3, 6, out=a)
array([3., 3., 3., 3., 4., 5., 6., 6., 6., 6.], dtype=float32)
"""
if a_min is None and a_max is None:
raise ValueError('array_clip: must set either max or min')
if a_min is None:
a_min = float('-inf')
if a_max is None:
a_max = float('inf')
return _npi.clip(a, a_min, a_max, out=out)
@set_module('mxnet.ndarray.numpy')
def argmax(a, axis=None, out=None):
r"""
Returns the indices of the maximum values along an axis.
Parameters
----------
a : ndarray
Input array. Only support ndarrays of dtype `float16`, `float32`, and `float64`.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
Returns
-------
index_array : ndarray of indices whose dtype is same as the input ndarray.
Array of indices into the array. It has the same shape as `a.shape`
with the dimension along `axis` removed.
Notes
-----
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.
This function differs from the original `numpy.argmax
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html>`_ in
the following aspects:
- Input type does not support Python native iterables(list, tuple, ...).
- Output has dtype that is same as the input ndarray.
- ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
Examples
--------
>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10., 11., 12.],
[13., 14., 15.]])
>>> np.argmax(a)
array(5.)
>>> np.argmax(a, axis=0)
array([1., 1., 1.])
>>> np.argmax(a, axis=1)
array([2., 2.])
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0., 5., 2., 3., 4., 5.])
>>> np.argmax(b) # Only the first occurrence is returned.
array(1.)
Specify ``out`` ndarray:
>>> a = np.arange(6).reshape(2,3) + 10
>>> b = np.zeros((2,))
>>> np.argmax(a, axis=1, out=b)
array([2., 2.])
>>> b
array([2., 2.])
"""
return _npi.argmax(a, axis=axis, keepdims=False, out=out)
@set_module('mxnet.ndarray.numpy')
def argmin(a, axis=None, out=None):
r"""
Returns the indices of the maximum values along an axis.
Parameters
----------
a : ndarray
Input array. Only support ndarrays of dtype `float16`, `float32`, and `float64`.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
out : ndarray or None, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype.
Returns
-------
index_array : ndarray of indices whose dtype is same as the input ndarray.
Array of indices into the array. It has the same shape as `a.shape`
with the dimension along `axis` removed.
Notes
-----
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.
This function differs from the original `numpy.argmax
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html>`_ in
the following aspects:
- Input type does not support Python native iterables(list, tuple, ...).
- Output has dtype that is same as the input ndarray.
- ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
Examples
--------
>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10., 11., 12.],
[13., 14., 15.]])
>>> np.argmin(a)
array(0.)
>>> np.argmin(a, axis=0)
array([0., 0., 0.])
>>> np.argmin(a, axis=1)
array([0., 0.])
>>> b = np.arange(6)
>>> b[2] = 0
>>> b
array([0., 1., 0., 3., 4., 5.])
>>> np.argmax(b) # Only the first occurrence is returned.
array(0.)
Specify ``out`` ndarray:
>>> a = np.arange(6).reshape(2,3) + 10
>>> b = np.zeros((2,))
>>> np.argmin(a, axis=1, out=b)
array([0., 0.])
>>> b
array([0., 0.])
"""
return _npi.argmin(a, axis=axis, keepdims=False, out=out)
@set_module('mxnet.ndarray.numpy')
def average(a, axis=None, weights=None, returned=False, out=None):
"""
Compute the weighted average along the specified axis.
Parameters
--------
a : ndarray
Array containing data to be averaged.
axis : None or int or tuple of ints, optional
Axis or axes along which to average a.
The default, axis=None, will average over
all of the elements of the input array.
If axis is negative it counts from the last to the first axis.
New in version 1.7.0.
If axis is a tuple of ints, averaging is
performed on all of the axes specified in the tuple
instead of a single axis or all the axes as before.
weights : ndarray, optional
An array of weights associated with the values in a, must be the same dtype with a.
Each value in a contributes to the average according to its associated weight.
The weights array can either be 1-D (in which case its length must be
the size of a along the given axis) or of the same shape as a.
If weights=None, then all data in a are assumed to have a weight equal to one.
The 1-D calculation is: avg = sum(a * weights) / sum(weights)
The only constraint on weights is that sum(weights) must not be 0.
returned : bool, optional
Default is False.
If True, the tuple (average, sum_of_weights) is returned,
otherwise only the average is returned.
If weights=None, sum_of_weights is equivalent to
the number of elements over which the average is taken.
out : ndarray, optional
If provided, the calculation is done into this array.
Returns
--------
retval, [sum_of_weights] : ndarray
Return the average along the specified axis.
When returned is True, return a tuple with the average as the first element
and the sum of the weights as the second element. sum_of_weights is of the same type as retval.
If a is integral, the result dtype will be float32, otherwise it will be the same as dtype of a.
Raises
--------
MXNetError
- When all weights along axis sum to zero.
- When the length of 1D weights is not the same as the shape of a along axis.
- When given 1D weights, the axis is not specified or is not int.
- When the shape of weights and a differ, but weights are not 1D.
See also
--------
mean
Notes
--------
This function differs from the original `numpy.average`
<https://numpy.org/devdocs/reference/generated/numpy.average.html>`_ in
the following way(s):
- Does not guarantee the same behavior with numpy when given float16 dtype and overflow happens
- Does not support complex dtype
- The dtypes of a and weights must be the same
- Integral a results in float32 returned dtype, not float64
Examples
--------
>>> data = np.arange(1, 5)
>>> data
array([1., 2., 3., 4.])
>>> np.average(data)
array(2.5)
>>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1))
array(4.)
>>> data = np.arange(6).reshape((3,2))
>>> data
array([[0., 1.],
[2., 3.],
[4., 5.]])
>>> weights = np.array([0.25, 0.75])
array([0.25, 0.75])
>>> np.average(data, axis=1, weights=weights)
array([0.75, 2.75, 4.75])
"""
if weights is None:
return _npi.average(a, axis=axis, weights=None, returned=returned, weighted=False, out=out)
else:
return _npi.average(a, axis=axis, weights=weights, returned=returned, out=out)
@set_module('mxnet.ndarray.numpy')
def mean(a, axis=None, dtype=None, out=None, keepdims=False): # pylint: disable=arguments-differ
"""
mean(a, axis=None, dtype=None, out=None, keepdims=None)
Compute the arithmetic mean along the specified axis.
Returns the average of the array elements.
The average is taken over the flattened array by default, otherwise over the specified axis.
Parameters
----------
a : ndarray
ndarray containing numbers whose mean is desired.
axis : None or int or tuple of ints, optional
Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.
If this is a tuple of ints, a mean is performed over multiple axes,
instead of a single axis or all the axes as before.
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default is float32;
for floating point inputs, it is the same as the input dtype.
out : ndarray, optional
Alternate output array in which to place the result. The default is None; if provided,
it must have the same shape and type as the expected output
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in the result
as dimensions with size one. With this option, the result will broadcast correctly
against the input array.
If the default value is passed, then keepdims will not be passed through to the mean
method of sub-classes of ndarray, however any non-default value will be. If the sub-class
method does not implement keepdims any exceptions will be raised.
Returns
-------
m : ndarray, see dtype parameter above
If out=None, returns a new array containing the mean values,
otherwise a reference to the output array is returned.
Notes
-----
This function differs from the original `numpy.mean
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html>`_ in
the following way(s):
- only ndarray is accepted as valid input, python iterables or scalar is not supported
- default data type for integer input is float32
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
array(2.5)
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0,:] = 1.0
>>> a[1,:] = 0.1
>>> np.mean(a)
array(0.55)
>>> np.mean(a, dtype=np.float64)
array(0.55)
"""
return _npi.mean(a, axis=axis, dtype=dtype, keepdims=keepdims, out=out)
@set_module('mxnet.ndarray.numpy')
def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): # pylint: disable=too-many-arguments
"""
Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution,
of the array elements. The standard deviation is computed for the
flattened array by default, otherwise over the specified axis.
Parameters
----------
a : ndarray
Calculate the standard deviation of these values.
axis : None or int or tuple of ints, optional
Axis or axes along which the standard deviation is computed. The
default is to compute the standard deviation of the flattened array.
.. versionadded:: 1.7.0
If this is a tuple of ints, a standard deviation is performed over
multiple axes, instead of a single axis or all the axes as before.
dtype : dtype, optional
Type to use in computing the standard deviation. For arrays of
integer type the default is float64, for arrays of float types it is
the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type (of the calculated
values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
By default `ddof` is zero.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `std` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
Returns
-------
standard_deviation : ndarray, see dtype parameter above.
If `out` is None, return a new array containing the standard deviation,
otherwise return a reference to the output array.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> np.std(a)
1.1180339887498949 # may vary
>>> np.std(a, axis=0)
array([1., 1.])
>>> np.std(a, axis=1)
array([0.5, 0.5])
In single precision, std() can be inaccurate:
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.std(a)
array(0.45)
>>> np.std(a, dtype=np.float64)
array(0.45, dtype=float64)
"""
return _npi.std(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims, out=out)
@set_module('mxnet.ndarray.numpy')
def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): # pylint: disable=too-many-arguments
"""
Compute the variance along the specified axis.
Returns the variance of the array elements, a measure of the spread of a
distribution. The variance is computed for the flattened array by
default, otherwise over the specified axis.
Parameters
----------
a : ndarray
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which the variance is computed. The default is to
compute the variance of the flattened array.
.. versionadded:: 1.7.0
If this is a tuple of ints, a variance is performed over multiple axes,
instead of a single axis or all the axes as before.
dtype : data-type, optional
Type to use in computing the variance. For arrays of integer type
the default is `float32`; for arrays of float types it is the same as
the array type.
out : ndarray, optional
Alternate output array in which to place the result. It must have
the same shape as the expected output, but the type is cast if
necessary.
ddof : int, optional
"Delta Degrees of Freedom": the divisor used in the calculation is
``N - ddof``, where ``N`` represents the number of elements. By
default `ddof` is zero.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `var` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
Returns
-------
variance : ndarray, see dtype parameter above
If ``out=None``, returns a new array containing the variance;
otherwise, a reference to the output array is returned.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> np.var(a)
array(1.25)
>>> np.var(a, axis=0)
array([1., 1.])
>>> np.var(a, axis=1)
array([0.25, 0.25])
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.var(a)
array(0.2025)
>>> np.var(a, dtype=np.float64)
array(0.2025, dtype=float64)
>>> ((1-0.55)**2 + (0.1-0.55)**2)/2
0.2025
"""
return _npi.var(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims, out=out)
# pylint: disable=redefined-outer-name
@set_module('mxnet.ndarray.numpy')
def indices(dimensions, dtype=_np.int32, ctx=None):
"""Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0,1,...
varying only along the corresponding axis.
Parameters
----------
dimensions : sequence of ints
The shape of the grid.
dtype : data-type, optional
The desired data-type for the array. Default is `float32`.
ctx : device context, optional
Device context on which the memory is allocated. Default is
`mxnet.context.current_context()`.
Returns
-------
grid : ndarray
The array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
Notes
-----
The output shape is obtained by prepending the number of dimensions
in front of the tuple of dimensions, i.e. if `dimensions` is a tuple
``(r0, ..., rN-1)`` of length ``N``, the output shape is
``(N,r0,...,rN-1)``.
The subarrays ``grid[k]`` contains the N-D array of indices along the
``k-th`` axis. Explicitly::
grid[k,i0,i1,...,iN-1] = ik
Examples
--------
>>> grid = np.indices((2, 3))
>>> grid.shape
(2, 2, 3)
>>> grid[0] # row indices
array([[0, 0, 0],
[1, 1, 1]])
>>> grid[1] # column indices
array([[0, 0, 0],
[1, 1, 1]], dtype=int32)
The indices can be used as an index into an array.
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0., 1., 2.],
[4., 5., 6.]])
Note that it would be more straightforward in the above example to
extract the required elements directly with ``x[:2, :3]``.
"""
if isinstance(dimensions, (tuple, list)):
if ctx is None:
ctx = current_context()
return _npi.indices(dimensions=dimensions, dtype=dtype, ctx=ctx)
else:
raise ValueError("The dimensions must be sequence of ints")
# pylint: enable=redefined-outer-name
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def copysign(x1, x2, out=None, **kwargs):
r"""
Change the sign of x1 to that of x2, element-wise.
If `x2` is a scalar, its sign will be copied to all elements of `x1`.
Parameters
----------
x1 : ndarray or scalar
Values to change the sign of.
x2 : ndarray or scalar
The sign of `x2` is copied to `x1`.
out : ndarray or None, optional
A location into which the result is stored. It must be of the
right shape and right type to hold the output. If not provided
or `None`,a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
The values of `x1` with the sign of `x2`.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-------
This function differs from the original `numpy.copysign
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.copysign.html>`_ in
the following aspects:
- ``where`` param is not supported.
Examples
--------
>>> np.copysign(1.3, -1)
-1.3
>>> 1/np.copysign(0, 1)
inf
>>> 1/np.copysign(0, -1)
-inf
>>> a = np.array([-1, 0, 1])
>>> np.copysign(a, -1.1)
array([-1., -0., -1.])
>>> np.copysign(a, np.arange(3)-1)
array([-1., 0., 1.])
"""
return _ufunc_helper(x1, x2, _npi.copysign, _np.copysign, _npi.copysign_scalar, _npi.rcopysign_scalar, out)
@set_module('mxnet.ndarray.numpy')
def ravel(x, order='C'):
r"""
ravel(x)
Return a contiguous flattened array.
A 1-D array, containing the elements of the input, is returned. A copy is
made only if needed.
Parameters
----------
x : ndarray
Input array. The elements in `x` are read in row-major, C-style order and
packed as a 1-D array.
order : `C`, optional
Only support row-major, C-style order.
Returns
-------
y : ndarray
y is an array of the same subtype as `x`, with shape ``(x.size,)``.
Note that matrices are special cased for backward compatibility, if `x`
is a matrix, then y is a 1-D ndarray.
Notes
-----
This function differs from the original numpy.arange in the following aspects:
- Only support row-major, C-style order.
Examples
--------
It is equivalent to ``reshape(x, -1)``.
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(np.ravel(x))
[1. 2. 3. 4. 5. 6.]
>>> print(x.reshape(-1))
[1. 2. 3. 4. 5. 6.]
>>> print(np.ravel(x.T))
[1. 4. 2. 5. 3. 6.]
"""
if order != 'C':
raise NotImplementedError('order {} is not supported'.format(order))
if isinstance(x, numeric_types):
return _np.reshape(x, -1)
elif isinstance(x, NDArray):
return _npi.reshape(x, -1)
else:
raise TypeError('type {} not supported'.format(str(type(x))))
def unravel_index(indices, shape, order='C'): # pylint: disable=redefined-outer-name
"""
Converts a flat index or array of flat indices into a tuple of coordinate arrays.
Parameters:
-------------
indices : array_like
An integer array whose elements are indices into the flattened version of an array of dimensions shape.
Before version 1.6.0, this function accepted just one index value.
shape : tuple of ints
The shape of the array to use for unraveling indices.
Returns:
-------------
unraveled_coords : ndarray
Each row in the ndarray has the same shape as the indices array.
Each column in the ndarray represents the unravelled index
Examples:
-------------
>>> np.unravel_index([22, 41, 37], (7,6))
([3. 6. 6.]
[4. 5. 1.])
>>> np.unravel_index(1621, (6,7,8,9))
(3, 1, 4, 1)
"""
if order == 'C':
if isinstance(indices, numeric_types):
return _np.unravel_index(indices, shape)
ret = _npi.unravel_index_fallback(indices, shape=shape)
ret_list = []
for item in ret:
ret_list += [item]
return tuple(ret_list)
else:
raise NotImplementedError('Do not support column-major (Fortran-style) order at this moment')
@set_module('mxnet.ndarray.numpy')
def hanning(M, dtype=_np.float32, ctx=None):
r"""Return the Hanning window.
The Hanning window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
dtype : str or numpy.dtype, optional
An optional value type. Default is `float32`. Note that you need
select numpy.float32 or float64 in this operator.
ctx : Context, optional
An optional device context (default is the current default context).
Returns
-------
out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value
one appears only if `M` is odd).
See Also
--------
blackman, hamming
Notes
-----
The Hanning window is defined as
.. math:: w(n) = 0.5 - 0.5cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hanning was named for Julius von Hann, an Austrian meteorologist.
It is also known as the Cosine Bell. Some authors prefer that it be
called a Hann window, to help avoid confusion with the very similar
Hamming window.
Most references to the Hanning window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 106-108.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> np.hanning(12)
array([0. , 0.07937324, 0.29229254, 0.5711574 , 0.8274304 ,
0.9797465 , 0.97974646, 0.82743025, 0.5711573 , 0.29229245,
0.07937312, 0. ])
Plot the window and its frequency response:
>>> import matplotlib.pyplot as plt
>>> window = np.hanning(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Hann window")
Text(0.5, 1.0, 'Hann window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
"""
if ctx is None:
ctx = current_context()
return _npi.hanning(M, dtype=dtype, ctx=ctx)
@set_module('mxnet.ndarray.numpy')
def hamming(M, dtype=_np.float32, ctx=None):
r"""Return the hamming window.
The hamming window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
dtype : str or numpy.dtype, optional
An optional value type. Default is `float32`. Note that you need
select numpy.float32 or float64 in this operator.
ctx : Context, optional
An optional device context (default is the current default context).
Returns
-------
out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value
one appears only if `M` is odd).
See Also
--------
blackman, hanning
Notes
-----
The Hamming window is defined as
.. math:: w(n) = 0.54 - 0.46cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey
and is described in Blackman and Tukey. It was recommended for
smoothing the truncated autocovariance function in the time domain.
Most references to the Hamming window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 109-110.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> np.hamming(12)
array([0.08000001, 0.15302339, 0.34890914, 0.6054648 , 0.841236 ,
0.9813669 , 0.9813668 , 0.8412359 , 0.6054647 , 0.34890908,
0.15302327, 0.08000001])
Plot the window and its frequency response:
>>> import matplotlib.pyplot as plt
>>> window = np.hamming(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("hamming window")
Text(0.5, 1.0, 'hamming window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
"""
if ctx is None:
ctx = current_context()
return _npi.hamming(M, dtype=dtype, ctx=ctx)
@set_module('mxnet.ndarray.numpy')
def blackman(M, dtype=_np.float32, ctx=None):
r"""Return the Blackman window.
The Blackman window is a taper formed by using the first three
terms of a summation of cosines. It was designed to have close to the
minimal leakage possible. It is close to optimal, only slightly worse
than a Kaiser window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
dtype : str or numpy.dtype, optional
An optional value type. Default is `float32`. Note that you need
select numpy.float32 or float64 in this operator.
ctx : Context, optional
An optional device context (default is the current default context).
Returns
-------
out : ndarray
The window, with the maximum value normalized to one (the value one
appears only if the number of samples is odd).
See Also
--------
hamming, hanning
Notes
-----
The Blackman window is defined as
.. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/{M-1}) + 0.08 \cos(4\pi n/{M-1})
Most references to the Blackman window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function. It is known as a
"near optimal" tapering function, almost as good (by some measures)
as the kaiser window.
References
----------
Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra,
Dover Publications, New York.
Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
Examples
--------
>>> np.blackman(12)
array([-1.4901161e-08, 3.2606423e-02, 1.5990365e-01, 4.1439798e-01,
7.3604530e-01, 9.6704686e-01, 9.6704674e-01, 7.3604506e-01,
4.1439781e-01, 1.5990359e-01, 3.2606363e-02, -1.4901161e-08])
Plot the window and its frequency response:
>>> import matplotlib.pyplot as plt
>>> window = np.blackman(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("blackman window")
Text(0.5, 1.0, 'blackman window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
"""
if ctx is None:
ctx = current_context()
return _npi.blackman(M, dtype=dtype, ctx=ctx)
@set_module('mxnet.ndarray.numpy')
def flip(m, axis=None, out=None):
r"""
flip(m, axis=None, out=None)
Reverse the order of elements in an array along the given axis.
The shape of the array is preserved, but the elements are reordered.
Parameters
----------
m : ndarray or scalar
Input array.
axis : None or int or tuple of ints, optional
Axis or axes along which to flip over. The default,
axis=None, will flip over all of the axes of the input array.
If axis is negative it counts from the last to the first axis.
If axis is a tuple of ints, flipping is performed on all of the axes
specified in the tuple.
out : ndarray or scalar, optional
Alternative output array in which to place the result. It must have
the same shape and type as the expected output.
Returns
-------
out : ndarray or scalar
A view of `m` with the entries of axis reversed. Since a view is
returned, this operation is done in constant time.
Examples
--------
>>> A = np.arange(8).reshape((2,2,2))
>>> A
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.flip(A, 0)
array([[[4, 5],
[6, 7]],
[[0, 1],
[2, 3]]])
>>> np.flip(A, 1)
array([[[2, 3],
[0, 1]],
[[6, 7],
[4, 5]]])
>>> np.flip(A)
array([[[7, 6],
[5, 4]],
[[3, 2],
[1, 0]]])
>>> np.flip(A, (0, 2))
array([[[5, 4],
[7, 6]],
[[1, 0],
[3, 2]]])
"""
from ...numpy import ndarray
if isinstance(m, numeric_types):
return _np.flip(m, axis)
elif isinstance(m, ndarray):
return _npi.flip(m, axis, out=out)
else:
raise TypeError('type {} not supported'.format(str(type(m))))
@set_module('mxnet.ndarray.numpy')
def around(x, decimals=0, out=None, **kwargs):
r"""
around(x, decimals=0, out=None)
Evenly round to the given number of decimals.
Parameters
----------
x : ndarray or scalar
Input data.
decimals : int, optional
Number of decimal places to round to (default: 0). If
decimals is negative, it specifies the number of positions to
the left of the decimal point.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape and type as the expected output.
Returns
-------
rounded_array : ndarray or scalar
An array of the same type as `x`, containing the rounded values.
A reference to the result is returned.
Notes
-----
For values exactly halfway between rounded decimal values, NumPy
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
-0.5 and 0.5 round to 0.0, etc.
This function differs from the original numpy.prod in the following aspects:
- Cannot cast type automatically. Dtype of `out` must be same as the expected one.
- Cannot support complex-valued number.
Examples
--------
>>> np.around([0.37, 1.64])
array([ 0., 2.])
>>> np.around([0.37, 1.64], decimals=1)
array([ 0.4, 1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([ 0., 2., 2., 4., 4.])
>>> np.around([1, 2, 3, 11], decimals=1) # ndarray of ints is returned
array([ 1, 2, 3, 11])
>>> np.around([1, 2, 3, 11], decimals=-1)
array([ 0, 0, 0, 10])
"""
from ...numpy import ndarray
if isinstance(x, numeric_types):
return _np.around(x, decimals, **kwargs)
elif isinstance(x, ndarray):
return _npi.around(x, decimals, out=out, **kwargs)
else:
raise TypeError('type {} not supported'.format(str(type(x))))
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def arctan2(x1, x2, out=None, **kwargs):
r"""
Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly.
The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is
the signed angle in radians between the ray ending at the origin and
passing through the point (1,0), and the ray ending at the origin and
passing through the point (`x2`, `x1`). (Note the role reversal: the
"`y`-coordinate" is the first function parameter, the "`x`-coordinate"
is the second.) By IEEE convention, this function is defined for
`x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see
Notes for specific values).
This function is not defined for complex-valued arguments; for the
so-called argument of complex values, use `angle`.
Parameters
----------
x1 : ndarray or scalar
`y`-coordinates.
x2 : ndarray or scalar
`x`-coordinates. `x2` must be broadcastable to match the shape of
`x1` or vice versa.
out : ndarray or None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Array of angles in radians, in the range ``[-pi, pi]``. This is a scalar if
`x1` and `x2` are scalars.
Notes
-----
*arctan2* is identical to the `atan2` function of the underlying
C library. The following special values are defined in the C
standard: [1]_
====== ====== ================
`x1` `x2` `arctan2(x1,x2)`
====== ====== ================
+/- 0 +0 +/- 0
+/- 0 -0 +/- pi
> 0 +/-inf +0 / +pi
< 0 +/-inf -0 / -pi
+/-inf +inf +/- (pi/4)
+/-inf -inf +/- (3*pi/4)
====== ====== ================
Note that +0 and -0 are distinct floating point numbers, as are +inf
and -inf.
This function differs from the original numpy.arange in the following aspects:
- Only support float16, float32 and float64.
References
----------
.. [1] ISO/IEC standard 9899:1999, "Programming language C."
Examples
--------
Consider four points in different quadrants:
>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.arctan2(y, x) * 180 / np.pi
array([-135., -45., 45., 135.])
Note the order of the parameters. `arctan2` is defined also when `x2` = 0
and at several other special points, obtaining values in
the range ``[-pi, pi]``:
>>> x = np.array([1, -1])
>>> y = np.array([0, 0])
>>> np.arctan2(x, y)
array([ 1.5707964, -1.5707964])
"""
return _ufunc_helper(x1, x2, _npi.arctan2, _np.arctan2,
_npi.arctan2_scalar, _npi.rarctan2_scalar, out=out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def hypot(x1, x2, out=None, **kwargs):
r"""
Given the "legs" of a right triangle, return its hypotenuse.
Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or
`x2` is scalar_like (i.e., unambiguously cast-able to a scalar type),
it is broadcast for use with each element of the other argument.
Parameters
----------
x1, x2 : ndarray
Leg of the triangle(s).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
Returns
-------
z : ndarray
The hypotenuse of the triangle(s).
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
This function differs from the original numpy.arange in the following aspects:
- Only support float16, float32 and float64.
Examples
--------
>>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
Example showing broadcast of scalar_like argument:
>>> np.hypot(3*np.ones((3, 3)), [4])
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
"""
return _ufunc_helper(x1, x2, _npi.hypot, _np.hypot, _npi.hypot_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def bitwise_xor(x1, x2, out=None, **kwargs):
r"""
Compute the bit-wise XOR of two arrays element-wise.
Parameters
----------
x1, x2 : ndarray or scalar
Only integer and boolean types are handled. If x1.shape != x2.shape,
they must be broadcastable to a common shape (which becomes the shape of the output).
out : ndarray, optional
A location into which the result is stored. If provided, it must have a shape that the
inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
Returns
-------
out : ndarray
Result.
Examples
--------
>>> np.bitwise_xor(13, 17)
28
>>> np.bitwise_xor(31, 5)
26
>>> np.bitwise_xor(np.array([31,3], dtype='int32'), 5)
array([26, 6])
>>> np.bitwise_xor(np.array([31,3], dtype='int32'), np.array([5,6], dtype='int32'))
array([26, 5])
>>> np.bitwise_xor(np.array([True, True], dtype='bool'), np.array([False, True], dtype='bool'))
array([ True, False])
"""
return _ufunc_helper(x1, x2, _npi.bitwise_xor, _np.bitwise_xor, _npi.bitwise_xor_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def bitwise_or(x1, x2, out=None, **kwargs):
r"""
Compute the bit-wise OR of two arrays element-wise.
Parameters
----------
x1, x2 : ndarray or scalar
Only integer and boolean types are handled. If x1.shape != x2.shape,
they must be broadcastable to a common shape (which becomes the shape of the output).
out : ndarray, optional
A location into which the result is stored. If provided, it must have a shape that the
inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
Returns
-------
out : ndarray
Result.
Examples
--------
>>> np.bitwise_or(13, 17)
29
>>> np.bitwise_or(31, 5)
31
>>> np.bitwise_or(np.array([31,3], dtype='int32'), 5)
array([31, 7])
>>> np.bitwise_or(np.array([31,3], dtype='int32'), np.array([5,6], dtype='int32'))
array([31, 7])
>>> np.bitwise_or(np.array([True, True], dtype='bool'), np.array([False, True], dtype='bool'))
array([ True, True])
"""
return _ufunc_helper(x1, x2, _npi.bitwise_or, _np.bitwise_or, _npi.bitwise_or_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
@wrap_np_binary_func
def ldexp(x1, x2, out=None, **kwargs):
"""
Returns x1 * 2**x2, element-wise.
The mantissas `x1` and twos exponents `x2` are used to construct
floating point numbers ``x1 * 2**x2``.
Parameters
----------
x1 : ndarray or scalar
Array of multipliers.
x2 : ndarray or scalar, int
Array of twos exponents.
out : ndarray, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not, a freshly-allocated array is returned.
Returns
-------
y : ndarray or scalar
The result of ``x1 * 2**x2``.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Complex dtypes are not supported, they will raise a TypeError.
Different from numpy, we allow x2 to be float besides int.
`ldexp` is useful as the inverse of `frexp`, if used by itself it is
more clear to simply use the expression ``x1 * 2**x2``.
Examples
--------
>>> np.ldexp(5, np.arange(4))
array([ 5., 10., 20., 40.])
"""
return _ufunc_helper(x1, x2, _npi.ldexp, _np.ldexp, _npi.ldexp_scalar, _npi.rldexp_scalar, out)
@set_module('mxnet.ndarray.numpy')
def inner(a, b):
r"""
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex
conjugation), in higher dimensions a sum product over the last axes.
Parameters
----------
a, b : ndarray
If `a` and `b` are nonscalar, their last dimensions must match.
Returns
-------
out : ndarray
`out.shape = a.shape[:-1] + b.shape[:-1]`
Raises
------
ValueError
If the last dimension of `a` and `b` has different size.
See Also
--------
tensordot : Sum products over arbitrary axes.
dot : Generalised matrix product, using second last dimension of `b`.
einsum : Einstein summation convention.
Notes
-----
For vectors (1-D arrays) it computes the ordinary inner-product::
np.inner(a, b) = sum(a[:]*b[:])
More generally, if `ndim(a) = r > 0` and `ndim(b) = s > 0`::
np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
or explicitly::
np.inner(a, b)[i0,...,ir-1,j0,...,js-1]
= sum(a[i0,...,ir-1,:]*b[j0,...,js-1,:])
In addition `a` or `b` may be scalars, in which case::
np.inner(a,b) = a*b
Examples
--------
Ordinary inner product for vectors:
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
A multidimensional example:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14, 38, 62],
[ 86, 110, 134]])
"""
return tensordot(a, b, [-1, -1])
@set_module('mxnet.ndarray.numpy')
def outer(a, b):
r"""
Compute the outer product of two vectors.
Given two vectors, ``a = [a0, a1, ..., aM]`` and
``b = [b0, b1, ..., bN]``,
the outer product [1]_ is::
[[a0*b0 a0*b1 ... a0*bN ]
[a1*b0 .
[ ... .
[aM*b0 aM*bN ]]
Parameters
----------
a : (M,) ndarray
First input vector. Input is flattened if
not already 1-dimensional.
b : (N,) ndarray
Second input vector. Input is flattened if
not already 1-dimensional.
Returns
-------
out : (M, N) ndarray
``out[i, j] = a[i] * b[j]``
See also
--------
inner
einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
ufunc.outer : A generalization to N dimensions and other operations.
``np.multiply.outer(a.ravel(), b.ravel())`` is the equivalent.
References
----------
.. [1] : G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
ed., Baltimore, MD, Johns Hopkins University Press, 1996,
pg. 8.
Examples
--------
Make a (*very* coarse) grid for computing a Mandelbrot set:
>>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
>>> rl
array([[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.]])
"""
return tensordot(a.flatten(), b.flatten(), 0)
@set_module('mxnet.ndarray.numpy')
def vdot(a, b):
r"""
Return the dot product of two vectors.
Note that `vdot` handles multidimensional arrays differently than `dot`:
it does *not* perform a matrix product, but flattens input arguments
to 1-D vectors first. Consequently, it should only be used for vectors.
Parameters
----------
a : ndarray
First argument to the dot product.
b : ndarray
Second argument to the dot product.
Returns
-------
output : ndarray
Dot product of `a` and `b`.
See Also
--------
dot : Return the dot product without using the complex conjugate of the
first argument.
Examples
--------
Note that higher-dimensional arrays are flattened!
>>> a = np.array([[1, 4], [5, 6]])
>>> b = np.array([[4, 1], [2, 2]])
>>> np.vdot(a, b)
30
>>> np.vdot(b, a)
30
>>> 1*4 + 4*1 + 5*2 + 6*2
30
"""
return tensordot(a.flatten(), b.flatten(), 1)
@set_module('mxnet.ndarray.numpy')
def equal(x1, x2, out=None):
"""
Return (x1 == x2) element-wise.
Parameters
----------
x1, x2 : ndarrays or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
not_equal, greater_equal, less_equal, greater, less
Examples
--------
>>> np.equal(np.ones(2, 1)), np.zeros(1, 3))
array([[False, False, False],
[False, False, False]])
>>> np.equal(1, np.ones(1))
array([ True])
"""
return _ufunc_helper(x1, x2, _npi.equal, _np.equal, _npi.equal_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
def not_equal(x1, x2, out=None):
"""
Return (x1 != x2) element-wise.
Parameters
----------
x1, x2 : ndarrays or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
equal, greater, greater_equal, less, less_equal
Examples
--------
>>> np.not_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[ True, True, True],
[ True, True, True]])
>>> np.not_equal(1, np.ones(1))
array([False])
"""
return _ufunc_helper(x1, x2, _npi.not_equal, _np.not_equal, _npi.not_equal_scalar, None, out)
@set_module('mxnet.ndarray.numpy')
def greater(x1, x2, out=None):
"""
Return the truth value of (x1 > x2) element-wise.
Parameters
----------
x1, x2 : ndarrays or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
equal, greater, greater_equal, less, less_equal
Examples
--------
>>> np.greater(np.ones(2, 1)), np.zeros(1, 3))
array([[ True, True, True],
[ True, True, True]])
>>> np.greater(1, np.ones(1))
array([False])
"""
return _ufunc_helper(x1, x2, _npi.greater, _np.greater, _npi.greater_scalar,
_npi.less_scalar, out)
@set_module('mxnet.ndarray.numpy')
def less(x1, x2, out=None):
"""
Return the truth value of (x1 < x2) element-wise.
Parameters
----------
x1, x2 : ndarrays or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
equal, greater, greater_equal, less, less_equal
Examples
--------
>>> np.less(np.ones(2, 1)), np.zeros(1, 3))
array([[ True, True, True],
[ True, True, True]])
>>> np.less(1, np.ones(1))
array([False])
"""
return _ufunc_helper(x1, x2, _npi.less, _np.less, _npi.less_scalar, _npi.greater_scalar, out)
@set_module('mxnet.ndarray.numpy')
def greater_equal(x1, x2, out=None):
"""
Return the truth value of (x1 >= x2) element-wise.
Parameters
----------
x1, x2 : ndarrays or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
equal, greater, greater_equal, less, less_equal
Examples
--------
>>> np.greater_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[ True, True, True],
[ True, True, True]])
>>> np.greater_equal(1, np.ones(1))
array([True])
"""
return _ufunc_helper(x1, x2, _npi.greater_equal, _np.greater_equal, _npi.greater_equal_scalar,
_npi.less_equal_scalar, out)
@set_module('mxnet.ndarray.numpy')
def less_equal(x1, x2, out=None):
"""
Return the truth value of (x1 <= x2) element-wise.
Parameters
----------
x1, x2 : ndarrays or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : ndarray or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
equal, greater, greater_equal, less, less_equal
Examples
--------
>>> np.less_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[False, False, False],
[False, False, False]])
>>> np.less_equal(1, np.ones(1))
array([True])
"""
return _ufunc_helper(x1, x2, _npi.less_equal, _np.less_equal, _npi.less_equal_scalar,
_npi.greater_equal_scalar, out)
@set_module('mxnet.ndarray.numpy')
def rot90(m, k=1, axes=(0, 1)):
"""
Rotate an array by 90 degrees in the plane specified by axes.
Rotation direction is from the first towards the second axis.
Parameters
----------
m : ndarray
Array of two or more dimensions.
k : integer
Number of times the array is rotated by 90 degrees.
axes: (2,) array_like
The array is rotated in the plane defined by the axes.
Axes must be different.
Returns
-------
y : ndarray
A rotated view of `m`.
-----
rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1))
rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))
Examples
--------
>>> m = np.array([[1,2],[3,4]], 'int')
>>> m
array([[1, 2],
[3, 4]], dtype=int64)
>>> np.rot90(m)
array([[2, 4],
[1, 3]], dtype=int64)
>>> np.rot90(m, 2)
array([[4, 3],
[2, 1]], dtype=int64)
>>> m = np.arange(8).reshape((2,2,2))
>>> np.rot90(m, 1, (1,2))
array([[[1., 3.],
[0., 2.]],
[[5., 7.],
[4., 6.]]])
"""
return _npi.rot90(m, k=k, axes=axes)
@set_module('mxnet.ndarray.numpy')
def einsum(*operands, **kwargs):
r"""
einsum(subscripts, *operands, out=None, optimize=False)
Evaluates the Einstein summation convention on the operands.
Using the Einstein summation convention, many common multi-dimensional,
linear algebraic array operations can be represented in a simple fashion.
In *implicit* mode `einsum` computes these values.
In *explicit* mode, `einsum` provides further flexibility to compute
other array operations that might not be considered classical Einstein
summation operations, by disabling, or forcing summation over specified
subscript labels.
See the notes and examples for clarification.
Parameters
----------
subscripts : str
Specifies the subscripts for summation as comma separated list of
subscript labels. An implicit (classical Einstein summation)
calculation is performed unless the explicit indicator '->' is
included as well as subscript labels of the precise output form.
operands : list of ndarray
These are the arrays for the operation.
out : ndarray, optional
If provided, the calculation is done into this array.
optimize : {False, True}, optional
Controls if intermediate optimization should occur. No optimization
will occur if False. Defaults to False.
Returns
-------
output : ndarray
The calculation based on the Einstein summation convention.
Notes
-----
The Einstein summation convention can be used to compute
many multi-dimensional, linear algebraic array operations. `einsum`
provides a succinct way of representing these.
A non-exhaustive list of these operations,
which can be computed by `einsum`, is shown below along with examples:
* Trace of an array, :py:func:`np.trace`.
* Return a diagonal, :py:func:`np.diag`.
* Array axis summations, :py:func:`np.sum`.
* Transpositions and permutations, :py:func:`np.transpose`.
* Matrix multiplication and dot product, :py:func:`np.matmul` :py:func:`np.dot`.
* Vector inner and outer products, :py:func:`np.inner` :py:func:`np.outer`.
* Broadcasting, element-wise and scalar multiplication, :py:func:`np.multiply`.
* Tensor contractions, :py:func:`np.tensordot`.
The subscripts string is a comma-separated list of subscript labels,
where each label refers to a dimension of the corresponding operand.
Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
is equivalent to :py:func:`np.inner(a,b) <np.inner>`. If a label
appears only once, it is not summed, so ``np.einsum('i', a)`` produces a
view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``
describes traditional matrix multiplication and is equivalent to
:py:func:`np.matmul(a,b) <np.matmul>`. Repeated subscript labels in one
operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent
to :py:func:`np.trace(a) <np.trace>`.
In *implicit mode*, the chosen subscripts are important
since the axes of the output are reordered alphabetically. This
means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
``np.einsum('ji', a)`` takes its transpose. Additionally,
``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
``np.einsum('ij,jh', a, b)`` returns the transpose of the
multiplication since subscript 'h' precedes subscript 'i'.
In *explicit mode* the output can be directly controlled by
specifying output subscript labels. This requires the
identifier '->' as well as the list of output subscript labels.
This feature increases the flexibility of the function since
summing can be disabled or forced when required. The call
``np.einsum('i->', a)`` is like :py:func:`np.sum(a, axis=-1) <np.sum>`,
and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <np.diag>`.
The difference is that `einsum` does not allow broadcasting by default.
Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
order of the output subscript labels and therefore returns matrix
multiplication, unlike the example above in implicit mode.
To enable and control broadcasting, use an ellipsis. Default
NumPy-style broadcasting is done by adding an ellipsis
to the left of each term, like ``np.einsum('...ii->...i', a)``.
To take the trace along the first and last axes,
you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
product with the left-most indices instead of rightmost, one can do
``np.einsum('ij...,jk...->ik...', a, b)``.
When there is only one operand, no axes are summed, and no output
parameter is provided, a view into the operand is returned instead
of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
produces a view.
The ``optimize`` argument which will optimize the contraction order
of an einsum expression. For a contraction with three or more operands this
can greatly increase the computational efficiency at the cost of a larger
memory footprint during computation.
Typically a 'greedy' algorithm is applied which empirical tests have shown
returns the optimal path in the majority of cases. 'optimal' is not supported
for now.
This function differs from the original `numpy.einsum
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html>`_ in
the following way(s):
- Does not support 'optimal' strategy
- Does not support the alternative subscript like
`einsum(op0, sublist0, op1, sublist1, ..., [sublistout])`
- Does not produce view in any cases
Examples
--------
>>> a = np.arange(25).reshape(5,5)
>>> b = np.arange(5)
>>> c = np.arange(6).reshape(2,3)
Trace of a matrix:
>>> np.einsum('ii', a)
array(60.)
Extract the diagonal (requires explicit form):
>>> np.einsum('ii->i', a)
array([ 0., 6., 12., 18., 24.])
Sum over an axis (requires explicit form):
>>> np.einsum('ij->i', a)
array([ 10., 35., 60., 85., 110.])
>>> np.sum(a, axis=1)
array([ 10., 35., 60., 85., 110.])
For higher dimensional arrays summing a single axis can be done with ellipsis:
>>> np.einsum('...j->...', a)
array([ 10., 35., 60., 85., 110.])
Compute a matrix transpose, or reorder any number of axes:
>>> np.einsum('ji', c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
>>> np.einsum('ij->ji', c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
>>> np.transpose(c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
Vector inner products:
>>> np.einsum('i,i', b, b)
array(30.)
Matrix vector multiplication:
>>> np.einsum('ij,j', a, b)
array([ 30., 80., 130., 180., 230.])
>>> np.dot(a, b)
array([ 30., 80., 130., 180., 230.])
>>> np.einsum('...j,j', a, b)
array([ 30., 80., 130., 180., 230.])
Broadcasting and scalar multiplication:
>>> np.einsum('..., ...', np.array(3), c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
>>> np.einsum(',ij', np.array(3), c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
>>> np.multiply(3, c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
Vector outer product:
>>> np.einsum('i,j', np.arange(2)+1, b)
array([[0., 1., 2., 3., 4.],
[0., 2., 4., 6., 8.]])
Tensor contraction:
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> np.einsum('ijk,jil->kl', a, b)
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
Example of ellipsis use:
>>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
>>> np.einsum('k...,jk', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
Chained array operations. For more complicated contractions, speed ups
might be achieved by repeatedly computing a 'greedy' path. Performance
improvements can be particularly significant with larger arrays:
>>> a = np.ones(64).reshape(2,4,8)
# Basic `einsum`: ~42.22ms (benchmarked on 3.4GHz Intel Xeon.)
>>> for iteration in range(500):
... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
# Greedy `einsum` (faster optimal path approximation): ~0.117ms
>>> for iteration in range(500):
... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=True)
"""
# Grab non-einsum kwargs; do not optimize by default.
optimize_arg = kwargs.pop('optimize', False)
out = kwargs.pop('out', None)
subscripts = operands[0]
operands = operands[1:]
return _npi.einsum(*operands, subscripts=subscripts, out=out, optimize=int(optimize_arg))
@set_module('mxnet.ndarray.numpy')
def nonzero(a):
"""
Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of `a`,
containing the indices of the non-zero elements in that
dimension. The values in `a` are always returned in
row-major, C-style order.
To group the indices by element, rather than dimension, use `argwhere`,
which returns a row for each non-zero element.
Parameters
----------
a : ndarray
Input array.
Returns
-------
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also
--------
ndarray.nonzero :
Equivalent ndarray method.
Notes
-----
While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
will correctly handle 0-d arrays.
Examples
--------
>>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
>>> x
array([[3, 0, 0],
[0, 4, 0],
[5, 6, 0]], dtype=int32)
>>> np.nonzero(x)
(array([0, 1, 2, 2], dtype=int64), array([0, 1, 0, 1], dtype=int64))
>>> x[np.nonzero(x)]
array([3, 4, 5, 6])
>>> np.transpose(np.stack(np.nonzero(x)))
array([[0, 0],
[1, 1],
[2, 0],
[2, 1]], dtype=int64)
A common use for ``nonzero`` is to find the indices of an array, where
a condition is True. Given an array `a`, the condition `a` > 3 is a
boolean array and since False is interpreted as 0, np.nonzero(a > 3)
yields the indices of the `a` where the condition is true.
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
>>> a > 3
array([[False, False, False],
[ True, True, True],
[ True, True, True]])
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2], dtype=int64), array([0, 1, 2, 0, 1, 2], dtype=int64))
Using this result to index `a` is equivalent to using the mask directly:
>>> a[np.nonzero(a > 3)]
array([4, 5, 6, 7, 8, 9], dtype=int32)
>>> a[a > 3]
array([4, 5, 6, 7, 8, 9], dtype=int32)
``nonzero`` can also be called as a method of the array.
>>> (a > 3).nonzero()
(array([1, 1, 1, 2, 2, 2], dtype=int64), array([0, 1, 2, 0, 1, 2], dtype=int64))
"""
out = _npi.nonzero(a).transpose()
return tuple([out[i] for i in range(len(out))])
@set_module('mxnet.ndarray.numpy')
def shares_memory(a, b, max_work=None):
"""
Determine if two arrays share memory
Parameters
----------
a, b : ndarray
Input arrays
Returns
-------
out : bool
See Also
--------
may_share_memory
Examples
--------
>>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
False
This function differs from the original `numpy.shares_memory
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.shares_memory.html>`_ in
the following way(s):
- Does not support `max_work`, it is a dummy argument
- Actually it is same as `may_share_memory` in MXNet DeepNumPy
"""
return _npi.share_memory(a, b).item()
@set_module('mxnet.ndarray.numpy')
def may_share_memory(a, b, max_work=None):
"""
Determine if two arrays might share memory
A return of True does not necessarily mean that the two arrays
share any element. It just means that they *might*.
Only the memory bounds of a and b are checked by default.
Parameters
----------
a, b : ndarray
Input arrays
Returns
-------
out : bool
See Also
--------
shares_memory
Examples
--------
>>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
False
>>> x = np.zeros([3, 4])
>>> np.may_share_memory(x[:,0], x[:,1])
True
This function differs from the original `numpy.may_share_memory
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.may_share_memory.html>`_ in
the following way(s):
- Does not support `max_work`, it is a dummy argument
- Actually it is same as `shares_memory` in MXNet DeepNumPy
"""
return _npi.share_memory(a, b).item()
@set_module('mxnet.ndarray.numpy')
def diff(a, n=1, axis=-1, prepend=None, append=None): # pylint: disable=redefined-outer-name
r"""
Calculate the n-th discrete difference along the given axis.
Parameters
----------
a : ndarray
Input array
n : int, optional
The number of times values are differenced. If zero, the input is returned as-is.
axis : int, optional
The axis along which the difference is taken, default is the last axis.
prepend, append : ndarray, optional
Not supported yet
Returns
-------
diff : ndarray
The n-th differences.
The shape of the output is the same as a except along axis where the dimension is smaller by n.
The type of the output is the same as the type of the difference between any two elements of a.
Examples
--------
>>> x = np.array([1, 2, 4, 7, 0])
>>> np.diff(x)
array([ 1, 2, 3, -7])
>>> np.diff(x, n=2)
array([ 1, 1, -10])
>>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
>>> np.diff(x)
array([[2, 3, 4],
[5, 1, 2]])
>>> np.diff(x, axis=0)
array([[-1, 2, 0, -2]])
Notes
-----
Optional inputs `prepend` and `append` are not supported yet
"""
if (prepend or append):
raise NotImplementedError('prepend and append options are not supported yet')
return _npi.diff(a, n=n, axis=axis)
@set_module('mxnet.ndarray.numpy')
def resize(a, new_shape):
"""
Return a new array with the specified shape.
If the new array is larger than the original array, then the new
array is filled with repeated copies of `a`. Note that this behavior
is different from a.resize(new_shape) which fills with zeros instead
of repeated copies of `a`.
Parameters
----------
a : ndarray
Array to be resized.
new_shape : int or tuple of int
Shape of resized array.
Returns
-------
reshaped_array : ndarray
The new array is formed from the data in the old array, repeated
if necessary to fill out the required number of elements. The
data are repeated in the order that they are stored in memory.
See Also
--------
ndarray.resize : resize an array in-place.
Notes
-----
Warning: This functionality does **not** consider axes separately,
i.e. it does not apply interpolation/extrapolation.
It fills the return array with the required number of elements, taken
from `a` as they are laid out in memory, disregarding strides and axes.
(This is in case the new shape is smaller. For larger, see above.)
This functionality is therefore not suitable to resize images,
or data where each axis represents a separate and distinct entity.
Examples
--------
>>> a = np.array([[0, 1], [2, 3]])
>>> np.resize(a, (2, 3))
array([[0., 1., 2.],
[3., 0., 1.]])
>>> np.resize(a, (1, 4))
array([[0., 1., 2., 3.]])
>>> np.resize(a,(2, 4))
array([[0., 1., 2., 3.],
[0., 1., 2., 3.]])
"""
return _npi.resize_fallback(a, new_shape=new_shape)
@set_module('mxnet.ndarray.numpy')
def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None, **kwargs):
"""
Replace NaN with zero and infinity with large finite numbers (default
behaviour) or with the numbers defined by the user using the `nan`,
`posinf` and/or `neginf` keywords.
If `x` is inexact, NaN is replaced by zero or by the user defined value in
`nan` keyword, infinity is replaced by the largest finite floating point
values representable by ``x.dtype`` or by the user defined value in
`posinf` keyword and -infinity is replaced by the most negative finite
floating point values representable by ``x.dtype`` or by the user defined
value in `neginf` keyword.
For complex dtypes, the above is applied to each of the real and
imaginary components of `x` separately.
If `x` is not inexact, then no replacements are made.
Parameters
----------
x : ndarray
Input data.
copy : bool, optional
Whether to create a copy of `x` (True) or to replace values
in-place (False). The in-place operation only occurs if
casting to an array does not require a copy.
Default is True.
nan : int, float, optional
Value to be used to fill NaN values. If no value is passed
then NaN values will be replaced with 0.0.
posinf : int, float, optional
Value to be used to fill positive infinity values. If no value is
passed then positive infinity values will be replaced with a very
large number.
neginf : int, float, optional
Value to be used to fill negative infinity values. If no value is
passed then negative infinity values will be replaced with a very
small (or negative) number.
.. versionadded:: 1.13
Returns
-------
out : ndarray
`x`, with the non-finite values replaced. If `copy` is False, this may
be `x` itself.
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Examples
--------
>>> np.nan_to_num(np.inf)
1.7976931348623157e+308
>>> np.nan_to_num(-np.inf)
-1.7976931348623157e+308
>>> np.nan_to_num(np.nan)
0.0
>>> x = np.array([np.inf, -np.inf, np.nan, -128, 128])
>>> np.nan_to_num(x)
array([ 3.4028235e+38, -3.4028235e+38, 0.0000000e+00, -1.2800000e+02,
1.2800000e+02])
>>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333)
array([ 3.3333332e+07, 3.3333332e+07, -9.9990000e+03, -1.2800000e+02,
1.2800000e+02])
>>> y = np.array([[-1, 0, 1],[9999,234,-14222]],dtype="float64")/0
array([[-inf, nan, inf],
[ inf, inf, -inf]], dtype=float64)
>>> np.nan_to_num(y)
array([[-1.79769313e+308, 0.00000000e+000, 1.79769313e+308],
[ 1.79769313e+308, 1.79769313e+308, -1.79769313e+308]], dtype=float64)
>>> np.nan_to_num(y, nan=111111, posinf=222222)
array([[-1.79769313e+308, 1.11111000e+005, 2.22222000e+005],
[ 2.22222000e+005, 2.22222000e+005, -1.79769313e+308]], dtype=float64)
>>> y
array([[-inf, nan, inf],
[ inf, inf, -inf]], dtype=float64)
>>> np.nan_to_num(y, copy=False, nan=111111, posinf=222222)
array([[-1.79769313e+308, 1.11111000e+005, 2.22222000e+005],
[ 2.22222000e+005, 2.22222000e+005, -1.79769313e+308]], dtype=float64)
>>> y
array([[-1.79769313e+308, 1.11111000e+005, 2.22222000e+005],
[ 2.22222000e+005, 2.22222000e+005, -1.79769313e+308]], dtype=float64)
"""
if isinstance(x, numeric_types):
return _np.nan_to_num(x, copy, nan, posinf, neginf)
elif isinstance(x, NDArray):
if x.dtype in ['int8', 'uint8', 'int32', 'int64']:
return x
if not copy:
return _npi.nan_to_num(x, copy=copy, nan=nan, posinf=posinf, neginf=neginf, out=x)
return _npi.nan_to_num(x, copy=copy, nan=nan, posinf=posinf, neginf=neginf, out=None)
else:
raise TypeError('type {} not supported'.format(str(type(x))))
@set_module('mxnet.ndarray.numpy')
def where(condition, x=None, y=None):
"""where(condition, [x, y])
Return elements chosen from `x` or `y` depending on `condition`.
.. note::
When only `condition` is provided, this function is a shorthand for
``np.asarray(condition).nonzero()``. The rest of this documentation
covers only the case where all three arguments are provided.
Parameters
----------
condition : ndarray
Where True, yield `x`, otherwise yield `y`.
x, y : ndarray
Values from which to choose. `x`, `y` and `condition` need to be
broadcastable to some shape. `x` and `y` must have the same dtype.
Returns
-------
out : ndarray
An array with elements from `x` where `condition` is True, and elements
from `y` elsewhere.
Notes
-----
If all the arrays are 1-D, `where` is equivalent to::
[xv if c else yv
for c, xv, yv in zip(condition, x, y)]
Examples
--------
>>> a = np.arange(10)
>>> a
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> np.where(a < 5, a, 10*a)
array([ 0., 1., 2., 3., 4., 50., 60., 70., 80., 90.])
This can be used on multidimensional arrays too:
>>> cond = np.array([[True, False], [True, True]])
>>> x = np.array([[1, 2], [3, 4]])
>>> y = np.array([[9, 8], [7, 6]])
>>> np.where(cond, x, y)
array([[1., 8.],
[3., 4.]])
The shapes of x, y, and the condition are broadcast together:
>>> x, y = onp.ogrid[:3, :4]
>>> x = np.array(x)
>>> y = np.array(y)
>>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast
array([[10, 0, 0, 0],
[10, 11, 1, 1],
[10, 11, 12, 2]], dtype=int64)
>>> a = np.array([[0, 1, 2],
... [0, 2, 4],
... [0, 3, 6]])
>>> np.where(a < 4, a, np.array(-1)) # -1 is broadcast
array([[ 0., 1., 2.],
[ 0., 2., -1.],
[ 0., 3., -1.]])
"""
if x is None and y is None:
return nonzero(condition)
else:
return _npi.where(condition, x, y, out=None)
| 33.60542
| 132
| 0.60842
|
9c42b290a3ac94594cd5da54fc0574651f40662f
| 1,265
|
py
|
Python
|
discoreg/registrations/views/webhook.py
|
PyGotham/discoreg
|
43bffe1febdf326cbc71f549e1609bcb46258041
|
[
"Apache-2.0"
] | null | null | null |
discoreg/registrations/views/webhook.py
|
PyGotham/discoreg
|
43bffe1febdf326cbc71f549e1609bcb46258041
|
[
"Apache-2.0"
] | null | null | null |
discoreg/registrations/views/webhook.py
|
PyGotham/discoreg
|
43bffe1febdf326cbc71f549e1609bcb46258041
|
[
"Apache-2.0"
] | null | null | null |
import json
import logging
import os
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from ..models import DiscordRole, EmailRole, Registration
logger = logging.getLogger(__name__)
REGISTRATION_WEBHOOK_TOKEN = settings.REGISTRATION_WEBHOOK_TOKEN
@csrf_exempt
def webhook_handler(request):
if not REGISTRATION_WEBHOOK_TOKEN:
raise Exception("No webook token set")
if request.META.get("HTTP_AUTHORIZATION") != f"Bearer {REGISTRATION_WEBHOOK_TOKEN}":
return HttpResponse("Unauthorized", status=401)
payload = json.loads(request.body.decode("utf-8"))
logger.warning(payload)
default_roles = DiscordRole.objects.filter(assign_by_default=True)
try:
email_role = EmailRole.objects.get(email__iexact=payload["email"])
except ObjectDoesNotExist:
email_role = EmailRole(email=payload["email"].lower())
email_role.save()
logger.error(email_role)
email_role.discord_roles.add(*default_roles)
email_role.save()
registration = Registration(email=email_role, reference_id=payload["reference_id"])
registration.save()
return HttpResponse(status=201)
| 30.119048
| 88
| 0.762055
|
d61b3c7be5973a8b9535904f17cfe785a7cf955d
| 3,142
|
py
|
Python
|
setup.py
|
fakegit/python-pinyin
|
a421a83127ee55cba09ecabbf63d0c1bfb3a3aea
|
[
"MIT"
] | 1
|
2021-12-07T05:58:32.000Z
|
2021-12-07T05:58:32.000Z
|
setup.py
|
yaffils/python-pinyin
|
a421a83127ee55cba09ecabbf63d0c1bfb3a3aea
|
[
"MIT"
] | null | null | null |
setup.py
|
yaffils/python-pinyin
|
a421a83127ee55cba09ecabbf63d0c1bfb3a3aea
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from codecs import open
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
current_dir = os.path.dirname(os.path.realpath(__file__))
packages = [
'pypinyin',
'pypinyin.contrib',
'pypinyin.seg',
'pypinyin.style',
]
requirements = []
if sys.version_info[:2] < (2, 7):
requirements.append('argparse')
if sys.version_info[:2] < (3, 4):
requirements.append('enum34')
if sys.version_info[:2] < (3, 5):
requirements.append('typing')
extras_require = {
':python_version<"2.7"': ['argparse'],
':python_version<"3.4"': ['enum34'],
':python_version<"3.5"': ['typing'],
}
def get_meta():
meta_re = re.compile(r"(?P<name>__\w+__) = '(?P<value>[^']+)'")
meta_d = {}
with open(os.path.join(current_dir, 'pypinyin/__init__.py'),
encoding='utf8') as fp:
for match in meta_re.finditer(fp.read()):
meta_d[match.group('name')] = match.group('value')
return meta_d
def long_description():
with open(os.path.join(current_dir, 'README.rst'),
encoding='utf8') as fp:
return fp.read()
meta_d = get_meta()
setup(
name='pypinyin',
version=meta_d['__version__'],
description='汉字拼音转换模块/工具.',
long_description=long_description(),
long_description_content_type='text/x-rst',
url='https://github.com/mozillazg/python-pinyin',
author=meta_d['__author__'],
author_email='mozillazg101@gmail.com',
license=meta_d['__license__'],
project_urls={
'Documentation': 'https://pypinyin.readthedocs.io/',
'Source': 'https://github.com/mozillazg/python-pinyin',
'Tracker': 'https://github.com/mozillazg/python-pinyin/issues',
},
packages=packages,
package_dir={'pypinyin': 'pypinyin'},
include_package_data=True,
install_requires=requirements,
extras_require=extras_require,
python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*, <4',
zip_safe=False,
entry_points={
'console_scripts': [
'pypinyin = pypinyin.__main__:main',
],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Utilities',
'Topic :: Text Processing',
],
keywords='pinyin, 拼音',
)
| 30.504854
| 71
| 0.612031
|
82d5725797e20c223df0582ad44ccf350b29f7ec
| 1,244
|
py
|
Python
|
lab12/createIndices.py
|
xehoth/CS110P
|
120cc8a4ffc97ae75ddeb8b28708641be1672af3
|
[
"MIT"
] | null | null | null |
lab12/createIndices.py
|
xehoth/CS110P
|
120cc8a4ffc97ae75ddeb8b28708641be1672af3
|
[
"MIT"
] | null | null | null |
lab12/createIndices.py
|
xehoth/CS110P
|
120cc8a4ffc97ae75ddeb8b28708641be1672af3
|
[
"MIT"
] | null | null | null |
import sys
import re
from pyspark import SparkContext,SparkConf
def flatMapFunc(document):
"""
document[0] is the document ID (distinct for each document)
document[1] is a string of all text in that document
You will need to modify this code.
"""
documentID = document[0]
words = re.findall(r"\w+", document[1])
return [(f'{v} {documentID}', i) for i, v in enumerate(words)]
# def mapFunc(arg):
# """
# You may need to modify this code.
# """
# return (arg, 1)
def reduceFunc(arg1, arg2):
"""
You may need to modify this code.
"""
return str(arg1) + " " + str(arg2)
def createIndices(file_name, output="spark-wc-out-createIndices"):
sc = SparkContext("local[8]", "CreateIndices", conf=SparkConf().set("spark.hadoop.validateOutputSpecs", "false"))
file = sc.sequenceFile(file_name)
indices = file.flatMap(flatMapFunc) \
.reduceByKey(reduceFunc) \
.sortByKey()
# .map(mapFunc) \
indices.coalesce(1).saveAsTextFile(output)
""" Do not worry about this """
if __name__ == "__main__":
argv = sys.argv
if len(argv) == 2:
createIndices(argv[1])
else:
createIndices(argv[1], argv[2])
| 26.468085
| 117
| 0.614952
|
606aaa2ff87b1a4b9cd6f99cde611ed630c470cc
| 4,029
|
py
|
Python
|
alipay/aop/api/request/AlipayInsSceneApplicationQueryRequest.py
|
articuly/alipay-sdk-python-all
|
0259cd28eca0f219b97dac7f41c2458441d5e7a6
|
[
"Apache-2.0"
] | null | null | null |
alipay/aop/api/request/AlipayInsSceneApplicationQueryRequest.py
|
articuly/alipay-sdk-python-all
|
0259cd28eca0f219b97dac7f41c2458441d5e7a6
|
[
"Apache-2.0"
] | null | null | null |
alipay/aop/api/request/AlipayInsSceneApplicationQueryRequest.py
|
articuly/alipay-sdk-python-all
|
0259cd28eca0f219b97dac7f41c2458441d5e7a6
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayInsSceneApplicationQueryModel import AlipayInsSceneApplicationQueryModel
class AlipayInsSceneApplicationQueryRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._udf_params = None
self._need_encrypt = False
@property
def biz_model(self):
return self._biz_model
@biz_model.setter
def biz_model(self, value):
self._biz_model = value
@property
def biz_content(self):
return self._biz_content
@biz_content.setter
def biz_content(self, value):
if isinstance(value, AlipayInsSceneApplicationQueryModel):
self._biz_content = value
else:
self._biz_content = AlipayInsSceneApplicationQueryModel.from_alipay_dict(value)
@property
def version(self):
return self._version
@version.setter
def version(self, value):
self._version = value
@property
def terminal_type(self):
return self._terminal_type
@terminal_type.setter
def terminal_type(self, value):
self._terminal_type = value
@property
def terminal_info(self):
return self._terminal_info
@terminal_info.setter
def terminal_info(self, value):
self._terminal_info = value
@property
def prod_code(self):
return self._prod_code
@prod_code.setter
def prod_code(self, value):
self._prod_code = value
@property
def notify_url(self):
return self._notify_url
@notify_url.setter
def notify_url(self, value):
self._notify_url = value
@property
def return_url(self):
return self._return_url
@return_url.setter
def return_url(self, value):
self._return_url = value
@property
def udf_params(self):
return self._udf_params
@udf_params.setter
def udf_params(self, value):
if not isinstance(value, dict):
return
self._udf_params = value
@property
def need_encrypt(self):
return self._need_encrypt
@need_encrypt.setter
def need_encrypt(self, value):
self._need_encrypt = value
def add_other_text_param(self, key, value):
if not self.udf_params:
self.udf_params = dict()
self.udf_params[key] = value
def get_params(self):
params = dict()
params[P_METHOD] = 'alipay.ins.scene.application.query'
params[P_VERSION] = self.version
if self.biz_model:
params[P_BIZ_CONTENT] = json.dumps(obj=self.biz_model.to_alipay_dict(), use_decimal=True, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
if self.biz_content:
if hasattr(self.biz_content, 'to_alipay_dict'):
params['biz_content'] = json.dumps(obj=self.biz_content.to_alipay_dict(), use_decimal=True, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
else:
params['biz_content'] = self.biz_content
if self.terminal_type:
params['terminal_type'] = self.terminal_type
if self.terminal_info:
params['terminal_info'] = self.terminal_info
if self.prod_code:
params['prod_code'] = self.prod_code
if self.notify_url:
params['notify_url'] = self.notify_url
if self.return_url:
params['return_url'] = self.return_url
if self.udf_params:
params.update(self.udf_params)
return params
def get_multipart_params(self):
multipart_params = dict()
return multipart_params
| 27.786207
| 166
| 0.647803
|
f6447d99dd5bb61c645da6197780d8ee59bef3bb
| 891
|
py
|
Python
|
bare_locks/pywin32/win32file.py
|
psarka/bare-locks
|
6c04d8209621585f6581170f12534f8c24fa604e
|
[
"MIT"
] | null | null | null |
bare_locks/pywin32/win32file.py
|
psarka/bare-locks
|
6c04d8209621585f6581170f12534f8c24fa604e
|
[
"MIT"
] | null | null | null |
bare_locks/pywin32/win32file.py
|
psarka/bare-locks
|
6c04d8209621585f6581170f12534f8c24fa604e
|
[
"MIT"
] | null | null | null |
from ctypes import POINTER
from ctypes import pointer
from ctypes import WinDLL
from ctypes.wintypes import BOOL
from ctypes.wintypes import DWORD
from ctypes.wintypes import HANDLE
from bare_locks.pywin32.pywintypes import OVERLAPPED
kernel32 = WinDLL('kernel32', use_last_error=True)
_ = pointer
# Refer: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex
LockFileEx = kernel32.LockFileEx
LockFileEx.argtypes = [
HANDLE,
DWORD,
DWORD,
DWORD,
DWORD,
POINTER(OVERLAPPED),
]
LockFileEx.restype = BOOL
# Refer: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-unlockfile
UnlockFileEx = kernel32.UnlockFileEx
UnlockFileEx.argtypes = [
HANDLE,
DWORD,
DWORD,
DWORD,
POINTER(OVERLAPPED),
]
UnlockFileEx.restype = BOOL
# Errors/flags
GetLastError = kernel32.GetLastError
ERROR_LOCK_VIOLATION = 33
| 22.275
| 89
| 0.763187
|
b6e4170872dc33f549152d2f62bab2cd1878ca00
| 6,067
|
py
|
Python
|
tests/test.py
|
TakashiAihara/docker-selenium-arm64
|
467e189edd40eeaf31320a981fe2f24d28b1e786
|
[
"RSA-MD",
"Apache-1.1"
] | null | null | null |
tests/test.py
|
TakashiAihara/docker-selenium-arm64
|
467e189edd40eeaf31320a981fe2f24d28b1e786
|
[
"RSA-MD",
"Apache-1.1"
] | null | null | null |
tests/test.py
|
TakashiAihara/docker-selenium-arm64
|
467e189edd40eeaf31320a981fe2f24d28b1e786
|
[
"RSA-MD",
"Apache-1.1"
] | null | null | null |
import os
import docker
import unittest
import logging
import sys
import random
from docker.errors import NotFound
# LOGGING #
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
# Docker Client
client = docker.from_env()
NAMESPACE = os.environ.get('NAMESPACE')
VERSION = os.environ.get('VERSION')
USE_RANDOM_USER_ID = os.environ.get('USE_RANDOM_USER_ID')
http_proxy = os.environ.get('http_proxy', '')
https_proxy = os.environ.get('https_proxy', '')
no_proxy = os.environ.get('no_proxy', '')
IMAGE_NAME_MAP = {
# Hub
'Hub': 'hub',
# Chrome Images
'NodeChrome': 'node-chrome',
'StandaloneChrome': 'standalone-chrome',
# Firefox Images
'NodeFirefox': 'node-firefox',
'StandaloneFirefox': 'standalone-firefox',
}
TEST_NAME_MAP = {
# Chrome Images
'NodeChrome': 'ChromeTests',
'StandaloneChrome': 'ChromeTests',
# Firefox Images
'NodeFirefox': 'FirefoxTests',
'StandaloneFirefox': 'FirefoxTests',
}
def launch_hub(network_name):
"""
Launch the hub
:return: the hub ID
"""
logger.info("Launching Hub...")
existing_hub = None
try:
existing_hub = client.containers.get('selenium-hub')
except NotFound:
pass
if existing_hub:
logger.debug("hub already exists. removing.")
if existing_hub.status == 'running':
logger.debug("hub is running. Killing")
existing_hub.kill()
logger.debug("hub killed")
existing_hub.remove()
logger.debug("hub removed")
ports = {'4442': 4442, '4443': 4443, '4444': 4444}
if use_random_user_id:
hub_container_id = launch_container('Hub', network=network_name, name="selenium-hub", ports=ports, user=random_user_id)
else:
hub_container_id = launch_container('Hub', network=network_name, name="selenium-hub", ports=ports)
logger.info("Hub Launched")
return hub_container_id
def create_network(network_name):
client.networks.create(network_name, driver="bridge")
def prune_networks():
client.networks.prune()
def launch_container(container, **kwargs):
"""
Launch a specific container
:param container:
:return: the container ID
"""
# Build the container if it doesn't exist
logger.info("Building %s container..." % container)
client.images.build(path='../%s' % container,
tag="%s/%s:%s" % (NAMESPACE, IMAGE_NAME_MAP[container], VERSION),
rm=True)
logger.info("Done building %s" % container)
# Run the container
logger.info("Running %s container..." % container)
# Merging env vars
environment = {
'http_proxy': http_proxy,
'https_proxy': https_proxy,
'no_proxy': no_proxy,
'HUB_HOST': 'selenium-hub'
}
container_id = client.containers.run("%s/%s:%s" % (NAMESPACE, IMAGE_NAME_MAP[container], VERSION),
detach=True,
environment=environment,
**kwargs).short_id
logger.info("%s up and running" % container)
return container_id
if __name__ == '__main__':
# The container to test against
image = sys.argv[1]
use_random_user_id = USE_RANDOM_USER_ID == 'true'
random_user_id = random.randint(100000,2147483647)
if use_random_user_id:
logger.info("Running tests with a random user ID -> %s" % random_user_id)
standalone = 'standalone' in image.lower()
# Flag for failure (for posterity)
failed = False
logger.info('========== Starting %s Container ==========' % image)
if standalone:
"""
Standalone Configuration
"""
smoke_test_class = 'StandaloneTest'
if use_random_user_id:
test_container_id = launch_container(image, ports={'4444': 4444}, user=random_user_id)
else:
test_container_id = launch_container(image, ports={'4444': 4444})
else:
"""
Hub / Node Configuration
"""
smoke_test_class = 'NodeTest'
prune_networks()
create_network("grid")
hub_id = launch_hub("grid")
ports = {'5555': 5555}
if use_random_user_id:
test_container_id = launch_container(image, network='grid', ports=ports, user=random_user_id)
else:
test_container_id = launch_container(image, network='grid', ports=ports)
prune_networks()
logger.info('========== / Containers ready to go ==========')
try:
# Smoke tests
logger.info('*********** Running smoke tests %s Tests **********' % image)
image_class = "%sTest" % image
test_class = getattr(__import__('SmokeTests', fromlist=[smoke_test_class]), smoke_test_class)
suite = unittest.TestLoader().loadTestsFromTestCase(test_class)
test_runner = unittest.TextTestRunner(verbosity=3)
failed = not test_runner.run(suite).wasSuccessful()
except Exception as e:
logger.fatal(e)
failed = True
try:
# Run Selenium tests
logger.info('*********** Running Selenium tests %s Tests **********' % image)
test_class = getattr(__import__('SeleniumTests', fromlist=[TEST_NAME_MAP[image]]), TEST_NAME_MAP[image])
suite = unittest.TestLoader().loadTestsFromTestCase(test_class)
test_runner = unittest.TextTestRunner(verbosity=3)
failed = not test_runner.run(suite).wasSuccessful()
except Exception as e:
logger.fatal(e)
failed = True
logger.info("Cleaning up...")
test_container = client.containers.get(test_container_id)
test_container.kill()
test_container.remove()
if standalone:
logger.info("Standalone Cleaned up")
else:
# Kill the launched hub
hub = client.containers.get(hub_id)
hub.kill()
hub.remove()
logger.info("Hub / Node Cleaned up")
if failed:
exit(1)
| 30.034653
| 127
| 0.623702
|
45bedfbf3d37c6c45e8e12cb72e9678ba10a9596
| 17,393
|
py
|
Python
|
tests/providers/gcp/google_kubernetes_engine_test.py
|
jovial/PerfKitBenchmarker
|
ec0b44f3462cedf7e15e4d67263659afaa136162
|
[
"Apache-2.0"
] | null | null | null |
tests/providers/gcp/google_kubernetes_engine_test.py
|
jovial/PerfKitBenchmarker
|
ec0b44f3462cedf7e15e4d67263659afaa136162
|
[
"Apache-2.0"
] | null | null | null |
tests/providers/gcp/google_kubernetes_engine_test.py
|
jovial/PerfKitBenchmarker
|
ec0b44f3462cedf7e15e4d67263659afaa136162
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for perfkitbenchmarker.providers.gcp.google_kubernetes_engine."""
# pylint: disable=not-context-manager
import os
import unittest
from unittest import mock
from absl import flags as flgs
import contextlib2
from perfkitbenchmarker import container_service
from perfkitbenchmarker import data
from perfkitbenchmarker import errors
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.configs import benchmark_config_spec
from perfkitbenchmarker.providers.gcp import gce_network
from perfkitbenchmarker.providers.gcp import google_kubernetes_engine
from perfkitbenchmarker.providers.gcp import util
from tests import pkb_common_test_case
from six.moves import builtins
FLAGS = flgs.FLAGS
_COMPONENT = 'test_component'
_RUN_URI = 'fake-urn-uri'
_NVIDIA_DRIVER_SETUP_DAEMON_SET_SCRIPT = 'https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/nvidia-driver-installer/cos/daemonset-preloaded.yaml'
_NVIDIA_UNRESTRICTED_PERMISSIONS_DAEMON_SET = 'nvidia_unrestricted_permissions_daemonset.yml'
_INSTANCE_GROUPS_LIST_OUTPUT = (
'../../../tests/data/gcloud_compute_instance_groups_list_instances.json')
_NODE_POOLS_LIST_OUTPUT = (
'../../../tests/data/gcloud_container_node_pools_list.json')
@contextlib2.contextmanager
def patch_critical_objects(stdout='', stderr='', return_code=0, flags=FLAGS):
with contextlib2.ExitStack() as stack:
flags.gcloud_path = 'gcloud'
flags.run_uri = _RUN_URI
flags.data_search_paths = ''
stack.enter_context(mock.patch(builtins.__name__ + '.open'))
stack.enter_context(mock.patch(vm_util.__name__ + '.PrependTempDir'))
stack.enter_context(mock.patch(vm_util.__name__ + '.NamedTemporaryFile'))
stack.enter_context(
mock.patch(
util.__name__ + '.GetDefaultProject', return_value='fakeproject'))
stack.enter_context(
mock.patch(
util.__name__ + '.GetDefaultUser', return_value='fakeuser'))
stack.enter_context(
mock.patch(
gce_network.__name__ + '.GceFirewall.GetFirewall',
return_value='fakefirewall'))
stack.enter_context(
mock.patch(
gce_network.__name__ + '.GceNetwork.GetNetwork',
return_value=gce_network.GceNetwork(
gce_network.GceNetworkSpec('fakeproject'))))
retval = (stdout, stderr, return_code)
issue_command = stack.enter_context(
mock.patch(vm_util.__name__ + '.IssueCommand', return_value=retval))
yield issue_command
class GoogleKubernetesEngineCustomMachineTypeTestCase(
pkb_common_test_case.PkbCommonTestCase):
@staticmethod
def create_kubernetes_engine_spec():
kubernetes_engine_spec = benchmark_config_spec._ContainerClusterSpec(
'NAME', **{
'cloud': 'GCP',
'vm_spec': {
'GCP': {
'machine_type': {
'cpus': 4,
'memory': '1024MiB',
},
},
},
})
return kubernetes_engine_spec
def testCreate(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._Create()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud container clusters create', command_string)
self.assertIn('--machine-type custom-4-1024', command_string)
class GoogleKubernetesEngineTestCase(pkb_common_test_case.PkbCommonTestCase):
@staticmethod
def create_kubernetes_engine_spec():
kubernetes_engine_spec = benchmark_config_spec._ContainerClusterSpec(
'NAME', **{
'cloud': 'GCP',
'vm_spec': {
'GCP': {
'machine_type': 'fake-machine-type',
'zone': 'us-central1-a',
'min_cpu_platform': 'skylake',
'boot_disk_type': 'foo',
'boot_disk_size': 200,
'num_local_ssds': 2,
},
},
'vm_count': 2,
})
return kubernetes_engine_spec
def testCreate(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._Create()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud container clusters create', command_string)
self.assertIn('--num-nodes 2', command_string)
self.assertIn('--cluster-ipv4-cidr /19', command_string)
self.assertIn('--machine-type fake-machine-type', command_string)
self.assertIn('--zone us-central1-a', command_string)
self.assertIn('--min-cpu-platform skylake', command_string)
self.assertIn('--disk-size 200', command_string)
self.assertIn('--disk-type foo', command_string)
self.assertIn('--local-ssd-count 2', command_string)
def testCreateQuotaExceeded(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects(
stderr="""
message=Insufficient regional quota to satisfy request: resource "CPUS":
request requires '6400.0' and is short '5820.0'""",
return_code=1) as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
with self.assertRaises(
errors.Benchmarks.QuotaFailure):
cluster._Create()
self.assertEqual(issue_command.call_count, 1)
def testCreateResourcesExhausted(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects(
stderr="""
[ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS]:
Instance 'test' creation failed: The zone
'projects/artemis-prod/zones/us-central1-a' does not have enough
resources available to fulfill the request.""",
return_code=1) as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
with self.assertRaises(
errors.Benchmarks.InsufficientCapacityCloudFailure):
cluster._Create()
self.assertEqual(issue_command.call_count, 1)
def testPostCreate(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command, mock.patch.object(
container_service, 'RunKubectlCommand') as mock_kubectl_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._PostCreate()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn(
'gcloud container clusters get-credentials pkb-{0}'.format(_RUN_URI),
command_string)
self.assertIn('KUBECONFIG', issue_command.call_args[1]['env'])
self.assertEqual(mock_kubectl_command.call_count, 1)
def testDelete(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._Delete()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud container clusters delete pkb-{0}'.format(_RUN_URI),
command_string)
self.assertIn('--zone us-central1-a', command_string)
def testExists(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._Exists()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn(
'gcloud container clusters describe pkb-{0}'.format(_RUN_URI),
command_string)
def testGetResourceMetadata(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
metadata = cluster.GetResourceMetadata()
self.assertEqual(issue_command.call_count, 0)
self.assertContainsSubset(
{
'project': 'fakeproject',
'gce_local_ssd_count': 2,
'gce_local_ssd_interface': 'SCSI',
'machine_type': 'fake-machine-type',
'boot_disk_type': 'foo',
'boot_disk_size': 200,
'cloud': 'GCP',
'cluster_type': 'Kubernetes',
'zone': 'us-central1-a',
'size': 2,
'container_cluster_version': 'latest'
}, metadata)
def testCidrCalculations(self):
self.assertEqual(google_kubernetes_engine._CalculateCidrSize(1), 19)
self.assertEqual(google_kubernetes_engine._CalculateCidrSize(16), 19)
self.assertEqual(google_kubernetes_engine._CalculateCidrSize(17), 18)
self.assertEqual(google_kubernetes_engine._CalculateCidrSize(48), 18)
self.assertEqual(google_kubernetes_engine._CalculateCidrSize(49), 17)
self.assertEqual(google_kubernetes_engine._CalculateCidrSize(250), 15)
class GoogleKubernetesEngineAutoscalingTestCase(
pkb_common_test_case.PkbCommonTestCase):
@staticmethod
def create_kubernetes_engine_spec():
kubernetes_engine_spec = benchmark_config_spec._ContainerClusterSpec(
'NAME', **{
'cloud': 'GCP',
'vm_spec': {
'GCP': {
'machine_type': 'fake-machine-type',
'zone': 'us-central1-a',
},
},
'min_vm_count': 1,
'vm_count': 2,
'max_vm_count': 30,
})
return kubernetes_engine_spec
def testCreate(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._Create()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud container clusters create', command_string)
self.assertIn('--enable-autoscaling', command_string)
self.assertIn('--min-nodes 1', command_string)
self.assertIn('--num-nodes 2', command_string)
self.assertIn('--max-nodes 30', command_string)
self.assertIn('--cluster-ipv4-cidr /18', command_string)
def testGetResourceMetadata(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
metadata = cluster.GetResourceMetadata()
self.assertEqual(issue_command.call_count, 0)
self.assertContainsSubset(
{
'project': 'fakeproject',
'cloud': 'GCP',
'cluster_type': 'Kubernetes',
'min_size': 1,
'size': 2,
'max_size': 3
}, metadata)
class GoogleKubernetesEngineVersionFlagTestCase(
pkb_common_test_case.PkbCommonTestCase):
@staticmethod
def create_kubernetes_engine_spec():
kubernetes_engine_spec = benchmark_config_spec._ContainerClusterSpec(
'NAME', **{
'cloud': 'GCP',
'vm_spec': {
'GCP': {
'machine_type': 'fake-machine-type',
},
},
})
return kubernetes_engine_spec
def testCreateCustomVersion(self):
spec = self.create_kubernetes_engine_spec()
FLAGS.container_cluster_version = 'fake-version'
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._Create()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('--cluster-version fake-version', command_string)
def testCreateDefaultVersion(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._Create()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('--cluster-version latest', command_string)
class GoogleKubernetesEngineWithGpusTestCase(
pkb_common_test_case.PkbCommonTestCase):
@staticmethod
def create_kubernetes_engine_spec():
kubernetes_engine_spec = benchmark_config_spec._ContainerClusterSpec(
'NAME', **{
'cloud': 'GCP',
'vm_spec': {
'GCP': {
'machine_type': 'fake-machine-type',
'gpu_type': 'k80',
'gpu_count': 2,
},
},
'vm_count': 2,
})
return kubernetes_engine_spec
def testCreate(self):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._Create()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud container clusters create', command_string)
self.assertIn('--num-nodes 2', command_string)
self.assertIn('--machine-type fake-machine-type', command_string)
self.assertIn('--accelerator type=nvidia-tesla-k80,count=2',
command_string)
@mock.patch('perfkitbenchmarker.kubernetes_helper.CreateFromFile')
def testPostCreate(self, create_from_file_patch):
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects() as issue_command, mock.patch.object(
container_service, 'RunKubectlCommand') as mock_kubectl_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
cluster._PostCreate()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn(
'gcloud container clusters get-credentials pkb-{0}'.format(_RUN_URI),
command_string)
self.assertIn('KUBECONFIG', issue_command.call_args[1]['env'])
self.assertEqual(mock_kubectl_command.call_count, 1)
expected_args_to_create_from_file = (
_NVIDIA_DRIVER_SETUP_DAEMON_SET_SCRIPT,
data.ResourcePath(
_NVIDIA_UNRESTRICTED_PERMISSIONS_DAEMON_SET)
)
expected_calls = [mock.call(arg)
for arg in expected_args_to_create_from_file]
# Assert that create_from_file was called twice,
# and that the args were as expected (should be the NVIDIA
# driver setup daemon set, followed by the
# NVIDIA unrestricted permissions daemon set.
create_from_file_patch.assert_has_calls(expected_calls)
class GoogleKubernetesEngineGetNodesTestCase(GoogleKubernetesEngineTestCase):
def testGetInstancesFromInstanceGroups(self):
instance_group_name = 'gke-pkb-0c47e6fa-default-pool-167d73ee-grp'
path = os.path.join(os.path.dirname(__file__), _INSTANCE_GROUPS_LIST_OUTPUT)
output = open(path).read()
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects(stdout=output) as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
instances = cluster._GetInstancesFromInstanceGroup(instance_group_name)
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn(
'gcloud compute instance-groups list-instances '
'gke-pkb-0c47e6fa-default-pool-167d73ee-grp', command_string)
expected = set([
'gke-pkb-0c47e6fa-default-pool-167d73ee-hmwk',
'gke-pkb-0c47e6fa-default-pool-167d73ee-t854'
])
self.assertEqual(expected, set(instances)) # order doesn't matter
def testGetInstanceGroups(self):
path = os.path.join(os.path.dirname(__file__), _NODE_POOLS_LIST_OUTPUT)
output = open(path).read()
spec = self.create_kubernetes_engine_spec()
with patch_critical_objects(stdout=output) as issue_command:
cluster = google_kubernetes_engine.GkeCluster(spec)
instance_groups = cluster._GetInstanceGroups()
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud container node-pools list', command_string)
self.assertIn('--cluster', command_string)
expected = set([
'gke-pkb-0c47e6fa-default-pool-167d73ee-grp',
'gke-pkb-0c47e6fa-test-efea7796-grp'
])
self.assertEqual(expected, set(instance_groups)) # order doesn't matter
if __name__ == '__main__':
unittest.main()
| 38.737194
| 186
| 0.685793
|
ba77555db065a93329bd62fc627f3d25112a835d
| 490
|
py
|
Python
|
src/helper.py
|
ypinzon/ClinicalTrialsWGETL
|
4edd6b6868915ab8e3408f6e8f6e625dd3003d40
|
[
"Apache-2.0"
] | null | null | null |
src/helper.py
|
ypinzon/ClinicalTrialsWGETL
|
4edd6b6868915ab8e3408f6e8f6e625dd3003d40
|
[
"Apache-2.0"
] | null | null | null |
src/helper.py
|
ypinzon/ClinicalTrialsWGETL
|
4edd6b6868915ab8e3408f6e8f6e625dd3003d40
|
[
"Apache-2.0"
] | null | null | null |
import os
def get_fnames(path):
list_of_fnames = []
for dirname, dirs, files in os.walk(path, topdown=True):
for fname in files:
if fname.endswith('.csv'):
list_of_fnames.append((os.path.join(dirname, fname), fname))
return list_of_fnames
def run_script(spark, scriptname):
with open(scriptname, 'r') as script:
queries = script.read()
queries = queries.split(';')[: -1]
for query in queries:
spark.sql(query)
| 25.789474
| 76
| 0.618367
|
fdd78c5e43ef9789ae9bb05559ab277223f084d2
| 278
|
py
|
Python
|
autodriver/src/autodriver/serialcomm/params.py
|
rel1c/robocar
|
6e83391b84873781c839cfc57a9fc1a49f641dbb
|
[
"MIT"
] | null | null | null |
autodriver/src/autodriver/serialcomm/params.py
|
rel1c/robocar
|
6e83391b84873781c839cfc57a9fc1a49f641dbb
|
[
"MIT"
] | null | null | null |
autodriver/src/autodriver/serialcomm/params.py
|
rel1c/robocar
|
6e83391b84873781c839cfc57a9fc1a49f641dbb
|
[
"MIT"
] | null | null | null |
# File: params.py
# Desc: A collection of predefined constants governing control for the car.
# Copyright (c) 2020 Adam Peterson
SERIAL_PATH = '/dev/ttyACM0'
BAUD_RATE = 9600
STEERING_MID = 90
STEERING_MIN = 65
STEERING_MAX = 115
MOTOR_MAX = 255
MOTOR_MIN = 25
DEBUG = True
| 17.375
| 75
| 0.748201
|
be08191ae114ecdab075b2e379585375feb12a6c
| 18,822
|
py
|
Python
|
buildscripts/tests/resmokelib/powercycle/test_remote_operations.py
|
benety/mongo
|
203430ac9559f82ca01e3cbb3b0e09149fec0835
|
[
"Apache-2.0"
] | null | null | null |
buildscripts/tests/resmokelib/powercycle/test_remote_operations.py
|
benety/mongo
|
203430ac9559f82ca01e3cbb3b0e09149fec0835
|
[
"Apache-2.0"
] | null | null | null |
buildscripts/tests/resmokelib/powercycle/test_remote_operations.py
|
benety/mongo
|
203430ac9559f82ca01e3cbb3b0e09149fec0835
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python3
"""Unit test for buildscripts/remote_operations.py.
Note - Tests require sshd to be enabled on localhost with paswordless login
and can fail otherwise."""
import os
import shutil
import tempfile
import time
import unittest
from buildscripts.resmokelib.powercycle.lib import remote_operations as rop
# pylint: disable=invalid-name,missing-docstring,protected-access
class RemoteOperationsTestCase(unittest.TestCase):
def setUp(self):
self.temp_local_dir = tempfile.mkdtemp()
self.temp_remote_dir = tempfile.mkdtemp()
self.rop = rop.RemoteOperations(user_host="localhost")
self.rop_use_shell = rop.RemoteOperations(user_host="localhost", use_shell=True)
self.rop_sh_shell_binary = rop.RemoteOperations(user_host="localhost",
shell_binary="/bin/sh")
self.rop_ssh_opts = rop.RemoteOperations(
user_host="localhost",
ssh_connection_options="-v -o ConnectTimeout=10 -o ConnectionAttempts=10")
def tearDown(self):
shutil.rmtree(self.temp_local_dir, ignore_errors=True)
shutil.rmtree(self.temp_remote_dir, ignore_errors=True)
class RemoteOperationConnection(RemoteOperationsTestCase):
@unittest.skip("Known broken. SERVER-48969 tracks re-enabling.")
def runTest(self):
self.assertTrue(self.rop.access_established())
ret, buff = self.rop.access_info()
self.assertEqual(0, ret)
# Invalid host
remote_op = rop.RemoteOperations(user_host="badhost")
ret, buff = remote_op.access_info()
self.assertFalse(remote_op.access_established())
self.assertEqual(255, ret)
self.assertIsNotNone(buff)
# Valid host with invalid ssh options
ssh_connection_options = "-o invalid"
remote_op = rop.RemoteOperations(user_host="localhost",
ssh_connection_options=ssh_connection_options)
ret, buff = remote_op.access_info()
self.assertFalse(remote_op.access_established())
self.assertNotEqual(0, ret)
self.assertIsNotNone(buff)
ssh_options = "--invalid"
remote_op = rop.RemoteOperations(user_host="localhost", ssh_options=ssh_options)
ret, buff = remote_op.access_info()
self.assertFalse(remote_op.access_established())
self.assertNotEqual(0, ret)
self.assertIsNotNone(buff)
# Valid host with valid ssh options
ssh_connection_options = "-v -o ConnectTimeout=10 -o ConnectionAttempts=10"
remote_op = rop.RemoteOperations(user_host="localhost",
ssh_connection_options=ssh_connection_options)
ret, buff = remote_op.access_info()
self.assertTrue(remote_op.access_established())
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ssh_options = "-v -o ConnectTimeout=10 -o ConnectionAttempts=10"
remote_op = rop.RemoteOperations(user_host="localhost", ssh_options=ssh_options)
ret, buff = remote_op.access_info()
self.assertTrue(remote_op.access_established())
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ssh_connection_options = "-v -o ConnectTimeout=10 -o ConnectionAttempts=10"
ssh_options = "-t"
remote_op = rop.RemoteOperations(user_host="localhost",
ssh_connection_options=ssh_connection_options,
ssh_options=ssh_options)
ret, buff = remote_op.access_info()
self.assertTrue(remote_op.access_established())
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
class RemoteOperationShell(RemoteOperationsTestCase):
@unittest.skip("Known broken. SERVER-48969 tracks re-enabling.")
def runTest(self): # pylint: disable=too-many-statements
# Shell connect
ret, buff = self.rop.shell("uname")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_use_shell.shell("uname")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_sh_shell_binary.shell("uname")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop.operation("shell", "uname")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
# Invalid command
ret, buff = self.rop.shell("invalid_command")
self.assertNotEqual(0, ret)
self.assertIsNotNone(buff)
# Multiple commands
ret, buff = self.rop.shell("date; whoami; ls")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_use_shell.shell("date; whoami; ls")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_sh_shell_binary.shell("date; whoami; ls")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_ssh_opts.shell("date; whoami; ls")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
# Command with single quotes
ret, buff = self.rop.shell("echo 'hello there' | grep 'hello'")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_use_shell.shell("echo 'hello there' | grep 'hello'")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
# Multiple commands with escaped single quotes
ret, buff = self.rop.shell("echo \"hello \'dolly\'\"; pwd; echo \"goodbye \'charlie\'\"")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_use_shell.shell(
"echo \"hello \'dolly\'\"; pwd; echo \"goodbye \'charlie\'\"")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
# Command with escaped double quotes
ret, buff = self.rop.shell("echo \"hello there\" | grep \"hello\"")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_use_shell.shell("echo \"hello there\" | grep \"hello\"")
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
# Command with directory and pipe
ret, buff = self.rop.shell("touch {dir}/{file}; ls {dir} | grep {file}".format(
file=time.time(), dir="/tmp"))
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
ret, buff = self.rop_use_shell.shell("touch {dir}/{file}; ls {dir} | grep {file}".format(
file=time.time(), dir="/tmp"))
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
class RemoteOperationCopyTo(RemoteOperationsTestCase):
@unittest.skip("Known broken. SERVER-48969 tracks re-enabling.")
def runTest(self): # pylint: disable=too-many-statements
# Copy to remote
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
ret, buff = self.rop.copy_to(l_temp_path, self.temp_remote_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
r_temp_path = os.path.join(self.temp_remote_dir, l_temp_file)
self.assertTrue(os.path.isfile(r_temp_path))
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
ret, buff = self.rop_use_shell.copy_to(l_temp_path, self.temp_remote_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
r_temp_path = os.path.join(self.temp_remote_dir, l_temp_file)
self.assertTrue(os.path.isfile(r_temp_path))
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
ret, buff = self.rop.operation("copy_to", l_temp_path, self.temp_remote_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
self.assertTrue(os.path.isfile(r_temp_path))
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
ret, buff = self.rop_ssh_opts.operation("copy_to", l_temp_path, self.temp_remote_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
self.assertTrue(os.path.isfile(r_temp_path))
# Copy multiple files to remote
num_files = 3
l_temp_files = []
for i in range(num_files):
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
l_temp_files.append(l_temp_path)
ret, buff = self.rop.copy_to(" ".join(l_temp_files), self.temp_remote_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
for i in range(num_files):
r_temp_path = os.path.join(self.temp_remote_dir, os.path.basename(l_temp_files[i]))
self.assertTrue(os.path.isfile(r_temp_path))
num_files = 3
l_temp_files = []
for i in range(num_files):
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
l_temp_files.append(l_temp_path)
ret, buff = self.rop_use_shell.copy_to(" ".join(l_temp_files), self.temp_remote_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
for i in range(num_files):
r_temp_path = os.path.join(self.temp_remote_dir, os.path.basename(l_temp_files[i]))
self.assertTrue(os.path.isfile(r_temp_path))
# Copy to remote without directory
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
ret, buff = self.rop.copy_to(l_temp_path)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
r_temp_path = os.path.join(os.environ["HOME"], l_temp_file)
self.assertTrue(os.path.isfile(r_temp_path))
os.remove(r_temp_path)
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
ret, buff = self.rop_use_shell.copy_to(l_temp_path)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
r_temp_path = os.path.join(os.environ["HOME"], l_temp_file)
self.assertTrue(os.path.isfile(r_temp_path))
os.remove(r_temp_path)
# Copy to remote with space in file name, note it must be quoted.
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir, prefix="filename with space")[1]
l_temp_file = os.path.basename(l_temp_path)
ret, buff = self.rop.copy_to("'{}'".format(l_temp_path))
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
r_temp_path = os.path.join(os.environ["HOME"], l_temp_file)
self.assertTrue(os.path.isfile(r_temp_path))
os.remove(r_temp_path)
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir, prefix="filename with space")[1]
l_temp_file = os.path.basename(l_temp_path)
ret, buff = self.rop_use_shell.copy_to("'{}'".format(l_temp_path))
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
r_temp_path = os.path.join(os.environ["HOME"], l_temp_file)
self.assertTrue(os.path.isfile(r_temp_path))
os.remove(r_temp_path)
# Valid scp options
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
l_temp_file = os.path.basename(l_temp_path)
scp_options = "-l 5000"
remote_op = rop.RemoteOperations(user_host="localhost", scp_options=scp_options)
ret, buff = remote_op.copy_to(l_temp_path, self.temp_remote_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
r_temp_path = os.path.join(self.temp_remote_dir, l_temp_file)
self.assertTrue(os.path.isfile(r_temp_path))
# Invalid scp options
l_temp_path = tempfile.mkstemp(dir=self.temp_local_dir)[1]
scp_options = "--invalid"
remote_op = rop.RemoteOperations(user_host="localhost", scp_options=scp_options)
ret, buff = remote_op.copy_to(l_temp_path, self.temp_remote_dir)
self.assertNotEqual(0, ret)
self.assertIsNotNone(buff)
class RemoteOperationCopyFrom(RemoteOperationsTestCase):
@unittest.skip("Known broken. SERVER-48969 tracks re-enabling.")
def runTest(self): # pylint: disable=too-many-statements
# Copy from remote
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
r_temp_file = os.path.basename(r_temp_path)
ret, buff = self.rop.copy_from(r_temp_path, self.temp_local_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
l_temp_path = os.path.join(self.temp_local_dir, r_temp_file)
self.assertTrue(os.path.isfile(l_temp_path))
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
r_temp_file = os.path.basename(r_temp_path)
ret, buff = self.rop_use_shell.copy_from(r_temp_path, self.temp_local_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
l_temp_path = os.path.join(self.temp_local_dir, r_temp_file)
self.assertTrue(os.path.isfile(l_temp_path))
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
r_temp_file = os.path.basename(r_temp_path)
ret, buff = self.rop_ssh_opts.copy_from(r_temp_path, self.temp_local_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
l_temp_path = os.path.join(self.temp_local_dir, r_temp_file)
self.assertTrue(os.path.isfile(l_temp_path))
# Copy from remote without directory
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
r_temp_file = os.path.basename(r_temp_path)
ret, buff = self.rop.copy_from(r_temp_path)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
self.assertTrue(os.path.isfile(r_temp_file))
os.remove(r_temp_file)
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
r_temp_file = os.path.basename(r_temp_path)
ret, buff = self.rop_use_shell.copy_from(r_temp_path)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
self.assertTrue(os.path.isfile(r_temp_file))
os.remove(r_temp_file)
# Copy from remote with space in file name, note it must be quoted.
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir, prefix="filename with space")[1]
r_temp_file = os.path.basename(r_temp_path)
ret, buff = self.rop.copy_from("'{}'".format(r_temp_path))
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
self.assertTrue(os.path.isfile(r_temp_file))
os.remove(r_temp_file)
# Copy multiple files from remote
num_files = 3
r_temp_files = []
for i in range(num_files):
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
r_temp_file = os.path.basename(r_temp_path)
r_temp_files.append(r_temp_path)
ret, buff = self.rop.copy_from(" ".join(r_temp_files), self.temp_local_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
for i in range(num_files):
basefile_name = os.path.basename(r_temp_files[i])
l_temp_path = os.path.join(self.temp_local_dir, basefile_name)
self.assertTrue(os.path.isfile(l_temp_path))
num_files = 3
r_temp_files = []
for i in range(num_files):
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
r_temp_file = os.path.basename(r_temp_path)
r_temp_files.append(r_temp_path)
ret, buff = self.rop_use_shell.copy_from(" ".join(r_temp_files), self.temp_local_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
for i in range(num_files):
basefile_name = os.path.basename(r_temp_files[i])
l_temp_path = os.path.join(self.temp_local_dir, basefile_name)
self.assertTrue(os.path.isfile(l_temp_path))
# Copy files from remote with wilcard
num_files = 3
r_temp_files = []
for i in range(num_files):
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir, prefix="wild1")[1]
r_temp_file = os.path.basename(r_temp_path)
r_temp_files.append(r_temp_path)
r_temp_path = os.path.join(self.temp_remote_dir, "wild1*")
ret, buff = self.rop.copy_from(r_temp_path, self.temp_local_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
for i in range(num_files):
l_temp_path = os.path.join(self.temp_local_dir, os.path.basename(r_temp_files[i]))
self.assertTrue(os.path.isfile(l_temp_path))
num_files = 3
r_temp_files = []
for i in range(num_files):
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir, prefix="wild2")[1]
r_temp_file = os.path.basename(r_temp_path)
r_temp_files.append(r_temp_path)
r_temp_path = os.path.join(self.temp_remote_dir, "wild2*")
ret, buff = self.rop_use_shell.copy_from(r_temp_path, self.temp_local_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
for i in range(num_files):
l_temp_path = os.path.join(self.temp_local_dir, os.path.basename(r_temp_files[i]))
self.assertTrue(os.path.isfile(l_temp_path))
# Local directory does not exist.
self.assertRaises(ValueError, lambda: self.rop_use_shell.copy_from(r_temp_path, "bad_dir"))
# Valid scp options
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
r_temp_file = os.path.basename(r_temp_path)
scp_options = "-l 5000"
remote_op = rop.RemoteOperations(user_host="localhost", scp_options=scp_options)
ret, buff = remote_op.copy_from(r_temp_path, self.temp_local_dir)
self.assertEqual(0, ret)
self.assertIsNotNone(buff)
l_temp_path = os.path.join(self.temp_local_dir, r_temp_file)
self.assertTrue(os.path.isfile(l_temp_path))
# Invalid scp options
r_temp_path = tempfile.mkstemp(dir=self.temp_remote_dir)[1]
scp_options = "--invalid"
remote_op = rop.RemoteOperations(user_host="localhost", scp_options=scp_options)
ret, buff = remote_op.copy_from(r_temp_path, self.temp_local_dir)
self.assertNotEqual(0, ret)
self.assertIsNotNone(buff)
class RemoteOperation(RemoteOperationsTestCase):
@unittest.skip("Known broken. SERVER-48969 tracks re-enabling.")
def runTest(self):
# Invalid operation
self.assertRaises(ValueError, lambda: self.rop.operation("invalid", None))
| 43.070938
| 99
| 0.660769
|
8fca4f48c08246213c34d8d4508c87622d4ff97d
| 665
|
py
|
Python
|
manage.py
|
bitbloxhub/shorttalk
|
5adb79ddda2d32077e5a5b666df2f084aa883c2c
|
[
"0BSD"
] | null | null | null |
manage.py
|
bitbloxhub/shorttalk
|
5adb79ddda2d32077e5a5b666df2f084aa883c2c
|
[
"0BSD"
] | null | null | null |
manage.py
|
bitbloxhub/shorttalk
|
5adb79ddda2d32077e5a5b666df2f084aa883c2c
|
[
"0BSD"
] | null | null | null |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shorttalk.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| 28.913043
| 73
| 0.679699
|
e880f2c3ae1ab86c40ae7211041248107061808e
| 13,308
|
py
|
Python
|
cassiopeia/core/common.py
|
mikaeldui/cassiopeia
|
fb22e0dd2c71ae5e14c046379e49c8a44215e79d
|
[
"MIT"
] | null | null | null |
cassiopeia/core/common.py
|
mikaeldui/cassiopeia
|
fb22e0dd2c71ae5e14c046379e49c8a44215e79d
|
[
"MIT"
] | null | null | null |
cassiopeia/core/common.py
|
mikaeldui/cassiopeia
|
fb22e0dd2c71ae5e14c046379e49c8a44215e79d
|
[
"MIT"
] | null | null | null |
from abc import abstractmethod, abstractclassmethod
import types
from typing import Mapping, Set, Union, Optional, Type, Generator
import functools
import logging
from enum import Enum
import arrow
import datetime
import inspect
from merakicommons.ghost import Ghost, ghost_load_on as _ghost_load_on
from merakicommons.container import SearchableLazyList
from .. import configuration
from ..data import Region, Platform
import json # Can't use ujson here because of the encoder
LOGGER = logging.getLogger("core")
def ghost_load_on(method):
return _ghost_load_on(AttributeError)(method)
def get_latest_version(region: Union[Region, str], endpoint: Optional[str]):
from .staticdata.realm import Realms
if endpoint is not None:
return Realms(region=region).latest_versions[endpoint]
else:
return Realms(region=region).version
class CoreData(object):
@property
@abstractclassmethod
def _renamed(cls) -> Mapping[str, str]:
pass
def __init__(self, **kwargs):
self(**kwargs)
def __call__(self, **kwargs):
for key, value in kwargs.items():
new_key = self._renamed.get(key, key)
setattr(self, new_key, value)
return self
def to_dict(self):
d = {}
attrs = {attrname for attrname in dir(self)} - {
attrname for attrname in dir(self.__class__)
}
for attr in attrs:
v = getattr(self, attr)
if isinstance(v, CoreData):
v = v.to_dict()
elif hasattr(v, "__iter__") and not isinstance(v, str):
if isinstance(v, dict):
new_v = {}
for k, vi in v.items():
if isinstance(vi, CoreData):
new_v[k] = vi.to_dict()
else:
new_v[k] = vi
v = new_v
else:
v = [vi.to_dict() if isinstance(vi, CoreData) else vi for vi in v]
d[attr] = v
return d
class CoreDataList(list, CoreData):
def __str__(self):
return list.__str__(self)
def __init__(self, *args, **kwargs):
list.__init__(self, *args)
CoreData.__init__(self, **kwargs)
class CassiopeiaObject(object):
_renamed = {}
def __init__(self, **kwargs):
# Note: Dto names are not allowed to be passed in.
self._data = {_type: None for _type in self._data_types}
# Re-implement __call__ code here so that __call__ can be overridden in subclasses
results = {_type: {} for _type in self._data_types}
found = False
for key, value in kwargs.items():
# We don't know which type to put the piece of data under, so put it in any type that supports this key
for _type in self._data_types:
if issubclass(_type, CoreData) or key in dir(_type):
results[_type][key] = value
found = True
if not found:
# The user passed in a value that we don't know anything about -- raise a warning.
LOGGER.warning(
"When initializing {}, key `{}` is not in type(s) {}. Not set.".format(
self.__class__.__name__, key, self._data_types
)
)
# Now that we've parsed the data and know where to put it all, we can update our data.
for _type, insert_this in results.items():
if self._data[_type] is not None:
self._data[_type] = self._data[_type](**insert_this)
else:
self._data[_type] = _type(**insert_this)
def __str__(self) -> str:
# This is a bit strange because we'll print a list of dict-like objects rather than one joined dict, but we've decided it's appropriate.
result = {}
for _type, data in self._data.items():
result[str(_type)] = str(data)
return str(result).replace("\\'", "'")
@property
@abstractclassmethod
def _data_types(cls) -> Set[type]:
"""The `CoreData`_ types that belongs to this core type."""
pass
@classmethod
def from_data(cls, data: CoreData):
assert data is not None
self = cls()
if data.__class__ not in self._data_types:
raise TypeError(
"Wrong data type '{}' passed to '{}.from_data'".format(
data.__class__.__name__, self.__class__.__name__
)
)
self._data[data.__class__] = data
return self
def __call__(self, **kwargs) -> "CassiopeiaObject":
"""Updates `self` with `kwargs` and returns `self`.
Useful for updating default API parameters, for example:
for champion in cass.get_champions():
champion(champData={"tags"}).tags # only pulls the tag data
"""
# Update underlying data and deconstruct any Enums the user passed in.
results = {_type: {} for _type in self._data_types}
found = False
for key, value in kwargs.items():
# We don't know which type to put the piece of data under, so put it in any type that supports this key
for _type in self._data_types:
if issubclass(_type, CoreData) or key in dir(_type):
results[_type][key] = value
found = True
if not found:
# The user passed in a value that we don't know anything about -- raise a warning.
LOGGER.warning(
"When initializing {}, key `{}` is not in type(s) {}. Not set.".format(
self.__class__.__name__, key, self._data_types
)
)
# Now that we've parsed the data and know where to put it all, we can update our data.
for _type, insert_this in results.items():
if self._data[_type] is not None:
self._data[_type] = self._data[_type](**insert_this)
else:
self._data[_type] = _type(**insert_this)
return self
def to_dict(self):
d = {}
for data_type in self._data_types:
new = self._data[data_type].to_dict()
d.update(new)
return d
def to_json(self, **kwargs):
return json.dumps(self.to_dict(), cls=CassiopeiaJsonEncoder, **kwargs)
def __json__(self, **kwargs):
return self.to_json(**kwargs)
class GetFromPipeline(type):
def __call__(cls: "CassiopeiaPipelineObject", *args, **kwargs):
pipeline = configuration.settings.pipeline
query = cls.__get_query_from_kwargs__(**kwargs)
if (
hasattr(cls, "version")
and query.get("version", None) is None
and cls.__name__ not in ["Realms", "Match"]
):
query["version"] = get_latest_version(region=query["region"], endpoint=None)
return pipeline.get(cls, query=query)
class CassiopeiaPipelineObject(CassiopeiaObject, metaclass=GetFromPipeline):
@classmethod
def _construct_normally(cls, *args, **kwargs) -> "CassiopeiaObject":
# cls.__class__ will be this class's metaclass (GetFromPipeline), so supering that will find the metaclass's
# class, which is `type` in this case. Then `type`'s `__call__` will be called.
# This has the effect of skipping the GetFromPipeline instantiation, and defaulting to the normal class
# instantiation for the class.
# TODO I don't know how to handle includedData -> included_data for core...
if "includedData" in kwargs:
kwargs["included_data"] = kwargs.pop("includedData")
return super(cls.__class__, cls).__call__(*args, **kwargs)
@abstractmethod
def __get_query__(self):
pass
@classmethod
def __get_query_from_kwargs__(cls, **kwargs):
return kwargs
def __hash__(self):
stuff = sorted(self.__get_query__().items())
for i, (key, value) in enumerate(stuff):
if isinstance(value, set):
stuff[i] = (key, tuple(value))
return hash(tuple(stuff))
def __eq__(self, other: "CassiopeiaPipelineObject") -> bool:
if not isinstance(other, self.__class__): # Using isinstance here seems bad
return False
else:
return hash(self) == hash(other)
def __ne__(self, other: "CassiopeiaPipelineObject") -> bool:
return not self == other
class CassiopeiaGhost(CassiopeiaPipelineObject, Ghost):
def load(self, load_groups: Set = None) -> "CassiopeiaGhost":
if load_groups is None:
load_groups = self._Ghost__load_groups
if self._Ghost__all_loaded:
return self
self.__load__()
for load_group in load_groups:
self._Ghost__set_loaded(
load_group
) # __load__ doesn't trigger __set_loaded.
return self
def __load__(self, load_group: CoreData = None, load_groups: Set = None) -> None:
if load_groups is None:
load_groups = self._Ghost__load_groups
if load_group is None: # Load all groups
if self._Ghost__all_loaded:
raise ValueError("object has already been loaded.")
for group in load_groups:
if not self._Ghost__is_loaded(group):
self.__load__(group)
else: # Load the specific load group
if self._Ghost__is_loaded(load_group):
raise ValueError("object has already been loaded.")
query = self.__get_query__()
if (
hasattr(self.__class__, "version")
and "version" not in query
and self.__class__.__name__ not in ["Realms", "Match"]
):
query["version"] = get_latest_version(
region=query["region"], endpoint=None
)
data = configuration.settings.pipeline.get(
type=self._load_types[load_group], query=query
)
self.__load_hook__(load_group, data)
@property
def _load_types(cls):
return {t: t for t in cls._data_types}
@property
def _load_type(cls):
return cls
@classmethod
def from_data(
cls, data: CoreData, loaded_groups: Optional[Set[Type[CoreData]]] = None
):
assert data is not None
# Manually skip the CheckCache (well, all metaclass' __call__s) for ghost objects if they are
# created via this constructor.
self = cls._construct_normally()
# Make spots for the data and put it in
self._data = {_type: None for _type in self._data_types}
if data.__class__ not in self._data_types:
raise TypeError(
"Wrong data type '{}' passed to '{}.from_data'".format(
data.__class__.__name__, self.__class__.__name__
)
)
self._data[data.__class__] = data
# Set as loaded
if loaded_groups is None:
for load_group in self._Ghost__load_groups:
self._Ghost__set_loaded(load_group)
else:
for load_group in loaded_groups:
self._Ghost__set_loaded(load_group)
return self
def __load_hook__(self, load_group: CoreData, data: CoreData) -> None:
if not isinstance(data, CoreData):
raise TypeError(
"expected subclass of CoreData, got {cls}".format(cls=data.__class__)
)
self._data[load_group] = data
class CassiopeiaLazyList(SearchableLazyList, CassiopeiaPipelineObject):
def __init__(self, *args, **kwargs):
if "generator" in kwargs:
generator = kwargs.pop("generator")
else:
if len(args) == 1 and isinstance(args[0], types.GeneratorType):
generator = args[0]
else:
def generator(*args):
for arg in args:
yield arg
generator = generator(args)
SearchableLazyList.__init__(self, generator)
# Something feels very wrong; this is meant to work with MatchHistory.from_generator
if self.__class__ is not CassiopeiaLazyList:
self.__init__(**kwargs)
else:
CassiopeiaObject.__init__(self, **kwargs)
@classmethod
def from_data(cls, *args, **kwargs):
return cls._construct_normally(*args, **kwargs)
@classmethod
def from_generator(cls, generator: Generator, **kwargs):
self = cls.__new__(cls)
CassiopeiaLazyList.__init__(self, generator=generator, **kwargs)
return self
def __hash__(self):
return id(self)
def __str__(self):
return SearchableLazyList.__str__(self)
class CassiopeiaJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Enum):
return obj.name
elif isinstance(obj, (datetime.datetime, arrow.Arrow)):
return obj.isoformat()
elif isinstance(obj, datetime.timedelta):
return obj.seconds
return json.JSONEncoder.default(self, obj)
| 36.163043
| 144
| 0.592876
|
06be20eddfdbb8f127ad0de90c3d9e742d293f5a
| 2,275
|
py
|
Python
|
extensions/music.py
|
ggoncalopereira/JBB.py
|
e66419466cc6d35e134cceb8c8ad48102556658b
|
[
"MIT"
] | null | null | null |
extensions/music.py
|
ggoncalopereira/JBB.py
|
e66419466cc6d35e134cceb8c8ad48102556658b
|
[
"MIT"
] | null | null | null |
extensions/music.py
|
ggoncalopereira/JBB.py
|
e66419466cc6d35e134cceb8c8ad48102556658b
|
[
"MIT"
] | 1
|
2020-12-10T23:08:52.000Z
|
2020-12-10T23:08:52.000Z
|
import discord
from discord.ext import commands
import json
import subprocess
class Music(commands.Cog):
"""Play all great classics"""
def __init__(self, bot):
self.bot = bot
@commands.command(name='play',
description="play a given music",
brief="play a given music")
async def play(self, ctx, music):
#play a mp3 file
#check if user in voice channel
if ctx.message.author.voice_channel:
music = music.lower()
#check if requested music exists
if music in self.bot.musicMap:
#if bot is not connected to voice channel connect
if self.bot.voice_client == None:
voice = await self.bot.join_voice_channel(ctx.message.author.voice_channel)
self.bot.voice_client = voice
#if bot is connected and is playing dont play
if self.bot.player_client != None and self.bot.player_client.is_playing():
await ctx.send("Already Playing")
else:
#create player and play file
player = self.bot.voice_client.create_ffmpeg_player(self.bot.MUSIC_PATH + self.bot.musicMap[music])
self.bot.player_client = player
player.start()
else:
await ctx.send("Invalid Music")
else:
await ctx.send("You're not in a voice channel")
@commands.command(name='stop',
description="stop music and leave voice channel",
brief="stop music")
async def stop(self, ctx):
appInfo = await self.bot.application_info()
#check if user in voice channel
if ctx.message.author.voice_channel:
#cheack if bot in voice channel
if self.bot.voice_client:
#disconnect
await self.bot.voice_client.disconnect()
self.bot.voice_client = None
self.bot.player_client = None
else:
await ctx.send(appInfo.name + " not in a voice channel")
else:
await ctx.send("You're not in a voice channel")
def setup(bot):
bot.add_cog(Music(bot))
| 39.224138
| 119
| 0.565714
|
e983c856f1a3e6159aed10233248b08b33f282c9
| 3,678
|
py
|
Python
|
moveit_planners/pilz_industrial_motion_planner/test/unit_tests/launch/common_parameters.py
|
corycrean/moveit2
|
86a24a494264045883119c41a02188735f025f40
|
[
"BSD-3-Clause"
] | 1
|
2021-12-15T17:09:31.000Z
|
2021-12-15T17:09:31.000Z
|
moveit_planners/pilz_industrial_motion_planner/test/unit_tests/launch/common_parameters.py
|
corycrean/moveit2
|
86a24a494264045883119c41a02188735f025f40
|
[
"BSD-3-Clause"
] | 2
|
2021-08-24T15:45:42.000Z
|
2021-09-21T15:29:18.000Z
|
moveit_planners/pilz_industrial_motion_planner/test/unit_tests/launch/common_parameters.py
|
corycrean/moveit2
|
86a24a494264045883119c41a02188735f025f40
|
[
"BSD-3-Clause"
] | null | null | null |
from ament_index_python.packages import get_package_share_directory
import xacro
import yaml
import os
# TODO(henningkayser): Switch to ParameterBuilder once #591 is merged
# from moveit_configs_utils import MoveItConfigsBuilder
# from parameter_builder import ParameterBuilder
def _load_file(package_name, file_path):
package_path = get_package_share_directory(package_name)
absolute_file_path = os.path.join(package_path, file_path)
try:
with open(absolute_file_path, "r") as file:
return file.read()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None
def load_yaml(package_name, file_path):
# TODO(henningkayser): Switch to ParameterBuilder once #591 is merged
# return (
# ParameterBuilder(package_name)
# .yaml(file_path)
# .to_dict()
# )
package_path = get_package_share_directory(package_name)
absolute_file_path = os.path.join(package_path, file_path)
try:
with open(absolute_file_path, "r") as file:
return yaml.safe_load(file)
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None
class MoveItConfigs:
robot_description = {}
robot_description_semantic = {}
robot_description_kinematics = {}
robot_description_planning = {}
planning_plugin = {}
def load_moveit_config():
moveit_config_package_name = "moveit_resources_prbt_moveit_config"
description_package_name = "moveit_resources_prbt_support"
description_xacro_file = "urdf/prbt.xacro"
robot_description_semantic_file = "config/prbt.srdf.xacro"
robot_description_kinematics_file = "config/kinematics.yaml"
joint_limits_file = "config/joint_limits.yaml"
cartesian_limits_file = "config/cartesian_limits.yaml"
# TODO(henningkayser): Switch to MoveItConfigsBuilder once #591 is merged
# return (
# MoveItConfigsBuilder(moveit_config_package_name)
# .robot_description(
# file_path=get_package_share_directory(description_package_name)
# + "/" + description_xacro_file
# )
# .robot_description_semantic(file_path=robot_description_semantic_file)
# .robot_description_kinematics(file_path=robot_description_kinematics_file)
# .joint_limits(file_path=joint_limits_file)
# .cartesian_limits(file_path=cartesian_limits_file)
# .to_moveit_configs()
# )
configs = MoveItConfigs()
# planning_context
robot_description = xacro.process_file(
os.path.join(
get_package_share_directory(description_package_name),
description_xacro_file,
)
)
configs.robot_description = {"robot_description": robot_description.toxml()}
semantic_xacro = xacro.process_file(
os.path.join(
get_package_share_directory(moveit_config_package_name),
robot_description_semantic_file,
)
)
configs.robot_description_semantic = {
"robot_description_semantic": semantic_xacro.toxml()
}
configs.robot_description_kinematics = {
"robot_description_kinematics": load_yaml(
moveit_config_package_name, robot_description_kinematics_file
)
}
configs.robot_description_planning = {
"robot_description_planning": {
**load_yaml(moveit_config_package_name, joint_limits_file),
**load_yaml(moveit_config_package_name, cartesian_limits_file),
}
}
planning_plugin = {
"planning_plugin": "pilz_industrial_motion_planner::CommandPlanner"
}
return configs
| 33.436364
| 93
| 0.71615
|
a44467d56fed39f2693f5f9bc4859eada0839769
| 179
|
py
|
Python
|
python_data_utils/spark/ml/__init__.py
|
surajiyer/python-data-utils
|
d6e9bf81204a01545a3edb165c5724eb24f37c18
|
[
"MIT"
] | 4
|
2019-01-06T00:09:21.000Z
|
2022-01-28T06:03:13.000Z
|
python_data_utils/spark/ml/__init__.py
|
surajiyer/python-data-utils
|
d6e9bf81204a01545a3edb165c5724eb24f37c18
|
[
"MIT"
] | null | null | null |
python_data_utils/spark/ml/__init__.py
|
surajiyer/python-data-utils
|
d6e9bf81204a01545a3edb165c5724eb24f37c18
|
[
"MIT"
] | null | null | null |
from .base import (
BaseCVModel,
BinaryClassCVModel,
RegressionCVModel
)
from .randomforest import RandomForestBinaryModel
from .lightgbm import LightGBMRegressorModel
| 25.571429
| 49
| 0.810056
|
4a6a9225598aba55db4d996e3e02ff7d085cfe9d
| 460
|
py
|
Python
|
test/test_files.py
|
USGS-EROS/lcmap-merlin
|
692568e7e8e0bbb236e6e801b90abde8be8a05ea
|
[
"Unlicense"
] | null | null | null |
test/test_files.py
|
USGS-EROS/lcmap-merlin
|
692568e7e8e0bbb236e6e801b90abde8be8a05ea
|
[
"Unlicense"
] | null | null | null |
test/test_files.py
|
USGS-EROS/lcmap-merlin
|
692568e7e8e0bbb236e6e801b90abde8be8a05ea
|
[
"Unlicense"
] | 3
|
2018-05-08T14:51:56.000Z
|
2018-07-12T19:07:34.000Z
|
""" Functions for working with files in python """
from merlin import files
def test_read():
assert 1 > 0
def test_readb():
assert 1 > 0
def test_readlines():
assert 1 > 0
def test_readlinesb():
assert 1 > 0
def test_write():
assert 1 > 0
def test_writeb():
assert 1 > 0
def test_append():
assert 1 > 0
def test_appendb():
assert 1 > 0
def test_delete():
assert 1 > 0
def test_exists():
assert 1 > 0
| 10.697674
| 50
| 0.61087
|
59350eb7609b0c43250cb8cfdc0232cd4451af13
| 21,529
|
py
|
Python
|
pygr/blast.py
|
ctb/pygr
|
a3a3e68073834c20ddbdb27ed746baf8c73fef0a
|
[
"BSD-3-Clause"
] | 2
|
2015-03-07T13:20:50.000Z
|
2015-11-04T12:01:21.000Z
|
pygr/blast.py
|
ctb/pygr
|
a3a3e68073834c20ddbdb27ed746baf8c73fef0a
|
[
"BSD-3-Clause"
] | null | null | null |
pygr/blast.py
|
ctb/pygr
|
a3a3e68073834c20ddbdb27ed746baf8c73fef0a
|
[
"BSD-3-Clause"
] | null | null | null |
import os, tempfile, glob
import classutil, logger
from sequtil import *
from parse_blast import BlastHitParser
from seqdb import write_fasta, read_fasta
from nlmsa_utils import CoordsGroupStart, CoordsGroupEnd, CoordsToIntervals,\
EmptySlice
from annotation import AnnotationDB, TranslationAnnot, TranslationAnnotSlice
import cnestedlist
import translationDB
import UserDict
# NCBI HAS THE NASTY HABIT OF TREATING THE IDENTIFIER AS A BLOB INTO
# WHICH THEY STUFF FIELD AFTER FIELD... E.G. gi|1234567|foobarU|NT_1234567|...
# THIS JUST YANKS OUT THE SECOND ARGUMENT SEPARATED BY |
NCBI_ID_PARSER=lambda id:id.split('|')[1]
def blast_program(query_type,db_type):
progs= {DNA_SEQTYPE:{DNA_SEQTYPE:'blastn', PROTEIN_SEQTYPE:'blastx'},
PROTEIN_SEQTYPE:{DNA_SEQTYPE:'tblastn', PROTEIN_SEQTYPE:'blastp'}}
if query_type == RNA_SEQTYPE:
query_type = DNA_SEQTYPE
if db_type == RNA_SEQTYPE:
db_type = DNA_SEQTYPE
return progs[query_type][db_type]
def read_blast_alignment(ofile, srcDB, destDB, al=None, pipeline=None,
translateSrc=False, translateDest=False):
"""Apply sequence of transforms to read input from 'ofile'.
srcDB: database for finding query sequences from the blast input;
destDB: database for finding subject sequences from the blast input;
al, if not None, must be a writeable alignment object in which to
store the alignment intervals;
translateSrc=True forces creation of a TranslationDB representing
the possible 6-frames of srcDB (for blastx, tblastx);
translateDest=True forces creation of a TranslationDB representing
the possible 6-frames of destDB (for tblastn, tblastx).
If pipeline is not None, it must be a list of filter functions each
taking a single argument and returning an iterator or iterable result
object.
"""
p = BlastHitParser()
d = dict(id='src_id', start='src_start', stop='src_end', ori='src_ori',
idDest='dest_id', startDest='dest_start',
stopDest='dest_end', oriDest='dest_ori')
if translateSrc:
srcDB = translationDB.get_translation_db(srcDB)
if translateDest:
destDB = translationDB.get_translation_db(destDB)
cti = CoordsToIntervals(srcDB, destDB, d)
alignedIvals = cti(p.parse_file(ofile))
if pipeline is None:
result = save_interval_alignment(alignedIvals, al)
else: # apply all the filters in our pipeline one by one
result = alignedIvals
for f in pipeline:
result = f(result)
return result
def save_interval_alignment(alignedIvals, al=None):
"""Save alignedIvals to al, or a new in-memory NLMSA"""
needToBuild = False
if al is None:
al = cnestedlist.NLMSA('blasthits', 'memory', pairwiseMode=True,
bidirectional=False)
needToBuild = True
al.add_aligned_intervals(alignedIvals)
if needToBuild:
al.build()
return al
def start_blast(cmd, seq, seqString=None, seqDict=None, **kwargs):
"""Run blast and return results."""
p = classutil.FilePopen(cmd, stdin=classutil.PIPE, stdout=classutil.PIPE,
**kwargs)
if seqString is None:
seqString = seq
if seqDict is not None: # write all seqs to nonblocking ifile
for seqID, seq in seqDict.iteritems():
write_fasta(p.stdin, seq)
seqID = None
else: # just write one query sequence
seqID = write_fasta(p.stdin, seqString)
if p.wait(): # blast returned error code
raise OSError('command %s failed' % ' '.join(cmd))
return seqID, p
def process_blast(cmd, seq, blastDB, al=None, seqString=None, queryDB=None,
popenArgs={}, **kwargs):
"""Run blast and return an alignment."""
seqID,p = start_blast(cmd, seq, seqString, seqDict=queryDB, **popenArgs)
try:
if not queryDB: # need a query db for translation / parsing results
try:
queryDB = seq.db # use this sequence's database
except AttributeError:
queryDB = { seqID : seq } # construct a trivial "database"
al = read_blast_alignment(p.stdout, queryDB, blastDB, al, **kwargs)
finally:
p.close() # close our PIPE files
return al
def repeat_mask(seq, progname='RepeatMasker', opts=()):
'Run RepeatMasker on a sequence, return lowercase-masked string'
## fd, temppath = tempfile.mkstemp()
## ofile = os.fdopen(fd, 'w') # text file
p = classutil.FilePopen([progname] + list(opts), stdin=classutil.PIPE,
stdinFlag=None)
write_fasta(p.stdin, seq, reformatter=lambda x:x.upper()) # save uppercase!
try:
if p.wait():
raise OSError('command %s failed' % ' '.join(p.args[0]))
ifile = file(p._stdin_path + '.masked', 'rU') # text file
try:
for id,title,seq_masked in read_fasta(ifile):
break # JUST READ ONE SEQUENCE
finally:
ifile.close()
finally: # clean up our temp files no matter what happened
p.close() # close temp stdin file
for fpath in glob.glob(p._stdin_path + '.*'):
try:
os.remove(fpath)
except OSError:
pass
return seq_masked # ONLY THE REPEATS ARE IN LOWERCASE NOW
def warn_if_whitespace(filepath):
l = filepath.split() # check filepath for whitespace
if len(l) > 1 or len(l[0]) < len(filepath): # contains whitespace
logger.warn("""
Your sequence filepath contains whitespace characters:
%s
The NCBI formatdb (and blastall) programs cannot handle file paths
containing whitespace! This is a known NCBI formatdb / blastall bug.
Please use a path containing no whitespace characters!""" % filepath)
return True # signal caller that a warning was issued
class BlastMapping(object):
'Graph interface for mapping a sequence to homologs in a seq db via BLAST'
def __init__(self, seqDB, filepath=None, blastReady=False,
blastIndexPath=None, blastIndexDirs=None, verbose=True,
showFormatdbMessages=True, **kwargs):
'''seqDB: sequence database object to search for homologs
filepath: location of FASTA format file for the sequence database
blastReady: if True, ensure that BLAST index file ready to use
blastIndexPath: location of the BLAST index file
blastIndexDirs: list of directories for trying to build index in
'''
self.seqDB = seqDB
self.idIndex = BlastIDIndex(seqDB)
self.verbose = verbose
self.showFormatdbMessages = showFormatdbMessages
if filepath is not None:
self.filepath = filepath
else:
self.filepath = seqDB.filepath
if blastIndexPath is not None:
self.blastIndexPath = blastIndexPath
if blastIndexDirs is not None:
self.blastIndexDirs = blastIndexDirs
self.checkdb() # CHECK WHETHER BLAST INDEX FILE IS PRESENT...
if not self.blastReady and blastReady: # FORCE CONSTRUCTION OF BLAST DB
self.formatdb()
def __repr__(self):
return "<BlastMapping '%s'>" % (self.filepath)
def __getitem__(self, k):
'return NLMSASlice representing BLAST results'
al = self.__call__(k) # run BLAST & get NLMSA storing results
return al[k] # return NLMSASlice representing these results
def test_db_location(self, testpath):
'''check whether BLAST index files ready for use; return status.'''
if not os.access(testpath+'.nsd',os.R_OK) \
and not os.access(testpath+'.psd',os.R_OK) \
and not os.access(testpath+'.00.nsd',os.R_OK) \
and not os.access(testpath+'.00.psd',os.R_OK):
return False
else: # FOUND INDEX FILES IN THIS LOCATION
if testpath != self.filepath:
self.blastIndexPath = testpath
return True
def checkdb(self):
'look for blast index files in blastIndexPath, standard list of locations'
for testpath in self.blast_index_paths():
self.blastReady = self.test_db_location(testpath)
if self.blastReady:
break
return self.blastReady
def run_formatdb(self, testpath):
'ATTEMPT TO BUILD BLAST DATABASE INDEXES at testpath'
dirname = classutil.file_dirpath(testpath)
if not os.access(dirname, os.W_OK): # check if directory is writable
raise IOError('run_formatdb: directory %s is not writable!'
% dirname)
cmd = ['formatdb', '-i', self.filepath, '-n', testpath, '-o', 'T']
if self.seqDB._seqtype != PROTEIN_SEQTYPE:
cmd += ['-p', 'F'] # special flag required for nucleotide seqs
logger.info('Building index: ' + ' '.join(cmd))
if self.showFormatdbMessages:
kwargs = {}
else: # suppress formatdb messages by redirecting them
kwargs = dict(stdout=classutil.PIPE, stderr=classutil.PIPE)
if classutil.call_subprocess(cmd, **kwargs):
# bad exit code, so command failed
warn_if_whitespace(self.filepath) \
or warn_if_whitespace(testpath) # only issue one warning
raise OSError('command %s failed' % ' '.join(cmd))
self.blastReady=True
if testpath!=self.filepath:
self.blastIndexPath = testpath
def get_blast_index_path(self):
'get path to base name for BLAST index files'
try:
return self.blastIndexPath
except AttributeError:
return self.filepath
# DEFAULT: BUILD INDEX FILES IN self.filepath . HOME OR APPROPRIATE
# USER-/SYSTEM-SPECIFIC TEMPORARY DIRECTORY
blastIndexDirs = ['FILEPATH',os.getcwd,os.path.expanduser,
tempfile.gettempdir()]
def blast_index_paths(self):
'iterate over possible blast index directories'
try: # 1ST TRY ACTUAL SAVED LOCATION IF ANY
yield self.blastIndexPath
except AttributeError:
pass
for m in self.blastIndexDirs: # NOW TRY STANDARD LOCATIONS
if m=='FILEPATH':
yield self.filepath
continue
elif m == os.path.expanduser:
s = m('~') # GET HOME DIRECTORY
elif callable(m):
s = m()
else: # TREAT AS STRING
s = str(m)
yield os.path.join(s,os.path.basename(self.filepath))
def formatdb(self, filepath=None):
'try to build BLAST index files in an appropriate location'
if filepath is not None: # JUST USE THE SPECIFIED PATH
return self.run_formatdb(filepath)
notFirst = False
for testpath in self.blast_index_paths():
if notFirst:
logger.info('Trying next entry in self.blastIndexDirs...')
notFirst = True
try: # BUILD IN TARGET DIRECTORY
return self.run_formatdb(testpath)
except (IOError,OSError): # BUILD FAILED
pass
raise IOError, "cannot build BLAST database for %s" % (self.filepath,)
def raw_fasta_stream(self, ifile=None, idFilter=None):
'''Return a stream of fasta-formatted sequences.
Optionally, apply an ID filter function if supplied.
'''
if ifile is not None: # JUST USE THE STREAM WE ALREADY HAVE OPEN
return ifile,idFilter
try: # DEFAULT: JUST READ THE FASTA FILE, IF IT EXISTS
return file(self.filepath, 'rU'),idFilter
except IOError: # TRY READING FROM FORMATTED BLAST DATABASE
cmd='fastacmd -D -d "%s"' % self.get_blast_index_path()
return os.popen(cmd),NCBI_ID_PARSER #BLAST ADDS lcl| TO id
_blast_prog_dict = dict(blastx='#BlastxMapping')
def blast_program(self, seq, blastprog=None):
'figure out appropriate blast program & remap via _blast_prog_dict'
if blastprog is None:
blastprog = blast_program(seq.seqtype(), self.seqDB._seqtype)
oldprog = blastprog
try: # apply program transformation if provided
blastprog = self._blast_prog_dict[blastprog]
if blastprog.startswith('#'): # not permitted by this class!
raise ValueError('Use %s for %s' % (blastprog[1:],oldprog))
except KeyError:
pass # no program transformation to apply, so nothing to do...
return blastprog
def blast_command(self, blastpath, blastprog, expmax, maxseq, opts):
'generate command string for running blast with desired options'
filepath = self.get_blast_index_path()
warn_if_whitespace(filepath)
cmd = [blastpath, '-d', filepath, '-p', blastprog,
'-e', '%e' % float(expmax)] + list(opts)
if maxseq is not None: # ONLY TAKE TOP maxseq HITS
cmd += ['-b', '%d' % maxseq, '-v', '%d' % maxseq]
return cmd
def get_seq_from_queryDB(self, queryDB):
'get one sequence obj from queryDB'
seqID = iter(queryDB).next() # get 1st seq ID
return queryDB[seqID]
def translation_kwargs(self, blastprog):
'return kwargs for read_blast_alignment() based on blastprog'
d = dict(tblastn=dict(translateDest=True),
blastx=dict(translateSrc=True),
tblastx=dict(translateSrc=True, translateDest=True))
try:
return d[blastprog]
except KeyError:
return {}
def __call__(self, seq=None, al=None, blastpath='blastall',
blastprog=None, expmax=0.001, maxseq=None, verbose=None,
opts=(), queryDB=None, **kwargs):
"Run blast search for seq in database, return alignment object"
if seq is None and queryDB is None:
raise ValueError("we need a sequence or db to use as query!")
if seq and queryDB:
raise ValueError("both a sequence AND a db provided for query")
if queryDB is not None:
seq = self.get_seq_from_queryDB(queryDB)
if not self.blastReady: # HAVE TO BUILD THE formatdb FILES...
self.formatdb()
blastprog = self.blast_program(seq, blastprog)
cmd = self.blast_command(blastpath, blastprog, expmax, maxseq, opts)
return process_blast(cmd, seq, self.idIndex, al, queryDB=queryDB,
** self.translation_kwargs(blastprog))
class BlastxMapping(BlastMapping):
"""Because blastx changes the query to multiple sequences
(representing its six possible frames), getitem can no longer
return a single slice object, but instead an iterator for one
or more slice objects representing the frames that had
homology hits."""
def __repr__(self):
return "<BlastxMapping '%s'>" % (self.filepath)
_blast_prog_dict = dict(blastn='tblastx', blastp='#BlastMapping',
tblastn='#BlastMapping')
def __getitem__(self, query):
"""generate slices for all translations of the query """
# generate NLMSA for this single sequence
al = self(query)
# get the translation database for the sequence
tdb = translationDB.get_translation_db(query.db)
# run through all of the frames & find alignments.
slices = []
for trans_seq in tdb[query.id].iter_frames():
try:
slice = al[trans_seq]
except KeyError:
continue
if not isinstance(slice, EmptySlice):
slices.append(slice)
return slices
class MegablastMapping(BlastMapping):
def __repr__(self):
return "<MegablastMapping '%s'>" % (self.filepath)
def __call__(self, seq, al=None, blastpath='megablast', expmax=1e-20,
maxseq=None, minIdentity=None,
maskOpts=['-U', 'T', '-F', 'm'],
rmPath='RepeatMasker', rmOpts=['-xsmall'],
verbose=None, opts=(), **kwargs):
"Run megablast search with optional repeat masking."
if not self.blastReady: # HAVE TO BUILD THE formatdb FILES...
self.formatdb()
# mask repeats to lowercase
masked_seq = repeat_mask(seq,rmPath,rmOpts)
filepath = self.get_blast_index_path()
warn_if_whitespace(filepath)
cmd = [blastpath] + maskOpts \
+ ['-d', filepath,
'-D', '2', '-e', '%e' % float(expmax)] + list(opts)
if maxseq is not None: # ONLY TAKE TOP maxseq HITS
cmd += ['-b', '%d' % maxseq, '-v', '%d' % maxseq]
if minIdentity is not None:
cmd += ['-p', '%f' % float(minIdentity)]
return process_blast(cmd, seq, self.idIndex, al, seqString=masked_seq,
popenArgs=dict(stdinFlag='-i'))
class BlastIDIndex(object):
"""This class acts as a wrapper around a regular seqDB, and handles
the mangled IDs returned by BLAST to translate them to the correct ID.
Since NCBI treats FASTA ID as a blob into which they like to stuff
many fields... and then NCBI BLAST mangles those IDs when it reports
hits, so they no longer match the true ID... we are forced into
contortions to rescue the true ID from mangled IDs.
Our workaround strategy: since NCBI packs the FASTA ID with multiple
IDs (GI, GB, RefSeq ID etc.), we can use any of these identifiers
that are found in a mangled ID, by storing a mapping of these
sub-identifiers to the true FASTA ID."""
def __init__(self, seqDB):
self.seqDB = seqDB
self.seqInfoDict = BlastIDInfoDict(self)
# FOR UNPACKING NCBI IDENTIFIERS AS WORKAROUND FOR BLAST ID CRAZINESS
id_delimiter='|'
def unpack_id(self,id):
"""Return |-packed NCBI identifiers as unpacked list.
NCBI packs identifier like gi|123456|gb|A12345|other|nonsense.
Return as list."""
return id.split(self.id_delimiter)
def index_unpacked_ids(self,unpack_f=None):
"""Build an index of sub-IDs (unpacked from NCBI nasty habit
of using the FASTA ID as a blob); you can customize the unpacking
by overriding the unpack_id function or changing the id_delimiter.
The index maps each sub-ID to the real ID, so that when BLAST
hands back a mangled, fragmentary ID, we can unpack that mangled ID
and look up the true ID in this index. Any sub-ID that is found
to map to more than one true ID will be mapped to None (so that
random NCBI garbage like gnl or NCBI_MITO wont be treated as
sub-IDs).
"""
if unpack_f is None:
unpack_f=self.unpack_id
t={}
for id in self.seqDB:
for s in unpack_f(id):
if s==id: continue # DON'T STORE TRIVIAL MAPPINGS!!
s=s.upper() # NCBI FORCES ID TO UPPERCASE?!?!
try:
if t[s]!=id and t[s] is not None:
t[s]=None # s NOT UNIQUE, CAN'T BE AN IDENTIFIER!!
except KeyError:
t[s]=id # s UNIQUE, TRY USING s AS AN IDENTIFIER
for id in t.itervalues():
if id is not None: # OK THERE ARE REAL MAPPINGS STORED, SO USE THIS
self._unpacked_dict=t # SAVE THE MAPPING TO REAL IDENTIFIERS
return
# NO NON-TRIVIAL MAPPINGS, SO JUST SAVE EMPTY MAPPING
self._unpacked_dict={}
def get_real_id(self,bogusID,unpack_f=None):
"try to translate an id that NCBI has mangled to the real sequence id"
if unpack_f is None:
unpack_f=self.unpack_id
if not hasattr(self,'_unpacked_dict'):
self.index_unpacked_ids(unpack_f)
for s in unpack_f(bogusID):
s=s.upper() # NCBI FORCES ID TO UPPERCASE?!?!
try:
id=self._unpacked_dict[s]
if id is not None:
return id # OK, FOUND A MAPPING TO REAL ID
except KeyError:
pass # KEEP TRYING...
# FOUND NO MAPPING, SO RAISE EXCEPTION
raise KeyError, "no key '%s' in database %s" % (bogusID,
repr(self.seqDB))
def __getitem__(self, seqID):
"If seqID is mangled by BLAST, use our index to get correct ID"
try: # default: treat as a correct ID
return self.seqDB[seqID]
except KeyError: # translate to the correct ID
return self.seqDB[self.get_real_id(seqID)]
def __contains__(self, seqID):
try:
self.seqInfoDict[seqID]
return True
except KeyError:
return False
class BlastIDInfoDict(object, UserDict.DictMixin):
"""provide seqInfoDict interface for BlastIDIndex """
def __init__(self, db):
self.blastDB = db
def __getitem__(self, seqID):
try:
return self.blastDB.seqDB.seqInfoDict[seqID]
except KeyError:
seqID = self.blastDB.get_real_id(seqID)
return self.blastDB.seqDB.seqInfoDict[seqID]
def __len__(self):
return len(self.blastDB.seqDB.seqInfoDict)
def __iter__(self):
return iter(self.blastDB.seqDB.seqInfoDict)
def keys(self):
return self.blastDB.seqDB.seqInfoDict.keys()
| 43.230924
| 82
| 0.623949
|
4f0de58c40a4b91b6f6013a638fbd03ccbc84774
| 1,500
|
py
|
Python
|
tests/notebook_test_case.py
|
tanjie123/hello-ltr
|
fe1ad1989e1bb17dfc8d1c09931480becf59766e
|
[
"Apache-2.0"
] | 109
|
2019-04-18T01:24:29.000Z
|
2022-03-12T17:37:30.000Z
|
tests/notebook_test_case.py
|
tanjie123/hello-ltr
|
fe1ad1989e1bb17dfc8d1c09931480becf59766e
|
[
"Apache-2.0"
] | 63
|
2019-04-14T01:01:24.000Z
|
2022-03-03T20:48:41.000Z
|
tests/notebook_test_case.py
|
tanjie123/hello-ltr
|
fe1ad1989e1bb17dfc8d1c09931480becf59766e
|
[
"Apache-2.0"
] | 41
|
2019-04-22T15:22:41.000Z
|
2022-02-26T00:03:02.000Z
|
import unittest
from nb_test_config import NotebookTestConfig
import runner
class NotebooksTestCase(unittest.TestCase):
SAVE_NB_PATH='tests/last_run.ipynb'
def test_paths(self):
return []
def ignored_nbs(self):
return []
def nbs_to_run(self):
class IncludeAll:
def __contains__(self, _):
return True
return IncludeAll()
def test_for_no_errors(self):
""" Run all nbs in directories at test_paths()
also included in nbs_to_run(),
excepting those in ignored_nbs()
- assert there are no errors
"""
for nb_path in self.test_paths():
nb_cfg = NotebookTestConfig(path=nb_path)
print("EXECUTING NBS IN DIRECTORY: " + nb_path)
if nb_cfg.setup:
print("Setting up ... " + nb_path)
nb, errors = runner.run_notebook(nb_cfg.setup, save_nb_path=NotebooksTestCase.SAVE_NB_PATH)
print(errors)
assert len(errors) == 0
for nb in nb_cfg.notebooks:
if nb in self.nbs_to_run():
if nb in self.ignored_nbs():
print("Ignored " + nb)
else:
print("Running... " + nb)
nb, errors = runner.run_notebook(nb, save_nb_path=NotebooksTestCase.SAVE_NB_PATH)
print(errors)
assert len(errors) == 0
| 32.608696
| 107
| 0.546
|
8613fb0bc33f835f10a0a0a27c6012db681f7213
| 13,992
|
py
|
Python
|
suncasa/eovsa/eovsa_pltQlookMovie.py
|
wyq24/suncasa
|
e6ed6d8b9bd2186c4af6d0354d03af5fff9aef7a
|
[
"BSD-2-Clause"
] | 7
|
2019-05-21T22:24:07.000Z
|
2021-02-25T20:20:24.000Z
|
suncasa/eovsa/eovsa_pltQlookMovie.py
|
wulinhui1/suncasa-src
|
1f94aaabaf6a3911fa532648ec6676a221553436
|
[
"BSD-2-Clause"
] | 26
|
2016-11-09T17:11:45.000Z
|
2021-08-20T13:41:50.000Z
|
suncasa/eovsa/eovsa_pltQlookMovie.py
|
wulinhui1/suncasa-src
|
1f94aaabaf6a3911fa532648ec6676a221553436
|
[
"BSD-2-Clause"
] | 17
|
2016-10-27T18:35:46.000Z
|
2021-08-03T05:33:57.000Z
|
import os
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from sunpy import map as smap
import sunpy.cm.cm as cm_smap
import astropy.units as u
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.colorbar as colorbar
import matplotlib.patches as patches
from datetime import timedelta
from datetime import datetime
from glob import glob
import numpy as np
from astropy.time import Time
import calendar
from suncasa.utils import plot_mapX as pmX
import urllib.request
from sunpy.physics.differential_rotation import diffrot_map
from suncasa.utils import DButil
from tqdm import tqdm
from suncasa.eovsa import eovsa_readfits as er
# imgfitsdir = '/Users/fisher/myworkspace/'
# imgfitstmpdir = '/Users/fisher/myworkspace/fitstmp/'
# pltfigdir = '/Users/fisher/myworkspace/SynopticImg/eovsamedia/eovsa-browser/'
imgfitsdir = '/data1/eovsa/fits/synoptic/'
imgfitstmpdir = '/data1/workdir/fitstmp/'
pltfigdir = '/common/webplots/SynopticImg/eovsamedia/eovsa-browser/'
def clearImage():
for (dirpath, dirnames, filenames) in os.walk(pltfigdir):
for filename in filenames:
for k in ['0094', '0193', '0335', '4500', '0171', '0304', '0131', '1700', '0211', '1600', '_HMIcont',
'_HMImag']:
# for k in ['_Halph_fr']:
if k in filename:
print(os.path.join(dirpath, filename))
os.system('rm -rf ' + os.path.join(dirpath, filename))
def pltEovsaQlookImageSeries(timobjs, spws, vmaxs, vmins, aiawave, bd, fig=None, axs=None, imgoutdir=None, overwrite=False,
verbose=False):
from astropy.visualization.stretch import AsinhStretch
from astropy.visualization import ImageNormalize
plt.ioff()
imgfiles = []
dpi = 512. / 4
aiaDataSource = {"0094": 8,
"0193": 11,
"0335": 14,
# "4500": 17,
"0171": 10,
"0304": 13,
"0131": 9,
"1700": 16,
"0211": 12,
# "1600": 15,
"_HMIcont": 18,
"_HMImag": 19}
tmjd = timobjs.mjd
tmjd_base = np.floor(tmjd)
tmjd_hr = (tmjd - tmjd_base) * 24
for tidx, timobj in enumerate(tqdm(timobjs)):
dateobj = timobj.to_datetime()
timestr = dateobj.strftime("%Y-%m-%dT%H:%M:%SZ")
tstrname = dateobj.strftime("%Y%m%dT%H%M%SZ")
datestrdir = dateobj.strftime("%Y/%m/%d/")
imgindir = imgfitsdir + datestrdir
timobj_prevday = Time(tmjd[tidx] - 1, format='mjd')
dateobj_prevday = timobj_prevday.to_datetime()
datestrdir_prevday = dateobj_prevday.strftime("%Y/%m/%d/")
imgindir_prevday = imgfitsdir + datestrdir_prevday
# if not os.path.exists(imgindir): os.makedirs(imgindir)
cmap = cm_smap.get_cmap('sdoaia304')
if verbose: print('Processing EOVSA images for date {}'.format(dateobj.strftime('%Y-%m-%d')))
key, sourceid = aiawave, aiaDataSource[aiawave]
s, sp = bd, spws[bd]
figoutname = os.path.join(imgoutdir, 'eovsa_bd{:02d}_aia{}_{}.jpg'.format(s + 1, key, tstrname))
if overwrite or (not os.path.exists(figoutname)):
ax = axs[0]
ax.cla()
spwstr = '-'.join(['{:02d}'.format(int(sp_)) for sp_ in sp.split('~')])
t_hr = tmjd_hr[tidx]
t_hr_st_blend = 2.0
t_hr_ed_blend = 14.0
if t_hr <= 8.0:
eofile = imgindir_prevday + 'eovsa_{}.spw{}.tb.disk.fits'.format(dateobj_prevday.strftime('%Y%m%d'),
spwstr)
else:
eofile = imgindir + 'eovsa_{}.spw{}.tb.disk.fits'.format(dateobj.strftime('%Y%m%d'), spwstr)
if not os.path.exists(eofile):
continue
stretch = AsinhStretch(a=0.15)
norm = ImageNormalize(vmin=vmins[s], vmax=vmaxs[s], stretch=stretch)
eomap = er.readfits(eofile)
eomap = eomap.resample(u.Quantity(eomap.dimensions) / 2)
eomap.data[np.isnan(eomap.data)] = 0.0
eomap_rot = diffrot_map(eomap, time=timobj)
offlimbidx = np.where(eomap_rot.data == eomap_rot.data[0, 0])
eomap_rot.data[offlimbidx] = eomap.data[offlimbidx]
t_hr = tmjd_hr[tidx]
if t_hr_st_blend <= t_hr <= t_hr_ed_blend:
if t_hr <= 8.0:
eofile_blend = imgindir + 'eovsa_{}.spw{}.tb.disk.fits'.format(
dateobj.strftime('%Y%m%d'), spwstr)
alpha = 1.0 - (t_hr - t_hr_st_blend) / (t_hr_ed_blend - t_hr_st_blend)
else:
eofile_blend = imgindir_prevday + 'eovsa_{}.spw{}.tb.disk.fits'.format(
dateobj_prevday.strftime('%Y%m%d'), spwstr)
alpha = (t_hr - t_hr_st_blend) / (t_hr_ed_blend - t_hr_st_blend)
alpha_blend = 1.0 - alpha
eomap_blend = er.readfits(eofile_blend)
eomap_blend = eomap_blend.resample(u.Quantity(eomap_blend.dimensions) / 2)
eomap_blend.data[np.isnan(eomap_blend.data)] = 0.0
eomap_rot_blend = diffrot_map(eomap_blend, time=timobj)
offlimbidx = np.where(eomap_rot_blend.data == eomap_rot_blend.data[0, 0])
eomap_rot_blend.data[offlimbidx] = eomap_blend.data[offlimbidx]
eomap_rot_plt = smap.Map((eomap_rot.data * alpha + eomap_rot_blend.data * alpha_blend), eomap_rot.meta)
else:
eomap_rot_plt = eomap_rot
# eomap_plt.plot(axes=ax, cmap=cmap, norm=norm)
eomap_rot_plt.plot(axes=ax, cmap=cmap, norm=norm)
ax.set_xlabel('')
ax.set_ylabel('')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.text(0.02, 0.02,
'EOVSA {:.1f} GHz {}'.format(eomap.meta['CRVAL3'] / 1e9, dateobj.strftime('%d-%b-%Y %H:%M UT')),
transform=ax.transAxes, color='w', ha='left', va='bottom', fontsize=9)
ax.text(0.98, 0.02, 'Max Tb {:.0f} K'.format(np.nanmax(eomap.data)),
transform=ax.transAxes, color='w', ha='right', va='bottom', fontsize=9)
ax.set_xlim(-1227, 1227)
ax.set_ylim(-1227, 1227)
ax = axs[1]
# for key, sourceid in aiaDataSource.items():
ax.cla()
if not os.path.exists(imgoutdir): os.makedirs(imgoutdir)
sdourl = 'https://api.helioviewer.org/v2/getJP2Image/?date={}&sourceId={}'.format(timestr, sourceid)
# print(sdourl)
sdofile = os.path.join(imgoutdir, 'AIA' + key + '.{}.jp2'.format(tstrname))
if not os.path.exists(sdofile):
urllib.request.urlretrieve(sdourl, sdofile)
if not os.path.exists(sdofile): continue
sdomap = smap.Map(sdofile)
norm = colors.Normalize()
# sdomap_ = pmX.Sunmap(sdomap)
if "HMI" in key:
cmap = plt.get_cmap('gray')
else:
cmap = cm_smap.get_cmap('sdoaia' + key.lstrip('0'))
sdomap.plot(axes=ax, cmap=cmap, norm=norm)
# sdomap_.imshow(axes=ax, cmap=cmap, norm=norm)
# sdomap_.draw_limb(axes=ax, lw=0.25, alpha=0.5)
# sdomap_.draw_grid(axes=ax, grid_spacing=10. * u.deg, lw=0.25)
ax.set_xlabel('')
ax.set_ylabel('')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.text(0.02, 0.02,
'{}/{} {} {}'.format(sdomap.observatory, sdomap.instrument.split(' ')[0], sdomap.measurement,
sdomap.date.strftime('%d-%b-%Y %H:%M UT')),
transform=ax.transAxes, color='w', ha='left', va='bottom', fontsize=9)
ax.set_xlim(-1227, 1227)
ax.set_ylim(-1227, 1227)
fig.savefig(figoutname, dpi=np.int(dpi), quality=85)
imgfiles.append(figoutname)
return imgfiles
def main(year, month, day=None, ndays=10, bd=3, show_warning=False):
'''
By default, the subroutine create EOVSA monthly movie
'''
if not show_warning:
import warnings
warnings.filterwarnings("ignore")
# tst = datetime.strptime("2017-04-01", "%Y-%m-%d")
# ted = datetime.strptime("2019-12-31", "%Y-%m-%d")
if day is None:
dst, ded = calendar.monthrange(year, month)
tst = datetime(year, month, 1)
ted = datetime(year, month, ded)
else:
if year:
ted = datetime(year, month, day)
else:
ted = datetime.now() - timedelta(days=2)
tst = Time(np.fix(Time(ted).mjd) - ndays, format='mjd').datetime
tsep = datetime.strptime('2019-02-22', "%Y-%m-%d")
vmaxs = [70.0e4, 35e4, 22e4, 16e4, 10e4, 8e4, 8e4]
vmins = [-18.0e3, -8e3, -4.8e3, -3.4e3, -2.1e3, -1.6e3, -1.6e3]
plt.ioff()
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
fig.subplots_adjust(bottom=0.0, top=1.0, left=0.0, right=1.0, hspace=0.0, wspace=0.0)
dateobs = tst
imgfileslist = []
while dateobs < ted:
monthstrdir = dateobs.strftime("%Y/%m/")
imgoutdir = imgfitstmpdir + monthstrdir
movieoutdir = pltfigdir + monthstrdir
for odir in [imgoutdir, movieoutdir]:
if not os.path.exists(odir):
os.makedirs(odir)
# dateobs = datetime.strptime("2019-12-21", "%Y-%m-%d")
if dateobs > tsep:
spws = ['0~1', '2~5', '6~10', '11~20', '21~30', '31~43', '44~49']
else:
spws = ['1~3', '4~9', '10~16', '17~24', '25~30']
# spw = spws[bd:bd + 1]
# vmax = vmaxs[bd:bd + 1]
# vmin = vmins[bd:bd + 1]
aiawave = '0304'
tdateobs = Time(Time(dateobs).mjd + np.arange(0, 24, 1) / 24, format='mjd')
imgfiles = pltEovsaQlookImageSeries(tdateobs, spws, vmaxs, vmins, aiawave, bd, fig=fig, axs=axs, overwrite=False,
imgoutdir=imgoutdir)
imgfileslist = imgfileslist + imgfiles
dateobs = dateobs + timedelta(days=1)
moviename = 'eovsa_bd{:02d}_aia304_{}'.format(bd + 1, dateobs.strftime("%Y%m"))
DButil.img2movie(imgprefix=imgfileslist, outname=moviename, img_ext='jpg')
os.system('mv {} {}'.format(os.path.join(imgoutdir + '../', moviename + '.mp4'),
os.path.join(movieoutdir, moviename + '.mp4')))
plt.close('all')
# if __name__ == '__main__':
# import sys
# import numpy as np
#
# # import subprocess
# # shell = subprocess.check_output('echo $0', shell=True).decode().replace('\n', '').split('/')[-1]
# # print("shell " + shell + " is using")
#
# print(sys.argv)
# try:
# argv = sys.argv[1:]
# if '--clearcache' in argv:
# clearcache = True
# argv.remove('--clearcache') # Allows --clearcache to be either before or after date items
# else:
# clearcache = False
#
# year = np.int(argv[0])
# month = np.int(argv[1])
# day = np.int(argv[2])
# if len(argv) == 3:
# dayspan = 30
# else:
# dayspan = np.int(argv[3])
# except:
# print('Error interpreting command line argument')
# year = None
# month = None
# day = None
# dayspan = 30
# clearcache = True
# print("Running pipeline_plt for date {}-{}-{}".format(year, month, day))
# main(year, month, None, dayspan)
if __name__ == '__main__':
'''
Name:
eovsa_pltQlookMovie --- pipeline for plotting EOVSA daily full-disk image movie at multi frequencies.
Synopsis:
eovsa_pltQlookMovie.py [options]... [DATE_IN_YY_MM_DD]
Description:
Make EOVSA daily full-disk image movie at multi frequencies of the date specified
by DATE_IN_YY_MM_DD (or from ndays before the DATE_IN_YY_MM_DD if option --ndays/-n is provided).
If DATE_IN_YY_MM_DD is omitted, it will be set to 2 days before now by default.
The are no mandatory arguments in this command.
-n, --ndays
Processing the date spanning from DATE_IN_YY_MM_DD-ndays to DATE_IN_YY_MM_DD. Default is 30
Example:
eovsa_pltQlookMovie.py -n 20 2020 06 10
'''
import sys
import numpy as np
import getopt
year = None
month = None
day = None
ndays = 30
show_warning = False
try:
argv = sys.argv[1:]
opts, args = getopt.getopt(argv, "n:w:",
['ndays=', 'show_warning='])
print(opts, args)
for opt, arg in opts:
if opt in ('-n', '--ndays'):
ndays = np.int(arg)
elif opt in ('-w', '--show_warning'):
if arg in ['True', 'T', '1']:
show_warning = True
elif arg in ['False', 'F', '0']:
show_warning = False
else:
show_warning = np.bool(arg)
nargs = len(args)
if nargs == 3:
year = np.int(args[0])
month = np.int(args[1])
day = np.int(args[2])
else:
year = None
month = None
day = None
except getopt.GetoptError as err:
print(err)
print('Error interpreting command line argument')
year = None
month = None
day = None
ndays = 30
show_warning = False
print("Running pipeline_plt for date {}-{}-{}.".format(year, month, day))
kargs = {'ndays': ndays}
for k, v in kargs.items():
print(k, v)
main(year=year, month=month, day=day, ndays=ndays, show_warning=show_warning)
| 39.637394
| 135
| 0.555818
|
01be757a4344251fc381361c794559ad62bf2173
| 905
|
py
|
Python
|
Processor/EQ/spectrogram.py
|
yuzhouhe2000/video-conference-enhancer
|
46aa130c0b7f02db5055c8d15877c8287c2276c7
|
[
"Apache-2.0"
] | 3
|
2021-07-15T12:02:25.000Z
|
2022-02-17T09:15:49.000Z
|
Processor/EQ/spectrogram.py
|
yuzhouhe2000/video-conference-enhancer
|
46aa130c0b7f02db5055c8d15877c8287c2276c7
|
[
"Apache-2.0"
] | 1
|
2021-08-28T09:58:35.000Z
|
2021-09-04T15:07:17.000Z
|
Processor/EQ/spectrogram.py
|
yuzhouhe2000/video-conference-enhancer
|
46aa130c0b7f02db5055c8d15877c8287c2276c7
|
[
"Apache-2.0"
] | 2
|
2021-08-28T09:48:10.000Z
|
2021-09-22T06:51:23.000Z
|
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
from scipy.io import wavfile
from pydub import AudioSegment
#ASSUME THERE IS ALREADY A FILE IN MONO FORMAT NAMED test_mono.wav
yMax = (int)(input("Enter maximum frequency value to visualize: "))
sample_rate, samples = wavfile.read('Testing_Files/test_mono.wav')
frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate)
original = plt.figure(1)
plt.pcolormesh(times, frequencies, spectrogram)
plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (s)')
plt.title('Original Audio')
sample_rate, samples = wavfile.read('Testing_Files/test_speech_mono.wav')
frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate)
processed = plt.figure(2)
plt.pcolormesh(times, frequencies, spectrogram)
plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (s)')
plt.title('Processed Audio')
plt.ylim(top=yMax)
plt.show()
| 31.206897
| 74
| 0.779006
|
228486a2b0a33131f0408dee5594b7794c427153
| 16,589
|
py
|
Python
|
framework/Samplers/Stratified.py
|
mattdon/raven
|
b5b4a9fc96cec37ca5fb3757c45653eec66522f1
|
[
"Apache-2.0"
] | null | null | null |
framework/Samplers/Stratified.py
|
mattdon/raven
|
b5b4a9fc96cec37ca5fb3757c45653eec66522f1
|
[
"Apache-2.0"
] | null | null | null |
framework/Samplers/Stratified.py
|
mattdon/raven
|
b5b4a9fc96cec37ca5fb3757c45653eec66522f1
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module contains the Stratified sampling strategy
Created on May 21, 2016
@author: alfoa
supercedes Samplers.py from alfoa
"""
#for future compatibility with Python 3--------------------------------------------------------------
from __future__ import division, print_function, unicode_literals, absolute_import
import warnings
warnings.simplefilter('default',DeprecationWarning)
#End compatibility block for Python 3----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
import numpy as np
from operator import mul
from functools import reduce
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from .Grid import Grid
from .Sampler import Sampler
from utils import utils,randomUtils,InputData
#Internal Modules End--------------------------------------------------------------------------------
class Stratified(Grid):
"""
Stratified sampler, also known as Latin Hypercube Sampling (LHS). Currently no
special filling methods are implemented
"""
@classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
inputSpecification = super(Stratified, cls).getInputSpecification()
samplerInitInput = InputData.parameterInputFactory("samplerInit")
samplerInitInput.addSub(InputData.parameterInputFactory("initialSeed", contentType=InputData.IntegerType))
samplerInitInput.addSub(InputData.parameterInputFactory("distInit", contentType=InputData.IntegerType))
inputSpecification.addSub(samplerInitInput)
globalGridInput = InputData.parameterInputFactory("globalGrid", contentType=InputData.StringType)
gridInput = InputData.parameterInputFactory("grid", contentType=InputData.StringType)
gridInput.addParam("name", InputData.StringType)
gridInput.addParam("type", InputData.StringType)
gridInput.addParam("construction", InputData.StringType)
gridInput.addParam("steps", InputData.IntegerType)
globalGridInput.addSub(gridInput)
inputSpecification.addSub(globalGridInput)
return inputSpecification
def __init__(self):
"""
Default Constructor that will initialize member variables with reasonable
defaults or empty lists/dictionaries where applicable.
@ In, None
@ Out, None
"""
Grid.__init__(self)
self.sampledCoordinate = [] # a list of list for i=0,..,limit a list of the coordinate to be used this is needed for the LHS
self.printTag = 'SAMPLER Stratified'
self.globalGrid = {} # Dictionary for the globalGrid. These grids are used only for Stratified for ND distributions.
def localInputAndChecks(self,xmlNode, paramInput):
"""
Class specific xml inputs will be read here and checked for validity.
@ In, xmlNode, xml.etree.ElementTree.Element, The xml element node that will be checked against the available options specific to this Sampler.
@ In, paramInput, InputData.ParameterInput, the parsed parameters
@ Out, None
"""
#TODO Remove using xmlNode
Sampler.readSamplerInit(self,xmlNode)
Grid.localInputAndChecks(self,xmlNode, paramInput)
pointByVar = [len(self.gridEntity.returnParameter("gridInfo")[variable][2]) for variable in self.gridInfo.keys()]
if len(set(pointByVar))!=1:
self.raiseAnError(IOError,'the latin Hyper Cube requires the same number of point in each dimension')
self.pointByVar = pointByVar[0]
self.inputInfo['upper'] = {}
self.inputInfo['lower'] = {}
def localInitialize(self):
"""
Will perform all initialization specific to this Sampler. For instance,
creating an empty container to hold the identified surface points, error
checking the optionally provided solution export and other preset values,
and initializing the limit surface Post-Processor used by this sampler.
@ In, None
@ Out, None
"""
Grid.localInitialize(self)
self.limit = (self.pointByVar-1)
# For the multivariate normal distribtuion, if the user generates the grids on the transformed space, the user needs to provide the grid for each variables, no globalGrid is needed
if self.variablesTransformationDict:
tempFillingCheck = [[None]*(self.pointByVar-1)]*len(self.gridEntity.returnParameter("dimensionNames")) #for all variables
self.sampledCoordinate = [[None]*len(self.axisName)]*(self.pointByVar-1)
for i in range(len(tempFillingCheck)):
tempFillingCheck[i] = randomUtils.randomPermutation(list(range(self.pointByVar-1)),self) #pick a random interval sequence
mappingIdVarName = {}
for cnt, varName in enumerate(self.axisName):
mappingIdVarName[varName] = cnt
# For the multivariate normal, if the user wants to generate the grids based on joint distribution, the user needs to provide the globalGrid for all corresponding variables
else:
globGridsCount = {}
dimInfo = self.gridEntity.returnParameter("dimInfo")
for val in dimInfo.values():
if val[-1] is not None and val[-1] not in globGridsCount.keys():
globGridsCount[val[-1]] = 0
globGridsCount[val[-1]] += 1
diff = -sum(globGridsCount.values())+len(globGridsCount.keys())
tempFillingCheck = [[None]*(self.pointByVar-1)]*(len(self.gridEntity.returnParameter("dimensionNames"))+diff) #for all variables
self.sampledCoordinate = [[None]*len(self.axisName)]*(self.pointByVar-1)
for i in range(len(tempFillingCheck)):
tempFillingCheck[i] = randomUtils.randomPermutation(list(range(self.pointByVar-1)),self) #pick a random interval sequence
cnt = 0
mappingIdVarName = {}
for varName in self.axisName:
if varName not in dimInfo.keys():
mappingIdVarName[varName] = cnt
else:
for addKey,value in dimInfo.items():
if value[1] == dimInfo[varName][1] and addKey not in mappingIdVarName.keys():
mappingIdVarName[addKey] = cnt
if len(mappingIdVarName.keys()) == len(self.axisName):
break
cnt +=1
for nPoint in range(self.pointByVar-1):
self.sampledCoordinate[nPoint]= [tempFillingCheck[mappingIdVarName[varName]][nPoint] for varName in self.axisName]
def localGenerateInput(self,model,myInput):
"""
Function to select the next most informative point for refining the limit
surface search.
After this method is called, the self.inputInfo should be ready to be sent
to the model
@ In, model, model instance, an instance of a model
@ In, myInput, list, a list of the original needed inputs for the model (e.g. list of files, etc.)
@ Out, None
"""
varCount = 0
self.inputInfo['distributionName'] = {} #Used to determine which distribution to change if needed.
self.inputInfo['distributionType'] = {} #Used to determine which distribution type is used
weight = 1.0
for varName in self.axisName:
# new implementation for ND LHS
if not "<distribution>" in varName:
if self.variables2distributionsMapping[varName]['totDim']>1 and self.variables2distributionsMapping[varName]['reducedDim'] == 1:
# to avoid double count of weight for ND distribution; I need to count only one variable instaed of N
distName = self.variables2distributionsMapping[varName]['name']
if self.variablesTransformationDict:
for distVarName in self.distributions2variablesMapping[distName]:
for subVar in utils.first(distVarName.keys()).strip().split(','):
self.inputInfo['distributionName'][subVar] = self.toBeSampled[varName]
self.inputInfo['distributionType'][subVar] = self.distDict[varName].type
ndCoordinate = np.zeros(len(self.distributions2variablesMapping[distName]))
dxs = np.zeros(len(self.distributions2variablesMapping[distName]))
centerCoordinate = np.zeros(len(self.distributions2variablesMapping[distName]))
positionList = self.distributions2variablesIndexList[distName]
sorted_mapping = sorted([(utils.first(var.keys()).strip(),
utils.first(var.values())) for var in
self.distributions2variablesMapping[distName]])
for var in sorted_mapping:
# if the varName is a comma separated list of strings the user wants to sample the comma separated variables with the same sampled value => link the value to all comma separated variables
variable, position = var
upper = self.gridEntity.returnShiftedCoordinate(self.gridEntity.returnIteratorIndexes(),{variable:self.sampledCoordinate[self.counter-1][varCount]+1})[variable]
lower = self.gridEntity.returnShiftedCoordinate(self.gridEntity.returnIteratorIndexes(),{variable:self.sampledCoordinate[self.counter-1][varCount]})[variable]
varCount += 1
if self.gridInfo[variable] == 'CDF':
coordinate = lower + (upper-lower)*randomUtils.random()
ndCoordinate[positionList.index(position)] = self.distDict[variable].inverseMarginalDistribution(coordinate,variable)
dxs[positionList.index(position)] = self.distDict[variable].inverseMarginalDistribution(max(upper,lower),variable)-self.distDict[variable].inverseMarginalDistribution(min(upper,lower),variable)
centerCoordinate[positionList.index(position)] = (self.distDict[variable].inverseMarginalDistribution(upper,variable)+self.distDict[variable].inverseMarginalDistribution(lower,variable))/2.0
for subVar in variable.strip().split(','):
self.values[subVar] = ndCoordinate[positionList.index(position)]
self.inputInfo['upper'][subVar] = self.distDict[variable].inverseMarginalDistribution(max(upper,lower),variable)
self.inputInfo['lower'][subVar] = self.distDict[variable].inverseMarginalDistribution(min(upper,lower),variable)
elif self.gridInfo[variable] == 'value':
dxs[positionList.index(position)] = max(upper,lower) - min(upper,lower)
centerCoordinate[positionList.index(position)] = (upper + lower)/2.0
coordinateCdf = self.distDict[variable].marginalCdf(lower) + (self.distDict[variable].marginalCdf(upper) - self.distDict[variable].marginalCdf(lower))*randomUtils.random()
coordinate = self.distDict[variable].inverseMarginalDistribution(coordinateCdf,variable)
ndCoordinate[positionList.index(position)] = coordinate
for subVar in variable.strip().split(','):
self.values[subVar] = coordinate
self.inputInfo['upper'][subVar] = max(upper,lower)
self.inputInfo['lower'][subVar] = min(upper,lower)
gridsWeight = self.distDict[varName].cellIntegral(centerCoordinate,dxs)
self.inputInfo['SampledVarsPb'][varName] = self.distDict[varName].pdf(ndCoordinate)
else:
if self.gridInfo[varName] == 'CDF':
upper = self.gridEntity.returnShiftedCoordinate(self.gridEntity.returnIteratorIndexes(),{varName:self.sampledCoordinate[self.counter-1][varCount]+1})[varName]
lower = self.gridEntity.returnShiftedCoordinate(self.gridEntity.returnIteratorIndexes(),{varName:self.sampledCoordinate[self.counter-1][varCount]})[varName]
varCount += 1
coordinate = lower + (upper-lower)*randomUtils.random()
gridCoordinate, distName = self.distDict[varName].ppf(coordinate), self.variables2distributionsMapping[varName]['name']
for distVarName in self.distributions2variablesMapping[distName]:
for subVar in utils.first(distVarName.keys()).strip().split(','):
self.inputInfo['distributionName'][subVar], self.inputInfo['distributionType'][subVar], self.values[subVar] = self.toBeSampled[varName], self.distDict[varName].type, np.atleast_1d(gridCoordinate)[utils.first(distVarName.values())-1]
# coordinate stores the cdf values, we need to compute the pdf for SampledVarsPb
self.inputInfo['SampledVarsPb'][varName] = self.distDict[varName].pdf(np.atleast_1d(gridCoordinate).tolist())
gridsWeight = max(upper,lower) - min(upper,lower)
else:
self.raiseAnError(IOError,"Since the globalGrid is defined, the Stratified Sampler is only working when the sampling is performed on a grid on a CDF. However, the user specifies the grid on " + self.gridInfo[varName])
weight *= gridsWeight
self.inputInfo['ProbabilityWeight-'+distName] = gridsWeight
if ("<distribution>" in varName) or self.variables2distributionsMapping[varName]['totDim']==1:
# 1D variable
# if the varName is a comma separated list of strings the user wants to sample the comma separated variables with the same sampled value => link the value to all comma separated variables
upper = self.gridEntity.returnShiftedCoordinate(self.gridEntity.returnIteratorIndexes(),{varName:self.sampledCoordinate[self.counter-1][varCount]+1})[varName]
lower = self.gridEntity.returnShiftedCoordinate(self.gridEntity.returnIteratorIndexes(),{varName:self.sampledCoordinate[self.counter-1][varCount]})[varName]
varCount += 1
if self.gridInfo[varName] =='CDF':
coordinate = lower + (upper-lower)*randomUtils.random()
ppfValue = self.distDict[varName].ppf(coordinate)
ppfLower = self.distDict[varName].ppf(min(upper,lower))
ppfUpper = self.distDict[varName].ppf(max(upper,lower))
gridWeight = self.distDict[varName].cdf(ppfUpper) - self.distDict[varName].cdf(ppfLower)
self.inputInfo['SampledVarsPb'][varName] = self.distDict[varName].pdf(ppfValue)
elif self.gridInfo[varName] == 'value':
coordinateCdf = self.distDict[varName].cdf(min(upper,lower)) + (self.distDict[varName].cdf(max(upper,lower))-self.distDict[varName].cdf(min(upper,lower)))*randomUtils.random()
if coordinateCdf == 0.0:
self.raiseAWarning(IOError,"The grid lower bound and upper bound in value will generate ZERO cdf value!!!")
coordinate = self.distDict[varName].ppf(coordinateCdf)
gridWeight = self.distDict[varName].cdf(max(upper,lower)) - self.distDict[varName].cdf(min(upper,lower))
self.inputInfo['SampledVarsPb'][varName] = self.distDict[varName].pdf(coordinate)
# compute the weight and ProbabilityWeight-varName
weight *= gridWeight
self.inputInfo['ProbabilityWeight-'+varName] = gridWeight
for subVar in varName.strip().split(','):
self.inputInfo['distributionName'][subVar] = self.toBeSampled[varName]
self.inputInfo['distributionType'][subVar] = self.distDict[varName].type
if self.gridInfo[varName] =='CDF':
self.values[subVar] = ppfValue
self.inputInfo['upper'][subVar] = ppfUpper
self.inputInfo['lower'][subVar] = ppfLower
elif self.gridInfo[varName] =='value':
self.values[subVar] = coordinate
self.inputInfo['upper'][subVar] = max(upper,lower)
self.inputInfo['lower'][subVar] = min(upper,lower)
self.inputInfo['PointProbability'] = reduce(mul, self.inputInfo['SampledVarsPb'].values())
self.inputInfo['ProbabilityWeight' ] = weight
self.inputInfo['SamplerType'] = 'Stratified'
| 61.440741
| 250
| 0.681717
|
15cbcfe3f4ba3ac800ce569905caf7f61c2dd8ee
| 756
|
py
|
Python
|
docs/examples/compute/oneandone/create_load_balancer.py
|
rgharris/libcloud
|
90971e17bfd7b6bb97b2489986472c531cc8e140
|
[
"Apache-2.0"
] | null | null | null |
docs/examples/compute/oneandone/create_load_balancer.py
|
rgharris/libcloud
|
90971e17bfd7b6bb97b2489986472c531cc8e140
|
[
"Apache-2.0"
] | 1
|
2021-12-06T12:29:13.000Z
|
2021-12-06T12:29:13.000Z
|
docs/examples/compute/oneandone/create_load_balancer.py
|
rgharris/libcloud
|
90971e17bfd7b6bb97b2489986472c531cc8e140
|
[
"Apache-2.0"
] | 1
|
2019-08-05T10:12:02.000Z
|
2019-08-05T10:12:02.000Z
|
import os
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.ONEANDONE)
drv = cls(key=os.environ.get("ONEANDONE_TOKEN"))
rules = [
{"protocol": "TCP", "port_balancer": 80, "port_server": 80, "source": "0.0.0.0"},
{
"protocol": "TCP",
"port_balancer": 9999,
"port_server": 8888,
"source": "0.0.0.0",
},
]
try:
shared_storage = drv.ex_create_load_balancer(
name="Test Load Balancer",
method="ROUND_ROBIN",
rules=rules,
persistence=False,
persistence_time=1200,
health_check_test="TCP",
health_check_interval=40,
)
print(shared_storage)
except Exception as e:
print(e)
| 22.909091
| 85
| 0.628307
|
632d04049aa1751a38a2fd403067443d750971fe
| 1,249
|
py
|
Python
|
test.py
|
ranok92/deepirl
|
88c7e76986243cf0b988d8d7dc0eef6b58e07864
|
[
"MIT"
] | 2
|
2019-01-04T22:03:15.000Z
|
2019-04-03T00:16:11.000Z
|
test.py
|
ranok92/deepirl
|
88c7e76986243cf0b988d8d7dc0eef6b58e07864
|
[
"MIT"
] | null | null | null |
test.py
|
ranok92/deepirl
|
88c7e76986243cf0b988d8d7dc0eef6b58e07864
|
[
"MIT"
] | null | null | null |
from debugtools import getperStateReward
from irlmethods.deep_maxent import RewardNet
import utils
from utils import to_oh
import itertools
import pdb
from envs.gridworld_clockless import GridWorldClockless as GridWorld
import numpy as np
import torch
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dtype = torch.float32
def per_state_reward(reward_function, rows, cols):
all_states = itertools.product(range(rows), range(cols))
oh_states = []
for state in all_states:
oh_states.append(utils.to_oh(state[0]*cols+state[1], rows*cols))
all_states = torch.tensor(oh_states,
dtype=torch.float).to(DEVICE)
return reward_function(all_states)
def main():
r = 10
c = 10
env = GridWorld(display=False, obstacles=[np.asarray([1, 2])])
reward_network = RewardNet(env.reset().shape[0])
reward_network.load('./experiments/saved-models-rewards/1.pt')
reward_network.eval()
reward_network.to(DEVICE)
reward_values = getperStateReward(reward_network, rows = 10 , cols = 10)
irl_reward_valies = per_state_reward(reward_network,
r,c)
pdb.set_trace()
plt.imshow(reward_values)
plt.colorbar()
plt.show()
if __name__ == '__main__':
main()
| 24.98
| 73
| 0.719776
|
fd9d1e5710d38b28a4f94fe0e37a3b89736291ba
| 31,932
|
py
|
Python
|
ifermi/surface.py
|
whzhangg/IFermi
|
511c69acd1e5ac849f073d435210a25a603d5bcb
|
[
"MIT"
] | 32
|
2021-03-02T14:51:46.000Z
|
2022-03-18T18:56:48.000Z
|
ifermi/surface.py
|
skphy/IFermi
|
41a7a942e30723dcbe0e7eb2d51cc9ff5921d3ee
|
[
"MIT"
] | 24
|
2021-03-04T00:09:06.000Z
|
2022-03-29T09:59:38.000Z
|
ifermi/surface.py
|
skphy/IFermi
|
41a7a942e30723dcbe0e7eb2d51cc9ff5921d3ee
|
[
"MIT"
] | 17
|
2021-03-06T08:55:59.000Z
|
2022-02-03T15:15:58.000Z
|
"""Tools to generate isosurfaces and Fermi surfaces."""
import warnings
from copy import deepcopy
from dataclasses import dataclass
from typing import Collection, Dict, List, Optional, Tuple, Union
import numpy as np
from monty.dev import requires
from monty.json import MSONable, jsanitize
from pymatgen.core.structure import Structure
from pymatgen.electronic_structure.bandstructure import BandStructure
from pymatgen.electronic_structure.core import Spin
from ifermi.brillouin_zone import ReciprocalCell, WignerSeitzCell
from ifermi.interpolate import LinearInterpolator
try:
import mcubes
except ImportError:
mcubes = None
try:
import open3d
except ImportError:
open3d = None
__all__ = [
"Isosurface",
"FermiSurface",
"compute_isosurfaces",
"trim_surface",
"expand_bands",
"decimate_mesh",
"face_properties",
]
@dataclass
class Isosurface(MSONable):
"""
An isosurface object contains a triangular mesh and surface properties.
Attributes:
vertices: A (n, 3) float array of the vertices in the isosurface.
faces: A (m, 3) int array of the faces of the isosurface.
band_idx: The band index to which the surface belongs.
properties: An optional (m, ...) float array containing face properties as
scalars or vectors.
dimensionality: The dimensionality of the surface.
orientation: The orientation of the surface (for 1D and 2D surfaces only).
"""
vertices: np.ndarray
faces: np.ndarray
band_idx: int
properties: Optional[np.ndarray] = None
dimensionality: Optional[str] = None
orientation: Optional[Tuple[int, int, int]] = None
def __post_init__(self):
# ensure all inputs are numpy arrays
self.vertices = np.array(self.vertices)
self.faces = np.array(self.faces)
if self.properties is not None:
self.properties = np.array(self.properties)
@property
def area(self) -> float:
r"""Area of the isosurface in Å\ :sup:`-2`\ ."""
from ifermi.analysis import isosurface_area
return isosurface_area(self.vertices, self.faces)
@property
def has_properties(self) -> float:
"""Whether the surface has properties."""
return self.properties is not None
@property
def properties_norms(self) -> np.ndarray:
"""(m, ) norm of isosurface properties."""
if not self.has_properties:
raise ValueError("Isosurface does not have face properties.")
if self.properties.ndim != 2:
raise ValueError("Isosurface does not have vector properties.")
return np.linalg.norm(self.properties, axis=1)
@property
def properties_ndim(self) -> int:
"""Dimensionality of face properties."""
if not self.has_properties:
raise ValueError("Isosurface does not have face properties.")
return self.properties.ndim
def average_properties(
self, norm: bool = False, projection_axis: Optional[Tuple[int, int, int]] = None
) -> Union[float, np.ndarray]:
"""
Average property across isosurface.
Args:
norm: Average the norm of the properties (vector properties only).
projection_axis: A (3, ) in array of the axis to project the properties onto
(vector properties only).
Returns:
The averaged property.
"""
from ifermi.analysis import average_properties
if not self.has_properties:
raise ValueError("Isosurface does not have face properties.")
properties = self.properties
if projection_axis is not None:
properties = self.scalar_projection(projection_axis)
return average_properties(self.vertices, self.faces, properties, norm=norm)
def scalar_projection(self, axis: Tuple[int, int, int]) -> np.ndarray:
"""
Get scalar projection of properties onto axis.
Args:
axis: A (3, ) int array of the axis to project onto.
Return:
(m, ) float array of scalar projection of properties.
"""
if not self.has_properties:
raise ValueError("Isosurface does not have face properties.")
if self.properties.ndim != 2:
raise ValueError("Isosurface does not have vector properties.")
return np.dot(self.properties, axis)
def sample_uniform(self, grid_size: float) -> np.ndarray:
"""
Sample mesh faces uniformly.
See the docstring for ``ifermi.analysis.sample_surface_uniform`` for more
details.
Args:
grid_size: The grid size in Å^-1.
Returns:
A (n, ) int array containing the indices of uniformly spaced faces.
"""
from ifermi.analysis import sample_surface_uniform
return sample_surface_uniform(self.vertices, self.faces, grid_size)
def __repr__(self):
rep = [
f"Isosurface(nvertices={len(self.vertices)}, "
f"nfaces={len(self.faces)}, band_idx={self.band_idx}",
]
if self.dimensionality is not None:
rep.append(f", dim={self.dimensionality}")
if self.orientation is not None:
rep.append(f", orientation={self.orientation}")
rep.append(")")
return "".join(rep)
@dataclass
class FermiSurface(MSONable):
"""
A FermiSurface object contains isosurfaces and the reciprocal lattice definition.
Attributes:
isosurfaces: A dict containing a list of isosurfaces for each spin channel.
reciprocal_space: A reciprocal space defining periodic boundary conditions.
structure: The structure.
"""
isosurfaces: Dict[Spin, List[Isosurface]]
reciprocal_space: ReciprocalCell
structure: Structure
@property
def n_surfaces(self) -> int:
"""Number of isosurfaces in the Fermi surface."""
return sum(self.n_surfaces_per_spin.values())
@property
def n_surfaces_per_band(self) -> Dict[Spin, Dict[int, int]]:
"""
Get number of surfaces for each band index for each spin channel.
Returned as a dict of ``{spin: {band_idx: count}}``.
"""
from collections import Counter
n_surfaces = {}
for spin, isosurfaces in self.isosurfaces.items():
n_surfaces[spin] = dict(Counter([s.band_idx for s in isosurfaces]))
return n_surfaces
@property
def n_surfaces_per_spin(self) -> Dict[Spin, int]:
"""
Get number of surfaces per spin channel.
Returned as a dict of ``{spin: count}``.
"""
return {spin: len(surfaces) for spin, surfaces in self.isosurfaces.items()}
@property
def area(self) -> float:
r"""Total area of all isosurfaces in the Fermi surface in Å\ :sup:`-2`\ ."""
return sum(map(sum, self.area_surfaces.values()))
@property
def area_surfaces(self) -> Dict[Spin, np.ndarray]:
r"""Area of each isosurface in the Fermi surface in Å\ :sup:`-2`\ ."""
return {k: np.array([i.area for i in v]) for k, v in self.isosurfaces.items()}
@property
def has_properties(self) -> bool:
"""Whether all isosurfaces have face properties."""
return all(
[all([i.has_properties for i in s]) for s in self.isosurfaces.values()]
)
def average_properties(
self, norm: bool = False, projection_axis: Optional[Tuple[int, int, int]] = None
) -> Union[float, np.ndarray]:
"""
Average property across the full Fermi surface.
Args:
norm: Average the norm of the properties (vector properties only).
projection_axis: A (3, ) in array of the axis to project the properties onto
(vector properties only).
Returns:
The averaged property.
"""
surface_averages = self.average_properties_surfaces(norm, projection_axis)
surface_areas = self.area_surfaces
scaled_average = 0
total_area = 0
for spin in self.spins:
for average, area in zip(surface_averages[spin], surface_areas[spin]):
scaled_average += average * area
total_area += area
return scaled_average / total_area
def average_properties_surfaces(
self, norm: bool = False, projection_axis: Optional[Tuple[int, int, int]] = None
) -> Dict[Spin, List[Union[float, np.ndarray]]]:
"""
Average property for each isosurface in the Fermi surface.
Args:
norm: Average the norm of the properties (vector properties only).
projection_axis: A (3, ) in array of the axis to project the properties onto
(vector properties only).
Returns:
The averaged property for each surface in each spin channel.
"""
return {
k: [i.average_properties(norm, projection_axis) for i in v]
for k, v in self.isosurfaces.items()
}
@property
def properties_ndim(self) -> int:
"""Dimensionality of isosurface properties."""
if not self.has_properties:
raise ValueError("Isosurfaces don't have properties.")
ndims = [i.properties_ndim for v in self.isosurfaces.values() for i in v]
if len(set(ndims)) != 1:
warnings.warn(
"Isosurfaces have different property dimensions, using the largest."
)
return max(ndims)
@property
def spins(self):
"""The spin channels in the Fermi surface."""
return tuple(self.isosurfaces.keys())
def all_vertices_faces(
self,
spins: Optional[Union[Spin, Collection[Spin]]] = None,
band_index: Optional[Union[int, list, dict]] = None,
) -> List[Tuple[np.ndarray, np.ndarray]]:
"""
Get the vertices and faces for all isosurfaces.
Args:
spins: One or more spin channels to select. Default is all spins available.
band_index: A choice of band indices (0-based). Valid options are:
- A single integer, which will select that band index in both spin
channels (if both spin channels are present).
- A list of integers, which will select that set of bands from both spin
channels (if both a present).
- A dictionary of ``{Spin.up: band_index_1, Spin.down: band_index_2}``,
where band_index_1 and band_index_2 are either single integers (if one
wishes to plot a single band for that particular spin) or a list of
integers. Note that the choice of integer and list can be different
for different spin channels.
- ``None`` in which case all bands will be selected.
Returns:
A list of (vertices, faces).
"""
if not spins:
spins = self.spins
elif isinstance(spins, Spin):
spins = [spins]
vertices_faces = []
if band_index is None:
band_index = {
spin: [i.band_idx for i in isosurfaces]
for spin, isosurfaces in self.isosurfaces.items()
}
if not isinstance(band_index, dict):
band_index = {spin: band_index for spin in spins}
for spin, spin_index in band_index.items():
if isinstance(spin_index, int):
band_index[spin] = [spin_index]
for spin in spins:
for isosurface in self.isosurfaces[spin]:
if spin in band_index and isosurface.band_idx in band_index[spin]:
vertices_faces.append((isosurface.vertices, isosurface.faces))
return vertices_faces
def all_properties(
self,
spins: Optional[Union[Spin, Collection[Spin]]] = None,
band_index: Optional[Union[int, list, dict]] = None,
projection_axis: Optional[Tuple[int, int, int]] = None,
norm: bool = False,
) -> List[np.ndarray]:
"""
Get the properties for all isosurfaces.
Args:
spins: One or more spin channels to select. Default is all spins available.
band_index: A choice of band indices (0-based). Valid options are:
- A single integer, which will select that band index in both spin
channels (if both spin channels are present).
- A list of integers, which will select that set of bands from both spin
channels (if both a present).
- A dictionary of ``{Spin.up: band_index_1, Spin.down: band_index_2}``,
where band_index_1 and band_index_2 are either single integers (if one
wishes to plot a single band for that particular spin) or a list of
integers. Note that the choice of integer and list can be different
for different spin channels.
- ``None`` in which case all bands will be selected.
projection_axis: A (3, ) in array of the axis to project the properties onto
(vector properties only).
norm: Calculate the norm of the properties (vector properties only).
Ignored if ``projection_axis`` is set.
Returns:
A list of properties arrays for each isosurface.
"""
if not spins:
spins = self.spins
elif isinstance(spins, Spin):
spins = [spins]
projections = []
if band_index is None:
band_index = {
spin: [i.band_idx for i in isosurfaces]
for spin, isosurfaces in self.isosurfaces.items()
}
if not isinstance(band_index, dict):
band_index = {spin: band_index for spin in spins}
for spin, spin_index in band_index.items():
if isinstance(spin_index, int):
band_index[spin] = [spin_index]
for spin in spins:
for isosurface in self.isosurfaces[spin]:
if spin in band_index and isosurface.band_idx in band_index[spin]:
if projection_axis is not None:
projections.append(
isosurface.scalar_projection(projection_axis)
)
elif norm:
projections.append(isosurface.properties_norms)
else:
projections.append(isosurface.properties)
return projections
@classmethod
def from_band_structure(
cls,
band_structure: BandStructure,
mu: float = 0.0,
wigner_seitz: bool = False,
decimate_factor: Optional[float] = None,
decimate_method: str = "quadric",
smooth: bool = False,
property_data: Optional[Dict[Spin, np.ndarray]] = None,
property_kpoints: Optional[np.ndarray] = None,
calculate_dimensionality: bool = False,
) -> "FermiSurface":
"""
Create a FermiSurface from a pymatgen band structure object.
Args:
band_structure: A band structure. The k-points must cover the full
Brillouin zone (i.e., not just be the irreducible mesh). Use
the ``ifermi.interpolator.FourierInterpolator`` class to expand the k-points to
the full Brillouin zone if required.
mu: Energy offset from the Fermi energy at which the isosurface is
calculated.
wigner_seitz: Controls whether the cell is the Wigner-Seitz cell
or the reciprocal unit cell parallelepiped.
decimate_factor: If method is "quadric", and factor is a floating point
value then factor is the scaling factor by which to reduce the number of
faces. I.e., final # faces = initial # faces * factor. If method is
"quadric" but factor is an integer then factor is the target number of
final faces. If method is "cluster", factor is the voxel size in which
to cluster points. Default is None (no decimation).
decimate_method: Algorithm to use for decimation. Options are "quadric"
or "cluster".
smooth: If True, will smooth resulting isosurface. Requires PyMCubes. See
compute_isosurfaces for more information.
property_data: A property to project onto the Fermi surface. It should be
given as a dict of ``{spin: properties}``, where properties is numpy
array with shape (nbands, nkpoints, ...). The number of bands should
equal the number of bands in the band structure but the k-point mesh
can be different. Must be used in combination with
``kpoints``.
property_kpoints: The k-points on which the data is generated.
Must be used in combination with ``data``.
calculate_dimensionality: Whether to calculate isosurface dimensionalities.
Returns:
A Fermi surface.
"""
from ifermi.kpoints import get_kpoint_mesh_dim, kpoints_from_bandstructure
band_structure = deepcopy(band_structure) # prevent data getting overwritten
structure = band_structure.structure
fermi_level = band_structure.efermi + mu
bands = band_structure.bands
kpoints = kpoints_from_bandstructure(band_structure)
kpoint_dim = get_kpoint_mesh_dim(kpoints)
if np.product(kpoint_dim) != len(kpoints):
raise ValueError(
"Number of k-points ({}) in band structure does not match number of "
"k-points expected from mesh dimensions ({})".format(
len(band_structure.kpoints), np.product(kpoint_dim)
)
)
if wigner_seitz:
reciprocal_space = WignerSeitzCell.from_structure(structure)
else:
reciprocal_space = ReciprocalCell.from_structure(structure)
interpolator = None
if property_data is not None and property_kpoints is not None:
interpolator = LinearInterpolator(property_kpoints, property_data)
elif property_data is not None or property_kpoints is not None:
raise ValueError("Both data and kpoints must be specified.")
bands, kpoints = expand_bands(
bands, kpoints, supercell_dim=(3, 3, 3), center=(1, 1, 1)
)
if isinstance(decimate_factor, int):
# increase number of target faces to account for 3x3x3 supercell
decimate_factor *= 27
isosurfaces = compute_isosurfaces(
bands,
kpoints,
fermi_level,
reciprocal_space,
decimate_factor=decimate_factor,
decimate_method=decimate_method,
smooth=smooth,
calculate_dimensionality=calculate_dimensionality,
property_interpolator=interpolator,
)
return cls(isosurfaces, reciprocal_space, structure)
def get_fermi_slice(self, plane_normal: Tuple[int, int, int], distance: float = 0):
"""
Get a slice through the Fermi surface.
Slice defined by the intersection of a plane with the Fermi surface.
Args:
plane_normal: (3, ) int array of the plane normal in fractional indices.
distance: The distance from the center of the Brillouin zone (Γ-point).
Returns:
The Fermi slice.
"""
from ifermi.slice import FermiSlice
return FermiSlice.from_fermi_surface(self, plane_normal, distance=distance)
@classmethod
def from_dict(cls, d) -> "FermiSurface":
"""Return FermiSurface object from dict."""
fs = super().from_dict(d)
fs.isosurfaces = {Spin(int(k)): v for k, v in fs.isosurfaces.items()}
return fs
def as_dict(self) -> dict:
"""Get a json-serializable dict representation of FermiSurface."""
d = super().as_dict()
d["isosurfaces"] = {str(spin): iso for spin, iso in self.isosurfaces.items()}
return jsanitize(d, strict=True)
def compute_isosurfaces(
bands: Dict[Spin, np.ndarray],
kpoints: np.ndarray,
fermi_level: float,
reciprocal_space: ReciprocalCell,
decimate_factor: Optional[float] = None,
decimate_method: str = "quadric",
smooth: bool = False,
calculate_dimensionality: bool = False,
property_interpolator: Optional[LinearInterpolator] = None,
) -> Dict[Spin, List[Isosurface]]:
"""
Compute the isosurfaces at a particular energy level.
Args:
bands: The band energies, given as a dictionary of ``{spin: energies}``, where
energies has the shape (nbands, nkpoints).
kpoints: The k-points in fractional coordinates.
fermi_level: The energy at which to calculate the Fermi surface.
reciprocal_space: The reciprocal space representation.
decimate_factor: If method is "quadric", and factor is a floating point value
then factor is the scaling factor by which to reduce the number of faces.
I.e., final # faces = initial # faces * factor. If method is "quadric" but
factor is an integer then factor is the target number of final faces.
If method is "cluster", factor is the voxel size in which to cluster points.
Default is None (no decimation).
decimate_method: Algorithm to use for decimation. Options are "quadric" or
"cluster".
smooth: If True, will smooth resulting isosurface. Requires PyMCubes. Smoothing
algorithm will use constrained smoothing algorithm to preserve fine details
if input dimension is lower than (500, 500, 500), otherwise will apply a
Gaussian filter.
calculate_dimensionality: Whether to calculate isosurface dimensionality.
property_interpolator: An interpolator class for interpolating properties
onto the surface. If ``None``, no properties will be calculated.
Returns:
A dictionary containing a list of isosurfaces for each spin channel.
"""
from ifermi.kpoints import get_kpoint_mesh_dim, get_kpoint_spacing
# sort k-points to be in the correct order
order = np.lexsort((kpoints[:, 2], kpoints[:, 1], kpoints[:, 0]))
kpoints = kpoints[order]
bands = {s: b[:, order] for s, b in bands.items()}
kpoint_dim = get_kpoint_mesh_dim(kpoints)
spacing = get_kpoint_spacing(kpoints)
reference = np.min(kpoints, axis=0)
isosurfaces = {}
for spin, ebands in bands.items():
ebands -= fermi_level
spin_isosurface = []
for band_idx, energies in enumerate(ebands):
if not np.nanmax(energies) > 0 > np.nanmin(energies):
# if band doesn't cross the Fermi level then skip it
continue
band_isosurfaces = _calculate_band_isosurfaces(
spin,
band_idx,
energies,
kpoint_dim,
spacing,
reference,
reciprocal_space,
decimate_factor,
decimate_method,
smooth,
calculate_dimensionality,
property_interpolator,
)
spin_isosurface.extend(band_isosurfaces)
isosurfaces[spin] = spin_isosurface
return isosurfaces
def _calculate_band_isosurfaces(
spin: Spin,
band_idx: int,
energies: np.ndarray,
kpoint_dim: Tuple[int, int, int],
spacing: np.ndarray,
reference: np.ndarray,
reciprocal_space: ReciprocalCell,
decimate_factor: Optional[float],
decimate_method: str,
smooth: bool,
calculate_dimensionality: bool,
property_interpolator: Optional[LinearInterpolator],
):
"""Helper function to calculate the connected isosurfaces for a band."""
from skimage.measure import marching_cubes
from ifermi.analysis import (
connected_subsurfaces,
equivalent_surfaces,
isosurface_dimensionality,
)
rlat = reciprocal_space.reciprocal_lattice
if smooth and mcubes is None:
smooth = False
warnings.warn("Smoothing disabled, install PyMCubes to enable smoothing.")
if decimate_factor is not None and open3d is None:
decimate_factor = None
warnings.warn("Decimation disabled, install open3d to enable decimation.")
band_data = energies.reshape(kpoint_dim)
if smooth:
smoothed_band_data = mcubes.smooth(band_data)
verts, faces = mcubes.marching_cubes(smoothed_band_data, 0)
# have to manually set spacing with PyMCubes
verts *= spacing
# comes out as np.uint64, but trimesh doesn't like this
faces = faces.astype(np.int32)
else:
verts, faces, _, _ = marching_cubes(band_data, 0, spacing=spacing)
if decimate_factor:
verts, faces = decimate_mesh(
verts, faces, decimate_factor, method=decimate_method
)
verts += reference
# break the isosurface into connected subsurfaces
subsurfaces = connected_subsurfaces(verts, faces)
if calculate_dimensionality:
# calculate dimensionality of periodically equivalent surfaces.
dimensionalities = {}
mapping = equivalent_surfaces([s[0] for s in subsurfaces])
for idx in mapping:
dimensionalities[idx] = isosurface_dimensionality(*subsurfaces[idx])
else:
dimensionalities = None
mapping = np.zeros(len(subsurfaces))
isosurfaces = []
dimensionality = None
orientation = None
properties = None
for (subverts, subfaces), idx in zip(subsurfaces, mapping):
# convert vertices to cartesian coordinates
subverts = np.dot(subverts, rlat)
subverts, subfaces = trim_surface(reciprocal_space, subverts, subfaces)
if len(subverts) == 0:
# skip surfaces that do not enter the reciprocal space boundaries
continue
if calculate_dimensionality:
dimensionality, orientation = dimensionalities[idx]
if property_interpolator is not None:
properties = face_properties(
property_interpolator, subverts, subfaces, band_idx, spin, rlat
)
isosurface = Isosurface(
vertices=subverts,
faces=subfaces,
band_idx=band_idx,
properties=properties,
dimensionality=dimensionality,
orientation=orientation,
)
isosurfaces.append(isosurface)
return isosurfaces
def trim_surface(
reciprocal_cell: ReciprocalCell, vertices: np.ndarray, faces: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
"""
Trim the surface to remove parts outside the cell boundaries.
Will add new triangles at the boundary edges as necessary to produce a smooth
surface.
Args:
reciprocal_cell: The reciprocal space object.
vertices: A (n, 3) float array of the vertices in the isosurface.
faces: A (m, 3) int array of the faces of the isosurface.
Returns:
(vertices, faces) of the trimmed surface.
"""
from trimesh.intersections import slice_faces_plane
for center, normal in zip(reciprocal_cell.centers, reciprocal_cell.normals):
vertices, faces = slice_faces_plane(vertices, faces, -normal, center)
return vertices, faces
def expand_bands(
bands: Dict[Spin, np.ndarray],
fractional_kpoints: np.ndarray,
supercell_dim: Tuple[int, int, int] = (3, 3, 3),
center: Tuple[int, int, int] = (0, 0, 0),
) -> Tuple[Dict[Spin, np.ndarray], np.ndarray]:
"""
Expand the band energies and k-points with periodic boundary conditions.
Args:
bands: The band energies, given as a dictionary of ``{spin: energies}``, where
energies has the shape (nbands, nkpoints).
fractional_kpoints: A (n, 3) float array of the fractional k-point coordinates.
supercell_dim: The supercell mesh dimensions.
center: The cell on which the supercell is centered.
Returns:
(energies, kpoints) The expanded band energies and k-points.
"""
final_ebands = {}
nk = len(fractional_kpoints)
ncells = np.product(supercell_dim)
final_kpoints = np.tile(fractional_kpoints, (ncells, 1))
for n, (i, j, k) in enumerate(np.ndindex(supercell_dim)):
final_kpoints[n * nk : (n + 1) * nk] += [i, j, k]
final_kpoints -= center
for spin, ebands in bands.items():
final_ebands[spin] = np.tile(ebands, (1, ncells))
return final_ebands, final_kpoints
def face_properties(
interpolator: LinearInterpolator,
vertices: np.ndarray,
faces: np.ndarray,
band_idx: int,
spin: Spin,
reciprocal_lattice: np.ndarray,
) -> np.ndarray:
"""
Interpolate properties data onto the Fermi surfaces.
Args:
interpolator: Periodic interpolator for property data.
vertices: A (n, 3) float array of the vertices in the isosurface.
faces: A (m, 3) int array of the faces of the isosurface.
band_idx: The band that the isosurface belongs to.
spin: The spin channel the isosurface belongs to.
reciprocal_lattice: Reciprocal lattice matrix
Returns:
A (m, ...) float array of the interpolated properties at the center of each
face in the isosurface.
"""
from ifermi.kpoints import kpoints_to_first_bz
# get the center of each of face in fractional coords
inv_lattice = np.linalg.inv(reciprocal_lattice)
face_verts = np.dot(vertices, inv_lattice)[faces]
centers = face_verts.mean(axis=1)
# convert to 1st BZ
centers = kpoints_to_first_bz(centers)
# get interpolated properties at center of faces
band_idxs = np.full(len(centers), band_idx)
return interpolator.interpolate(spin, band_idxs, centers)
@requires(open3d, "open3d package is required for mesh decimation")
def decimate_mesh(
vertices: np.ndarray, faces: np.ndarray, factor: Union[int, float], method="quadric"
):
"""Decimate mesh to reduce the number of triangles and vertices.
The open3d package is required for decimation.
Args:
vertices: A (n, 3) float array of the vertices in the isosurface.
faces: A (m, 3) int array of the faces of the isosurface.
factor: If method is "quadric", and factor is a floating point value then
factor is the scaling factor by which to reduce the number of faces.
I.e., final # faces = initial # faces * factor. If method is "quadric" but
factor is an integer then factor is the target number of final faces.
If method is "cluster", factor is the voxel size in which to cluster points.
method: Algorithm to use for decimation. Options are "quadric" or "cluster".
Returns:
(vertices, faces) of the decimated mesh.
"""
# convert mesh to open3d format
o3d_verts = open3d.utility.Vector3dVector(vertices)
o3d_faces = open3d.utility.Vector3iVector(faces)
o3d_mesh = open3d.geometry.TriangleMesh(o3d_verts, o3d_faces)
# decimate mesh
if method == "quadric":
if isinstance(factor, int):
n_target_triangles = min(factor, len(faces))
else:
n_target_triangles = int(len(faces) * factor)
o3d_new_mesh = o3d_mesh.simplify_quadric_decimation(n_target_triangles)
else:
cluster_type = open3d.geometry.SimplificationContraction.Quadric
o3d_new_mesh = o3d_mesh.simplify_vertex_clustering(factor, cluster_type)
return np.array(o3d_new_mesh.vertices), np.array(o3d_new_mesh.triangles)
| 37.26021
| 95
| 0.634755
|
277d998d5b5f38401334468053b0215094f5f89a
| 18,857
|
py
|
Python
|
oauth2app/migrations/0001_initial.py
|
mliu7/django-oauth2app
|
4daa587fa43b9fd1480180b827973e1bb7081adf
|
[
"MIT"
] | null | null | null |
oauth2app/migrations/0001_initial.py
|
mliu7/django-oauth2app
|
4daa587fa43b9fd1480180b827973e1bb7081adf
|
[
"MIT"
] | null | null | null |
oauth2app/migrations/0001_initial.py
|
mliu7/django-oauth2app
|
4daa587fa43b9fd1480180b827973e1bb7081adf
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Client'
db.create_table('oauth2app_client', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True, db_index=True)),
('status', self.gf('django.db.models.fields.IntegerField')(default=1)),
('submitted_by', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='client_submitted_by', null=True, to=orm['auth.User'])),
('approved_by', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='client_approved_by', null=True, to=orm['auth.User'])),
('removed_by', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='client_removed_by', null=True, to=orm['auth.User'])),
('submitted_time', self.gf('django.db.models.fields.DateTimeField')(db_index=True, null=True, blank=True)),
('approved_time', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('removed_time', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('submission_message', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
('removal_message', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
('auto_approve', self.gf('django.db.models.fields.BooleanField')(default=False)),
('counts_towards_contributions', self.gf('django.db.models.fields.BooleanField')(default=True)),
('action_taken', self.gf('django.db.models.fields.IntegerField')(default=1)),
('action_by', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='client_action_by', null=True, to=orm['auth.User'])),
('action_time', self.gf('django.db.models.fields.DateTimeField')(db_index=True, null=True, blank=True)),
('action_message', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
('is_head', self.gf('django.db.models.fields.BooleanField')(default=True)),
('points_to_id', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True, null=True, blank=True)),
('primary_merge_from_id', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True, null=True, blank=True)),
('secondary_merge_from_id', self.gf('django.db.models.fields.PositiveIntegerField')(db_index=True, null=True, blank=True)),
('merge_event', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['trackable_object.MergeEvent'], null=True, blank=True)),
('cache_time', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('real_type', self.gf('django.db.models.fields.related.ForeignKey')(related_name='client_real_type', null=True, to=orm['contenttypes.ContentType'])),
('name', self.gf('django.db.models.fields.CharField')(max_length=256)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('website', self.gf('django.db.models.fields.URLField')(max_length=256, blank=True)),
('key', self.gf('django.db.models.fields.CharField')(default='597b76c283590c42c00c59aa67a5b7', max_length=30, db_index=True)),
('secret', self.gf('django.db.models.fields.CharField')(default='943a045473d860d4f3aa9f6d48b565', max_length=30)),
('redirect_uri', self.gf('oauth2app.models.CustomURLField')(max_length=200, null=True, blank=True)),
))
db.send_create_signal('oauth2app', ['Client'])
# Adding model 'AccessRange'
db.create_table('oauth2app_accessrange', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('key', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255, db_index=True)),
('description', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal('oauth2app', ['AccessRange'])
# Adding model 'AccessToken'
db.create_table('oauth2app_accesstoken', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('client', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2app.Client'])),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('token', self.gf('django.db.models.fields.CharField')(default='8014e71be2', unique=True, max_length=10, db_index=True)),
('refresh_token', self.gf('django.db.models.fields.CharField')(null=True, default='b57d49430c', max_length=10, blank=True, unique=True, db_index=True)),
('mac_key', self.gf('django.db.models.fields.CharField')(default=None, max_length=20, unique=True, null=True, blank=True)),
('issue', self.gf('django.db.models.fields.PositiveIntegerField')(default=1351897074)),
('expire', self.gf('django.db.models.fields.PositiveIntegerField')(default=1352501874)),
('refreshable', self.gf('django.db.models.fields.BooleanField')(default=True)),
))
db.send_create_signal('oauth2app', ['AccessToken'])
# Adding M2M table for field scope on 'AccessToken'
db.create_table('oauth2app_accesstoken_scope', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('accesstoken', models.ForeignKey(orm['oauth2app.accesstoken'], null=False)),
('accessrange', models.ForeignKey(orm['oauth2app.accessrange'], null=False))
))
db.create_unique('oauth2app_accesstoken_scope', ['accesstoken_id', 'accessrange_id'])
# Adding model 'Code'
db.create_table('oauth2app_code', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('client', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2app.Client'])),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('key', self.gf('django.db.models.fields.CharField')(default='7a8026e92e098bab01e5211b92b34a', unique=True, max_length=30, db_index=True)),
('issue', self.gf('django.db.models.fields.PositiveIntegerField')(default=1351897074)),
('expire', self.gf('django.db.models.fields.PositiveIntegerField')(default=1351897194)),
('redirect_uri', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True)),
))
db.send_create_signal('oauth2app', ['Code'])
# Adding M2M table for field scope on 'Code'
db.create_table('oauth2app_code_scope', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('code', models.ForeignKey(orm['oauth2app.code'], null=False)),
('accessrange', models.ForeignKey(orm['oauth2app.accessrange'], null=False))
))
db.create_unique('oauth2app_code_scope', ['code_id', 'accessrange_id'])
# Adding model 'MACNonce'
db.create_table('oauth2app_macnonce', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('access_token', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2app.AccessToken'])),
('nonce', self.gf('django.db.models.fields.CharField')(max_length=30, db_index=True)),
))
db.send_create_signal('oauth2app', ['MACNonce'])
def backwards(self, orm):
# Deleting model 'Client'
db.delete_table('oauth2app_client')
# Deleting model 'AccessRange'
db.delete_table('oauth2app_accessrange')
# Deleting model 'AccessToken'
db.delete_table('oauth2app_accesstoken')
# Removing M2M table for field scope on 'AccessToken'
db.delete_table('oauth2app_accesstoken_scope')
# Deleting model 'Code'
db.delete_table('oauth2app_code')
# Removing M2M table for field scope on 'Code'
db.delete_table('oauth2app_code_scope')
# Deleting model 'MACNonce'
db.delete_table('oauth2app_macnonce')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'oauth2app.accessrange': {
'Meta': {'object_name': 'AccessRange'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'})
},
'oauth2app.accesstoken': {
'Meta': {'object_name': 'AccessToken'},
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2app.Client']"}),
'expire': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1352501874'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'issue': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1351897074'}),
'mac_key': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '20', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'refresh_token': ('django.db.models.fields.CharField', [], {'null': 'True', 'default': "'90069a68cb'", 'max_length': '10', 'blank': 'True', 'unique': 'True', 'db_index': 'True'}),
'refreshable': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'scope': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['oauth2app.AccessRange']", 'symmetrical': 'False'}),
'token': ('django.db.models.fields.CharField', [], {'default': "'b2d6563cc8'", 'unique': 'True', 'max_length': '10', 'db_index': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'oauth2app.client': {
'Meta': {'object_name': 'Client'},
'action_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'client_action_by'", 'null': 'True', 'to': "orm['auth.User']"}),
'action_message': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'action_taken': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'action_time': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'client_approved_by'", 'null': 'True', 'to': "orm['auth.User']"}),
'approved_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'auto_approve': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'cache_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'counts_towards_contributions': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True', 'db_index': 'True'}),
'is_head': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'default': "'142e948dc037708d27ed48e7cec3c4'", 'max_length': '30', 'db_index': 'True'}),
'merge_event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trackable_object.MergeEvent']", 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'points_to_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'primary_merge_from_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'real_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'client_real_type'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'redirect_uri': ('oauth2app.models.CustomURLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'removal_message': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'removed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'client_removed_by'", 'null': 'True', 'to': "orm['auth.User']"}),
'removed_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'secondary_merge_from_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'secret': ('django.db.models.fields.CharField', [], {'default': "'4b3772cd1a84437e681f051d7b7d69'", 'max_length': '30'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'submission_message': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'submitted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'client_submitted_by'", 'null': 'True', 'to': "orm['auth.User']"}),
'submitted_time': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '256', 'blank': 'True'})
},
'oauth2app.code': {
'Meta': {'object_name': 'Code'},
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2app.Client']"}),
'expire': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1351897194'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'issue': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1351897074'}),
'key': ('django.db.models.fields.CharField', [], {'default': "'a44cd324b8f1f125c0faf31a741c75'", 'unique': 'True', 'max_length': '30', 'db_index': 'True'}),
'redirect_uri': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'scope': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['oauth2app.AccessRange']", 'symmetrical': 'False'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'oauth2app.macnonce': {
'Meta': {'object_name': 'MACNonce'},
'access_token': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2app.AccessToken']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nonce': ('django.db.models.fields.CharField', [], {'max_length': '30', 'db_index': 'True'})
},
'trackable_object.mergeevent': {
'Meta': {'object_name': 'MergeEvent'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True', 'db_index': 'True'})
}
}
complete_apps = ['oauth2app']
| 78.570833
| 191
| 0.609641
|
c1ef13eb122d46411ee941ae1aeb9ba2d31dcb43
| 1,862
|
py
|
Python
|
indy_client/test/scripts/test_reset_client.py
|
sergeykupryushin/indy-node
|
3162c5750e99af3512218d5843ba065c7d0f07db
|
[
"Apache-2.0"
] | 1
|
2018-07-05T19:34:29.000Z
|
2018-07-05T19:34:29.000Z
|
indy_client/test/scripts/test_reset_client.py
|
sergeykupryushin/indy-node
|
3162c5750e99af3512218d5843ba065c7d0f07db
|
[
"Apache-2.0"
] | null | null | null |
indy_client/test/scripts/test_reset_client.py
|
sergeykupryushin/indy-node
|
3162c5750e99af3512218d5843ba065c7d0f07db
|
[
"Apache-2.0"
] | 1
|
2021-06-06T15:48:30.000Z
|
2021-06-06T15:48:30.000Z
|
import os
from plenum.common.util import randomString
from indy_client.script_helper import performIndyBaseDirCleanup, \
keepFilesInClientReset
from indy_client.test.cli.conftest import aliceCLI, CliBuilder, cliTempLogger
def createRandomDirsAndFiles(baseDir):
dirsCreated = []
filesCreated = []
def create(path, file=False, dir=False):
if not os.path.exists(path):
if dir:
os.mkdir(path)
dirsCreated.append(path)
elif file:
with open(path, 'w+') as f:
f.write(randomString(20))
filesCreated.append(path)
for n in range(1, 10):
path = os.path.join(baseDir, randomString(5))
if n % 2 == 0:
create(path, file=True, dir=False)
else:
create(path, file=False, dir=True)
return dirsCreated, filesCreated
def getCurrentDirAndFiles(baseDir):
dirs = []
files = []
for name in os.listdir(baseDir):
path = os.path.join(baseDir, name)
if os.path.isdir(name):
dirs.append(path)
else:
files.append(name)
return dirs, files
def testResetClient(tconf, aliceCLI):
newDirs, newFiels = createRandomDirsAndFiles(tconf.CLI_BASE_DIR)
beforeCleanupDirs, beforeCleanupFiles = getCurrentDirAndFiles(
tconf.CLI_BASE_DIR)
backupDir = performIndyBaseDirCleanup(tconf.CLI_BASE_DIR)
afterCleanupDirs, afterCleanupFiles = getCurrentDirAndFiles(tconf.CLI_BASE_DIR)
backedupDirs, backedupFiles = getCurrentDirAndFiles(backupDir)
for name in os.listdir(tconf.CLI_BASE_DIR):
assert name in keepFilesInClientReset
assert newDirs not in afterCleanupDirs
assert newFiels not in afterCleanupFiles
assert beforeCleanupDirs == backedupDirs
assert beforeCleanupFiles == backedupFiles
| 31.033333
| 83
| 0.669173
|
aec1315448224cf27c9887db6eb3fb57d0c08448
| 492
|
py
|
Python
|
tests/cpp/backends/llvm/cpu_aot.py
|
weiyunfei/taichi
|
52a7cd8325672bc160e5540e54064c960c78256d
|
[
"MIT"
] | 1
|
2020-11-10T07:17:01.000Z
|
2020-11-10T07:17:01.000Z
|
tests/cpp/backends/llvm/cpu_aot.py
|
weiyunfei/taichi
|
52a7cd8325672bc160e5540e54064c960c78256d
|
[
"MIT"
] | null | null | null |
tests/cpp/backends/llvm/cpu_aot.py
|
weiyunfei/taichi
|
52a7cd8325672bc160e5540e54064c960c78256d
|
[
"MIT"
] | null | null | null |
import os
import taichi as ti
def compile_aot():
ti.init(arch=ti.x64)
@ti.kernel
def run(base: int, arr: ti.types.ndarray()):
for i in arr:
arr[i] = base + i
arr = ti.ndarray(int, shape=16)
run(42, arr)
assert "TAICHI_AOT_FOLDER_PATH" in os.environ.keys()
dir_name = str(os.environ["TAICHI_AOT_FOLDER_PATH"])
m = ti.aot.Module(ti.x64)
m.add_kernel(run, template_args={'arr': arr})
m.save(dir_name, 'x64-aot')
compile_aot()
| 18.923077
| 56
| 0.617886
|
879ba0445d40151145886fdb6a71ee0acd014b41
| 2,202
|
py
|
Python
|
tests/test_style.py
|
Acribbs/trnamapper
|
db35e2eeec856d5e8f8a33d6fcb437c69f926ee6
|
[
"MIT"
] | 1
|
2020-10-15T05:54:49.000Z
|
2020-10-15T05:54:49.000Z
|
tests/test_style.py
|
Acribbs/trnamapper
|
db35e2eeec856d5e8f8a33d6fcb437c69f926ee6
|
[
"MIT"
] | 16
|
2019-06-07T09:28:55.000Z
|
2020-03-16T08:17:44.000Z
|
tests/test_style.py
|
Acribbs/trnamapper
|
db35e2eeec856d5e8f8a33d6fcb437c69f926ee6
|
[
"MIT"
] | 2
|
2019-06-07T09:21:33.000Z
|
2021-02-18T14:50:55.000Z
|
'''test_style - test coding style of CGAT code
==============================================
:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
This script runs pep8 on all code in this repository.
This script is best run within nosetests::
nosetests tests/test_style.py
'''
import pep8
import glob
import os
from nose.tools import ok_
# DIRECTORIES to examine
EXPRESSIONS = (
('FirstLevel', 'trnanalysis/*.py'),
('SecondLevel', 'trnanalysis/python/*.py'))
# Codes to ignore in the pep8 BaseReport
IGNORE = set(('E101', # indentation contains mixed spaces and tabs
'E201', # whitespace after '('
'E202', # whitespace before ')'
'E122', # continuation line missing indentation or outdented
'E265', # block comment should start with '# '
'E501', # line too long (82 > 79 characters)
'E502', # the backslash is redundant between brackets
'E731', # do not assign a lambda expression, use a def
'W191',
'W291',
'W293',
'W391',
'W503', # line break before binary operator
'W601',
'W602',
'files',
'directories',
'physical lines',
'logical lines',))
def check_style(filename):
'''check style of filename.
'''
p = pep8.StyleGuide(quiet=True)
report = p.check_files([filename])
# count errors/warning excluding
# those to ignore
take = [y for x, y
in list(report.counters.items()) if x not in IGNORE]
found = ['%s:%i' % (x, y) for x, y
in list(report.counters.items()) if x not in IGNORE]
total = sum(take)
ok_(total == 0,
'pep8 style violations: %s' % ','.join(found))
def test_style():
'''test style of scripts
'''
for label, expression in EXPRESSIONS:
files = glob.glob(expression)
files.sort()
for f in files:
if os.path.isdir(f):
continue
check_style.description = os.path.abspath(f)
yield(check_style, os.path.abspath(f))
| 26.53012
| 75
| 0.549955
|
339ef444b83e8cf51330d13a853096c682ff319c
| 534,731
|
py
|
Python
|
AppKit/_metadata.py
|
EnjoyLifeFund/macHighSierra-py36-pkgs
|
5668b5785296b314ea1321057420bcd077dba9ea
|
[
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null |
AppKit/_metadata.py
|
EnjoyLifeFund/macHighSierra-py36-pkgs
|
5668b5785296b314ea1321057420bcd077dba9ea
|
[
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null |
AppKit/_metadata.py
|
EnjoyLifeFund/macHighSierra-py36-pkgs
|
5668b5785296b314ea1321057420bcd077dba9ea
|
[
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null |
# This file is generated by objective.metadata
#
# Last update: Sun Dec 3 10:52:51 2017
import objc, sys
if sys.maxsize > 2 ** 32:
def sel32or64(a, b): return b
else:
def sel32or64(a, b): return a
if sys.byteorder == 'little':
def littleOrBig(a, b): return a
else:
def littleOrBig(a, b): return b
misc = {
}
misc.update({'NSOpenGLPixelFormatAuxiliary': objc.createStructType('NSOpenGLPixelFormatAuxiliary', b'{_CGLPixelFormatObject=}', []), 'NSScreenAuxiliaryOpaque': objc.createStructType('NSScreenAuxiliaryOpaque', b'{NSScreenAuxiliary=}', []), 'NSOpenGLContextAuxiliary': objc.createStructType('NSOpenGLContextAuxiliary', b'{_CGLContextObject=}', [])})
constants = '''$NSAFMAscender$NSAFMCapHeight$NSAFMCharacterSet$NSAFMDescender$NSAFMEncodingScheme$NSAFMFamilyName$NSAFMFontName$NSAFMFormatVersion$NSAFMFullName$NSAFMItalicAngle$NSAFMMappingScheme$NSAFMNotice$NSAFMUnderlinePosition$NSAFMUnderlineThickness$NSAFMVersion$NSAFMWeight$NSAFMXHeight$NSAbortModalException$NSAbortPrintingException$NSAboutPanelOptionApplicationIcon$NSAboutPanelOptionApplicationName$NSAboutPanelOptionApplicationVersion$NSAboutPanelOptionCredits$NSAboutPanelOptionVersion$NSAccessibilityActivationPointAttribute$NSAccessibilityAllowedValuesAttribute$NSAccessibilityAlternateUIVisibleAttribute$NSAccessibilityAnnotationElement$NSAccessibilityAnnotationLabel$NSAccessibilityAnnotationLocation$NSAccessibilityAnnotationTextAttribute$NSAccessibilityAnnouncementKey$NSAccessibilityAnnouncementRequestedNotification$NSAccessibilityApplicationActivatedNotification$NSAccessibilityApplicationDeactivatedNotification$NSAccessibilityApplicationHiddenNotification$NSAccessibilityApplicationRole$NSAccessibilityApplicationShownNotification$NSAccessibilityAscendingSortDirectionValue$NSAccessibilityAttachmentTextAttribute$NSAccessibilityAttributedStringForRangeParameterizedAttribute$NSAccessibilityAutocorrectedTextAttribute$NSAccessibilityBackgroundColorTextAttribute$NSAccessibilityBoundsForRangeParameterizedAttribute$NSAccessibilityBrowserRole$NSAccessibilityBusyIndicatorRole$NSAccessibilityButtonRole$NSAccessibilityCancelAction$NSAccessibilityCancelButtonAttribute$NSAccessibilityCellForColumnAndRowParameterizedAttribute$NSAccessibilityCellRole$NSAccessibilityCenterTabStopMarkerTypeValue$NSAccessibilityCentimetersUnitValue$NSAccessibilityCheckBoxRole$NSAccessibilityChildrenAttribute$NSAccessibilityClearButtonAttribute$NSAccessibilityCloseButtonAttribute$NSAccessibilityCloseButtonSubrole$NSAccessibilityCollectionListSubrole$NSAccessibilityColorWellRole$NSAccessibilityColumnCountAttribute$NSAccessibilityColumnHeaderUIElementsAttribute$NSAccessibilityColumnIndexRangeAttribute$NSAccessibilityColumnRole$NSAccessibilityColumnTitlesAttribute$NSAccessibilityColumnsAttribute$NSAccessibilityComboBoxRole$NSAccessibilityConfirmAction$NSAccessibilityContainsProtectedContentAttribute$NSAccessibilityContentListSubrole$NSAccessibilityContentsAttribute$NSAccessibilityCreatedNotification$NSAccessibilityCriticalValueAttribute$NSAccessibilityCustomTextAttribute$NSAccessibilityDecimalTabStopMarkerTypeValue$NSAccessibilityDecrementAction$NSAccessibilityDecrementArrowSubrole$NSAccessibilityDecrementButtonAttribute$NSAccessibilityDecrementPageSubrole$NSAccessibilityDefaultButtonAttribute$NSAccessibilityDefinitionListSubrole$NSAccessibilityDeleteAction$NSAccessibilityDescendingSortDirectionValue$NSAccessibilityDescriptionAttribute$NSAccessibilityDescriptionListSubrole$NSAccessibilityDialogSubrole$NSAccessibilityDisclosedByRowAttribute$NSAccessibilityDisclosedRowsAttribute$NSAccessibilityDisclosingAttribute$NSAccessibilityDisclosureLevelAttribute$NSAccessibilityDisclosureTriangleRole$NSAccessibilityDocumentAttribute$NSAccessibilityDrawerCreatedNotification$NSAccessibilityDrawerRole$NSAccessibilityEditedAttribute$NSAccessibilityEnabledAttribute$NSAccessibilityErrorCodeExceptionInfo$NSAccessibilityException$NSAccessibilityExpandedAttribute$NSAccessibilityExtrasMenuBarAttribute$NSAccessibilityFilenameAttribute$NSAccessibilityFirstLineIndentMarkerTypeValue$NSAccessibilityFloatingWindowSubrole$NSAccessibilityFocusedAttribute$NSAccessibilityFocusedUIElementAttribute$NSAccessibilityFocusedUIElementChangedNotification$NSAccessibilityFocusedWindowAttribute$NSAccessibilityFocusedWindowChangedNotification$NSAccessibilityFontFamilyKey$NSAccessibilityFontNameKey$NSAccessibilityFontSizeKey$NSAccessibilityFontTextAttribute$NSAccessibilityForegroundColorTextAttribute$NSAccessibilityFrontmostAttribute$NSAccessibilityFullScreenButtonAttribute$NSAccessibilityFullScreenButtonSubrole$NSAccessibilityGridRole$NSAccessibilityGroupRole$NSAccessibilityGrowAreaAttribute$NSAccessibilityGrowAreaRole$NSAccessibilityHandleRole$NSAccessibilityHandlesAttribute$NSAccessibilityHeadIndentMarkerTypeValue$NSAccessibilityHeaderAttribute$NSAccessibilityHelpAttribute$NSAccessibilityHelpTagCreatedNotification$NSAccessibilityHelpTagRole$NSAccessibilityHiddenAttribute$NSAccessibilityHorizontalOrientationValue$NSAccessibilityHorizontalScrollBarAttribute$NSAccessibilityHorizontalUnitDescriptionAttribute$NSAccessibilityHorizontalUnitsAttribute$NSAccessibilityHorizontialUnitDescriptionAttribute$NSAccessibilityHorizontialUnitsAttribute$NSAccessibilityIdentifierAttribute$NSAccessibilityImageRole$NSAccessibilityInchesUnitValue$NSAccessibilityIncrementAction$NSAccessibilityIncrementArrowSubrole$NSAccessibilityIncrementButtonAttribute$NSAccessibilityIncrementPageSubrole$NSAccessibilityIncrementorRole$NSAccessibilityIndexAttribute$NSAccessibilityInsertionPointLineNumberAttribute$NSAccessibilityLabelUIElementsAttribute$NSAccessibilityLabelValueAttribute$NSAccessibilityLanguageTextAttribute$NSAccessibilityLayoutAreaRole$NSAccessibilityLayoutChangedNotification$NSAccessibilityLayoutItemRole$NSAccessibilityLayoutPointForScreenPointParameterizedAttribute$NSAccessibilityLayoutSizeForScreenSizeParameterizedAttribute$NSAccessibilityLeftTabStopMarkerTypeValue$NSAccessibilityLevelIndicatorRole$NSAccessibilityLineForIndexParameterizedAttribute$NSAccessibilityLinkRole$NSAccessibilityLinkTextAttribute$NSAccessibilityLinkedUIElementsAttribute$NSAccessibilityListItemIndexTextAttribute$NSAccessibilityListItemLevelTextAttribute$NSAccessibilityListItemPrefixTextAttribute$NSAccessibilityListRole$NSAccessibilityMainAttribute$NSAccessibilityMainWindowAttribute$NSAccessibilityMainWindowChangedNotification$NSAccessibilityMarkedMisspelledTextAttribute$NSAccessibilityMarkerGroupUIElementAttribute$NSAccessibilityMarkerTypeAttribute$NSAccessibilityMarkerTypeDescriptionAttribute$NSAccessibilityMarkerUIElementsAttribute$NSAccessibilityMarkerValuesAttribute$NSAccessibilityMatteContentUIElementAttribute$NSAccessibilityMatteHoleAttribute$NSAccessibilityMatteRole$NSAccessibilityMaxValueAttribute$NSAccessibilityMenuBarAttribute$NSAccessibilityMenuBarItemRole$NSAccessibilityMenuBarRole$NSAccessibilityMenuButtonRole$NSAccessibilityMenuItemRole$NSAccessibilityMenuRole$NSAccessibilityMinValueAttribute$NSAccessibilityMinimizeButtonAttribute$NSAccessibilityMinimizeButtonSubrole$NSAccessibilityMinimizedAttribute$NSAccessibilityMisspelledTextAttribute$NSAccessibilityModalAttribute$NSAccessibilityMovedNotification$NSAccessibilityNextContentsAttribute$NSAccessibilityNumberOfCharactersAttribute$NSAccessibilityOrderedByRowAttribute$NSAccessibilityOrientationAttribute$NSAccessibilityOutlineRole$NSAccessibilityOutlineRowSubrole$NSAccessibilityOverflowButtonAttribute$NSAccessibilityPageRole$NSAccessibilityParentAttribute$NSAccessibilityPicasUnitValue$NSAccessibilityPickAction$NSAccessibilityPlaceholderValueAttribute$NSAccessibilityPointsUnitValue$NSAccessibilityPopUpButtonRole$NSAccessibilityPopoverRole$NSAccessibilityPositionAttribute$NSAccessibilityPressAction$NSAccessibilityPreviousContentsAttribute$NSAccessibilityPriorityKey$NSAccessibilityProgressIndicatorRole$NSAccessibilityProxyAttribute$NSAccessibilityRTFForRangeParameterizedAttribute$NSAccessibilityRadioButtonRole$NSAccessibilityRadioGroupRole$NSAccessibilityRaiseAction$NSAccessibilityRangeForIndexParameterizedAttribute$NSAccessibilityRangeForLineParameterizedAttribute$NSAccessibilityRangeForPositionParameterizedAttribute$NSAccessibilityRatingIndicatorSubrole$NSAccessibilityRelevanceIndicatorRole$NSAccessibilityRequiredAttribute$NSAccessibilityResizedNotification$NSAccessibilityRightTabStopMarkerTypeValue$NSAccessibilityRoleAttribute$NSAccessibilityRoleDescriptionAttribute$NSAccessibilityRowCollapsedNotification$NSAccessibilityRowCountAttribute$NSAccessibilityRowCountChangedNotification$NSAccessibilityRowExpandedNotification$NSAccessibilityRowHeaderUIElementsAttribute$NSAccessibilityRowIndexRangeAttribute$NSAccessibilityRowRole$NSAccessibilityRowsAttribute$NSAccessibilityRulerMarkerRole$NSAccessibilityRulerRole$NSAccessibilityScreenPointForLayoutPointParameterizedAttribute$NSAccessibilityScreenSizeForLayoutSizeParameterizedAttribute$NSAccessibilityScrollAreaRole$NSAccessibilityScrollBarRole$NSAccessibilitySearchButtonAttribute$NSAccessibilitySearchFieldSubrole$NSAccessibilitySearchMenuAttribute$NSAccessibilitySectionListSubrole$NSAccessibilitySecureTextFieldSubrole$NSAccessibilitySelectedAttribute$NSAccessibilitySelectedCellsAttribute$NSAccessibilitySelectedCellsChangedNotification$NSAccessibilitySelectedChildrenAttribute$NSAccessibilitySelectedChildrenChangedNotification$NSAccessibilitySelectedChildrenMovedNotification$NSAccessibilitySelectedColumnsAttribute$NSAccessibilitySelectedColumnsChangedNotification$NSAccessibilitySelectedRowsAttribute$NSAccessibilitySelectedRowsChangedNotification$NSAccessibilitySelectedTextAttribute$NSAccessibilitySelectedTextChangedNotification$NSAccessibilitySelectedTextRangeAttribute$NSAccessibilitySelectedTextRangesAttribute$NSAccessibilityServesAsTitleForUIElementsAttribute$NSAccessibilityShadowTextAttribute$NSAccessibilitySharedCharacterRangeAttribute$NSAccessibilitySharedFocusElementsAttribute$NSAccessibilitySharedTextUIElementsAttribute$NSAccessibilitySheetCreatedNotification$NSAccessibilitySheetRole$NSAccessibilityShowAlternateUIAction$NSAccessibilityShowDefaultUIAction$NSAccessibilityShowMenuAction$NSAccessibilityShownMenuAttribute$NSAccessibilitySizeAttribute$NSAccessibilitySliderRole$NSAccessibilitySortButtonRole$NSAccessibilitySortButtonSubrole$NSAccessibilitySortDirectionAttribute$NSAccessibilitySplitGroupRole$NSAccessibilitySplitterRole$NSAccessibilitySplittersAttribute$NSAccessibilityStandardWindowSubrole$NSAccessibilityStaticTextRole$NSAccessibilityStrikethroughColorTextAttribute$NSAccessibilityStrikethroughTextAttribute$NSAccessibilityStringForRangeParameterizedAttribute$NSAccessibilityStyleRangeForIndexParameterizedAttribute$NSAccessibilitySubroleAttribute$NSAccessibilitySuperscriptTextAttribute$NSAccessibilitySwitchSubrole$NSAccessibilitySystemDialogSubrole$NSAccessibilitySystemFloatingWindowSubrole$NSAccessibilitySystemWideRole$NSAccessibilityTabButtonSubrole$NSAccessibilityTabGroupRole$NSAccessibilityTableRole$NSAccessibilityTableRowSubrole$NSAccessibilityTabsAttribute$NSAccessibilityTailIndentMarkerTypeValue$NSAccessibilityTextAlignmentAttribute$NSAccessibilityTextAreaRole$NSAccessibilityTextAttachmentSubrole$NSAccessibilityTextFieldRole$NSAccessibilityTextLinkSubrole$NSAccessibilityTimelineSubrole$NSAccessibilityTitleAttribute$NSAccessibilityTitleChangedNotification$NSAccessibilityTitleUIElementAttribute$NSAccessibilityToggleSubrole$NSAccessibilityToolbarButtonAttribute$NSAccessibilityToolbarButtonSubrole$NSAccessibilityToolbarRole$NSAccessibilityTopLevelUIElementAttribute$NSAccessibilityUIElementDestroyedNotification$NSAccessibilityUIElementsKey$NSAccessibilityURLAttribute$NSAccessibilityUnderlineColorTextAttribute$NSAccessibilityUnderlineTextAttribute$NSAccessibilityUnitDescriptionAttribute$NSAccessibilityUnitsAttribute$NSAccessibilityUnitsChangedNotification$NSAccessibilityUnknownMarkerTypeValue$NSAccessibilityUnknownOrientationValue$NSAccessibilityUnknownRole$NSAccessibilityUnknownSortDirectionValue$NSAccessibilityUnknownSubrole$NSAccessibilityUnknownUnitValue$NSAccessibilityValueAttribute$NSAccessibilityValueChangedNotification$NSAccessibilityValueDescriptionAttribute$NSAccessibilityValueIndicatorRole$NSAccessibilityVerticalOrientationValue$NSAccessibilityVerticalScrollBarAttribute$NSAccessibilityVerticalUnitDescriptionAttribute$NSAccessibilityVerticalUnitsAttribute$NSAccessibilityVisibleCellsAttribute$NSAccessibilityVisibleCharacterRangeAttribute$NSAccessibilityVisibleChildrenAttribute$NSAccessibilityVisibleColumnsAttribute$NSAccessibilityVisibleNameKey$NSAccessibilityVisibleRowsAttribute$NSAccessibilityWarningValueAttribute$NSAccessibilityWindowAttribute$NSAccessibilityWindowCreatedNotification$NSAccessibilityWindowDeminiaturizedNotification$NSAccessibilityWindowMiniaturizedNotification$NSAccessibilityWindowMovedNotification$NSAccessibilityWindowResizedNotification$NSAccessibilityWindowRole$NSAccessibilityWindowsAttribute$NSAccessibilityZoomButtonAttribute$NSAccessibilityZoomButtonSubrole$NSAlignmentBinding$NSAllRomanInputSourcesLocaleIdentifier$NSAllowsEditingMultipleValuesSelectionBindingOption$NSAllowsNullArgumentBindingOption$NSAlternateImageBinding$NSAlternateTitleBinding$NSAlwaysPresentsApplicationModalAlertsBindingOption$NSAnimateBinding$NSAnimationDelayBinding$NSAnimationProgressMark$NSAnimationProgressMarkNotification$NSAnimationTriggerOrderIn$NSAnimationTriggerOrderOut$NSAntialiasThresholdChangedNotification$NSApp$NSAppKitIgnoredException$NSAppKitVersionNumber@d$NSAppKitVirtualMemoryException$NSAppearanceNameAqua$NSAppearanceNameLightContent$NSAppearanceNameVibrantDark$NSAppearanceNameVibrantLight$NSApplicationDidBecomeActiveNotification$NSApplicationDidChangeOcclusionStateNotification$NSApplicationDidChangeScreenParametersNotification$NSApplicationDidFinishLaunchingNotification$NSApplicationDidFinishRestoringWindowsNotification$NSApplicationDidHideNotification$NSApplicationDidResignActiveNotification$NSApplicationDidUnhideNotification$NSApplicationDidUpdateNotification$NSApplicationFileType$NSApplicationLaunchIsDefaultLaunchKey$NSApplicationLaunchRemoteNotificationKey$NSApplicationLaunchUserNotificationKey$NSApplicationWillBecomeActiveNotification$NSApplicationWillFinishLaunchingNotification$NSApplicationWillHideNotification$NSApplicationWillResignActiveNotification$NSApplicationWillTerminateNotification$NSApplicationWillUnhideNotification$NSApplicationWillUpdateNotification$NSArgumentBinding$NSAttachmentAttributeName$NSAttributedStringBinding$NSAuthorDocumentAttribute$NSBackgroundColorAttributeName$NSBackgroundColorDocumentAttribute$NSBackingPropertyOldColorSpaceKey$NSBackingPropertyOldScaleFactorKey$NSBadBitmapParametersException$NSBadComparisonException$NSBadRTFColorTableException$NSBadRTFDirectiveException$NSBadRTFFontTableException$NSBadRTFStyleSheetException$NSBaseURLDocumentOption$NSBaselineOffsetAttributeName$NSBottomMarginDocumentAttribute$NSBrowserColumnConfigurationDidChangeNotification$NSBrowserIllegalDelegateException$NSCalibratedBlackColorSpace$NSCalibratedRGBColorSpace$NSCalibratedWhiteColorSpace$NSCategoryDocumentAttribute$NSCharacterEncodingDocumentAttribute$NSCharacterEncodingDocumentOption$NSCharacterShapeAttributeName$NSCocoaVersionDocumentAttribute$NSCollectionElementKindInterItemGapIndicator$NSCollectionElementKindSectionFooter$NSCollectionElementKindSectionHeader$NSColorListDidChangeNotification$NSColorListIOException$NSColorListNotEditableException$NSColorPanelColorDidChangeNotification$NSColorPboardType$NSComboBoxSelectionDidChangeNotification$NSComboBoxSelectionIsChangingNotification$NSComboBoxWillDismissNotification$NSComboBoxWillPopUpNotification$NSCommentDocumentAttribute$NSCompanyDocumentAttribute$NSConditionallySetsEditableBindingOption$NSConditionallySetsEnabledBindingOption$NSConditionallySetsHiddenBindingOption$NSContentArrayBinding$NSContentArrayForMultipleSelectionBinding$NSContentBinding$NSContentDictionaryBinding$NSContentHeightBinding$NSContentObjectBinding$NSContentObjectsBinding$NSContentPlacementTagBindingOption$NSContentSetBinding$NSContentValuesBinding$NSContentWidthBinding$NSContextHelpModeDidActivateNotification$NSContextHelpModeDidDeactivateNotification$NSContinuouslyUpdatesValueBindingOption$NSControlTextDidBeginEditingNotification$NSControlTextDidChangeNotification$NSControlTextDidEndEditingNotification$NSControlTintDidChangeNotification$NSConvertedDocumentAttribute$NSCopyrightDocumentAttribute$NSCreatesSortDescriptorBindingOption$NSCreationTimeDocumentAttribute$NSCriticalValueBinding$NSCursorAttributeName$NSCustomColorSpace$NSDataBinding$NSDefaultAttributesDocumentAttribute$NSDefaultAttributesDocumentOption$NSDefaultTabIntervalDocumentAttribute$NSDefinitionPresentationTypeDictionaryApplication$NSDefinitionPresentationTypeKey$NSDefinitionPresentationTypeOverlay$NSDeletesObjectsOnRemoveBindingsOption$NSDeviceBitsPerSample$NSDeviceBlackColorSpace$NSDeviceCMYKColorSpace$NSDeviceColorSpaceName$NSDeviceIsPrinter$NSDeviceIsScreen$NSDeviceRGBColorSpace$NSDeviceResolution$NSDeviceSize$NSDeviceWhiteColorSpace$NSDirectoryFileType$NSDisplayNameBindingOption$NSDisplayPatternBindingOption$NSDisplayPatternTitleBinding$NSDisplayPatternValueBinding$NSDocFormatTextDocumentType$NSDocumentEditedBinding$NSDocumentTypeDocumentAttribute$NSDocumentTypeDocumentOption$NSDoubleClickArgumentBinding$NSDoubleClickTargetBinding$NSDragPboard$NSDraggingException$NSDraggingImageComponentIconKey$NSDraggingImageComponentLabelKey$NSDrawerDidCloseNotification$NSDrawerDidOpenNotification$NSDrawerWillCloseNotification$NSDrawerWillOpenNotification$NSEditableBinding$NSEditorDocumentAttribute$NSEnabledBinding$NSEventTrackingRunLoopMode$NSExcludedElementsDocumentAttribute$NSExcludedKeysBinding$NSExpansionAttributeName$NSFileContentsPboardType$NSFileTypeDocumentAttribute$NSFileTypeDocumentOption$NSFilenamesPboardType$NSFilesPromisePboardType$NSFilesystemFileType$NSFilterPredicateBinding$NSFindPanelCaseInsensitiveSearch$NSFindPanelSearchOptionsPboardType$NSFindPanelSubstringMatch$NSFindPboard$NSFontAttributeName$NSFontBinding$NSFontBoldBinding$NSFontCascadeListAttribute$NSFontCharacterSetAttribute$NSFontCollectionActionKey$NSFontCollectionAllFonts$NSFontCollectionDidChangeNotification$NSFontCollectionDisallowAutoActivationOption$NSFontCollectionFavorites$NSFontCollectionIncludeDisabledFontsOption$NSFontCollectionNameKey$NSFontCollectionOldNameKey$NSFontCollectionRecentlyUsed$NSFontCollectionRemoveDuplicatesOption$NSFontCollectionUser$NSFontCollectionVisibilityKey$NSFontCollectionWasHidden$NSFontCollectionWasRenamed$NSFontCollectionWasShown$NSFontColorAttribute$NSFontFaceAttribute$NSFontFamilyAttribute$NSFontFamilyNameBinding$NSFontFeatureSelectorIdentifierKey$NSFontFeatureSettingsAttribute$NSFontFeatureTypeIdentifierKey$NSFontFixedAdvanceAttribute$NSFontItalicBinding$NSFontMatrixAttribute$NSFontNameAttribute$NSFontNameBinding$NSFontPboard$NSFontPboardType$NSFontSetChangedNotification$NSFontSizeAttribute$NSFontSizeBinding$NSFontSlantTrait$NSFontSymbolicTrait$NSFontTraitsAttribute$NSFontUnavailableException$NSFontVariationAttribute$NSFontVariationAxisDefaultValueKey$NSFontVariationAxisIdentifierKey$NSFontVariationAxisMaximumValueKey$NSFontVariationAxisMinimumValueKey$NSFontVariationAxisNameKey$NSFontVisibleNameAttribute$NSFontWeightBlack@f$NSFontWeightBold@f$NSFontWeightHeavy@f$NSFontWeightLight@f$NSFontWeightMedium@f$NSFontWeightRegular@f$NSFontWeightSemibold@f$NSFontWeightThin@f$NSFontWeightTrait$NSFontWeightUltraLight@f$NSFontWidthTrait$NSForegroundColorAttributeName$NSFullScreenModeAllScreens$NSFullScreenModeApplicationPresentationOptions$NSFullScreenModeSetting$NSFullScreenModeWindowLevel$NSGeneralPboard$NSGlyphInfoAttributeName$NSGraphicsContextDestinationAttributeName$NSGraphicsContextPDFFormat$NSGraphicsContextPSFormat$NSGraphicsContextRepresentationFormatAttributeName$NSGridViewSizeForContent@d$NSHTMLPboardType$NSHTMLTextDocumentType$NSHandlesContentAsCompoundValueBindingOption$NSHeaderTitleBinding$NSHiddenBinding$NSHyphenationFactorDocumentAttribute$NSIllegalSelectorException$NSImageBinding$NSImageCacheException$NSImageColorSyncProfileData$NSImageCompressionFactor$NSImageCompressionMethod$NSImageCurrentFrame$NSImageCurrentFrameDuration$NSImageDitherTransparency$NSImageEXIFData$NSImageFallbackBackgroundColor$NSImageFrameCount$NSImageGamma$NSImageHintCTM$NSImageHintInterpolation$NSImageHintUserInterfaceLayoutDirection$NSImageInterlaced$NSImageLoopCount$NSImageNameActionTemplate$NSImageNameAddTemplate$NSImageNameAdvanced$NSImageNameApplicationIcon$NSImageNameBluetoothTemplate$NSImageNameBonjour$NSImageNameBookmarksTemplate$NSImageNameCaution$NSImageNameColorPanel$NSImageNameColumnViewTemplate$NSImageNameComputer$NSImageNameDotMac$NSImageNameEnterFullScreenTemplate$NSImageNameEveryone$NSImageNameExitFullScreenTemplate$NSImageNameFlowViewTemplate$NSImageNameFolder$NSImageNameFolderBurnable$NSImageNameFolderSmart$NSImageNameFollowLinkFreestandingTemplate$NSImageNameFontPanel$NSImageNameGoBackTemplate$NSImageNameGoForwardTemplate$NSImageNameGoLeftTemplate$NSImageNameGoRightTemplate$NSImageNameHomeTemplate$NSImageNameIChatTheaterTemplate$NSImageNameIconViewTemplate$NSImageNameInfo$NSImageNameInvalidDataFreestandingTemplate$NSImageNameLeftFacingTriangleTemplate$NSImageNameListViewTemplate$NSImageNameLockLockedTemplate$NSImageNameLockUnlockedTemplate$NSImageNameMenuMixedStateTemplate$NSImageNameMenuOnStateTemplate$NSImageNameMobileMe$NSImageNameMultipleDocuments$NSImageNameNetwork$NSImageNamePathTemplate$NSImageNamePreferencesGeneral$NSImageNameQuickLookTemplate$NSImageNameRefreshFreestandingTemplate$NSImageNameRefreshTemplate$NSImageNameRemoveTemplate$NSImageNameRevealFreestandingTemplate$NSImageNameRightFacingTriangleTemplate$NSImageNameShareTemplate$NSImageNameSlideshowTemplate$NSImageNameSmartBadgeTemplate$NSImageNameStatusAvailable$NSImageNameStatusNone$NSImageNameStatusPartiallyAvailable$NSImageNameStatusUnavailable$NSImageNameStopProgressFreestandingTemplate$NSImageNameStopProgressTemplate$NSImageNameTouchBarAddDetailTemplate$NSImageNameTouchBarAddTemplate$NSImageNameTouchBarAlarmTemplate$NSImageNameTouchBarAudioInputMuteTemplate$NSImageNameTouchBarAudioInputTemplate$NSImageNameTouchBarAudioOutputMuteTemplate$NSImageNameTouchBarAudioOutputVolumeHighTemplate$NSImageNameTouchBarAudioOutputVolumeLowTemplate$NSImageNameTouchBarAudioOutputVolumeMediumTemplate$NSImageNameTouchBarAudioOutputVolumeOffTemplate$NSImageNameTouchBarBookmarksTemplate$NSImageNameTouchBarColorPickerFill$NSImageNameTouchBarColorPickerFont$NSImageNameTouchBarColorPickerStroke$NSImageNameTouchBarCommunicationAudioTemplate$NSImageNameTouchBarCommunicationVideoTemplate$NSImageNameTouchBarComposeTemplate$NSImageNameTouchBarDeleteTemplate$NSImageNameTouchBarDownloadTemplate$NSImageNameTouchBarEnterFullScreenTemplate$NSImageNameTouchBarExitFullScreenTemplate$NSImageNameTouchBarFastForwardTemplate$NSImageNameTouchBarFolderCopyToTemplate$NSImageNameTouchBarFolderMoveToTemplate$NSImageNameTouchBarFolderTemplate$NSImageNameTouchBarGetInfoTemplate$NSImageNameTouchBarGoBackTemplate$NSImageNameTouchBarGoDownTemplate$NSImageNameTouchBarGoForwardTemplate$NSImageNameTouchBarGoUpTemplate$NSImageNameTouchBarHistoryTemplate$NSImageNameTouchBarIconViewTemplate$NSImageNameTouchBarListViewTemplate$NSImageNameTouchBarMailTemplate$NSImageNameTouchBarNewFolderTemplate$NSImageNameTouchBarNewMessageTemplate$NSImageNameTouchBarOpenInBrowserTemplate$NSImageNameTouchBarPauseTemplate$NSImageNameTouchBarPlayPauseTemplate$NSImageNameTouchBarPlayTemplate$NSImageNameTouchBarPlayheadTemplate$NSImageNameTouchBarQuickLookTemplate$NSImageNameTouchBarRecordStartTemplate$NSImageNameTouchBarRecordStopTemplate$NSImageNameTouchBarRefreshTemplate$NSImageNameTouchBarRemoveTemplate$NSImageNameTouchBarRewindTemplate$NSImageNameTouchBarRotateLeftTemplate$NSImageNameTouchBarRotateRightTemplate$NSImageNameTouchBarSearchTemplate$NSImageNameTouchBarShareTemplate$NSImageNameTouchBarSidebarTemplate$NSImageNameTouchBarSkipAhead15SecondsTemplate$NSImageNameTouchBarSkipAhead30SecondsTemplate$NSImageNameTouchBarSkipAheadTemplate$NSImageNameTouchBarSkipBack15SecondsTemplate$NSImageNameTouchBarSkipBack30SecondsTemplate$NSImageNameTouchBarSkipBackTemplate$NSImageNameTouchBarSkipToEndTemplate$NSImageNameTouchBarSkipToStartTemplate$NSImageNameTouchBarSlideshowTemplate$NSImageNameTouchBarTagIconTemplate$NSImageNameTouchBarTextBoldTemplate$NSImageNameTouchBarTextBoxTemplate$NSImageNameTouchBarTextCenterAlignTemplate$NSImageNameTouchBarTextItalicTemplate$NSImageNameTouchBarTextJustifiedAlignTemplate$NSImageNameTouchBarTextLeftAlignTemplate$NSImageNameTouchBarTextListTemplate$NSImageNameTouchBarTextRightAlignTemplate$NSImageNameTouchBarTextStrikethroughTemplate$NSImageNameTouchBarTextUnderlineTemplate$NSImageNameTouchBarUserAddTemplate$NSImageNameTouchBarUserGroupTemplate$NSImageNameTouchBarUserTemplate$NSImageNameTouchBarVolumeDownTemplate$NSImageNameTouchBarVolumeUpTemplate$NSImageNameTrashEmpty$NSImageNameTrashFull$NSImageNameUser$NSImageNameUserAccounts$NSImageNameUserGroup$NSImageNameUserGuest$NSImageProgressive$NSImageRGBColorTable$NSImageRepRegistryDidChangeNotification$NSIncludedKeysBinding$NSInitialKeyBinding$NSInitialValueBinding$NSInkTextPboardType$NSInsertsNullPlaceholderBindingOption$NSInterfaceStyleDefault$NSInvokesSeparatelyWithArrayObjectsBindingOption$NSIsIndeterminateBinding$NSKernAttributeName$NSKeywordsDocumentAttribute$NSLabelBinding$NSLeftMarginDocumentAttribute$NSLigatureAttributeName$NSLinkAttributeName$NSLocalizedKeyDictionaryBinding$NSMacSimpleTextDocumentType$NSManagedObjectContextBinding$NSManagerDocumentAttribute$NSMarkedClauseSegmentAttributeName$NSMaxValueBinding$NSMaxWidthBinding$NSMaximumRecentsBinding$NSMenuDidAddItemNotification$NSMenuDidBeginTrackingNotification$NSMenuDidChangeItemNotification$NSMenuDidEndTrackingNotification$NSMenuDidRemoveItemNotification$NSMenuDidSendActionNotification$NSMenuWillSendActionNotification$NSMinValueBinding$NSMinWidthBinding$NSMixedStateImageBinding$NSModalPanelRunLoopMode$NSModificationTimeDocumentAttribute$NSMultipleTextSelectionPboardType$NSMultipleValuesMarker$NSMultipleValuesPlaceholderBindingOption$NSNamedColorSpace$NSNibLoadingException$NSNibOwner$NSNibTopLevelObjects$NSNoSelectionMarker$NSNoSelectionPlaceholderBindingOption$NSNotApplicableMarker$NSNotApplicablePlaceholderBindingOption$NSNullPlaceholderBindingOption$NSObliquenessAttributeName$NSObservedKeyPathKey$NSObservedObjectKey$NSOffStateImageBinding$NSOfficeOpenXMLTextDocumentType$NSOnStateImageBinding$NSOpenDocumentTextDocumentType$NSOptionsKey$NSOutlineViewColumnDidMoveNotification$NSOutlineViewColumnDidResizeNotification$NSOutlineViewDisclosureButtonKey$NSOutlineViewItemDidCollapseNotification$NSOutlineViewItemDidExpandNotification$NSOutlineViewItemWillCollapseNotification$NSOutlineViewItemWillExpandNotification$NSOutlineViewSelectionDidChangeNotification$NSOutlineViewSelectionIsChangingNotification$NSOutlineViewShowHideButtonKey$NSPDFPboardType$NSPICTPboardType$NSPPDIncludeNotFoundException$NSPPDIncludeStackOverflowException$NSPPDIncludeStackUnderflowException$NSPPDParseException$NSPaperSizeDocumentAttribute$NSParagraphStyleAttributeName$NSPasteboardCommunicationException$NSPasteboardNameDrag$NSPasteboardNameFind$NSPasteboardNameFont$NSPasteboardNameGeneral$NSPasteboardNameRuler$NSPasteboardTypeColor$NSPasteboardTypeFileURL$NSPasteboardTypeFindPanelSearchOptions$NSPasteboardTypeFont$NSPasteboardTypeHTML$NSPasteboardTypeMultipleTextSelection$NSPasteboardTypePDF$NSPasteboardTypePNG$NSPasteboardTypeRTF$NSPasteboardTypeRTFD$NSPasteboardTypeRuler$NSPasteboardTypeSound$NSPasteboardTypeString$NSPasteboardTypeTIFF$NSPasteboardTypeTabularText$NSPasteboardTypeTextFinderOptions$NSPasteboardTypeURL$NSPasteboardURLReadingContentsConformToTypesKey$NSPasteboardURLReadingFileURLsOnlyKey$NSPatternColorSpace$NSPlainFileType$NSPlainTextDocumentType$NSPopUpButtonCellWillPopUpNotification$NSPopUpButtonWillPopUpNotification$NSPopoverCloseReasonDetachToWindow$NSPopoverCloseReasonKey$NSPopoverCloseReasonStandard$NSPopoverDidCloseNotification$NSPopoverDidShowNotification$NSPopoverWillCloseNotification$NSPopoverWillShowNotification$NSPositioningRectBinding$NSPostScriptPboardType$NSPredicateBinding$NSPredicateFormatBindingOption$NSPreferredScrollerStyleDidChangeNotification$NSPrefixSpacesDocumentAttribute$NSPrintAllPages$NSPrintAllPresetsJobStyleHint$NSPrintBottomMargin$NSPrintCancelJob$NSPrintCopies$NSPrintDetailedErrorReporting$NSPrintFaxCoverSheetName$NSPrintFaxHighResolution$NSPrintFaxJob$NSPrintFaxModem$NSPrintFaxNumber$NSPrintFaxReceiverNames$NSPrintFaxReceiverNumbers$NSPrintFaxReturnReceipt$NSPrintFaxSendTime$NSPrintFaxTrimPageEnds$NSPrintFaxUseCoverSheet$NSPrintFirstPage$NSPrintFormName$NSPrintHeaderAndFooter$NSPrintHorizontalPagination$NSPrintHorizontallyCentered$NSPrintJobDisposition$NSPrintJobFeatures$NSPrintJobSavingFileNameExtensionHidden$NSPrintJobSavingURL$NSPrintLastPage$NSPrintLeftMargin$NSPrintManualFeed$NSPrintMustCollate$NSPrintNoPresetsJobStyleHint$NSPrintOperationExistsException$NSPrintOrientation$NSPrintPackageException$NSPrintPagesAcross$NSPrintPagesDown$NSPrintPagesPerSheet$NSPrintPanelAccessorySummaryItemDescriptionKey$NSPrintPanelAccessorySummaryItemNameKey$NSPrintPaperFeed$NSPrintPaperName$NSPrintPaperSize$NSPrintPhotoJobStyleHint$NSPrintPreviewJob$NSPrintPrinter$NSPrintPrinterName$NSPrintReversePageOrder$NSPrintRightMargin$NSPrintSaveJob$NSPrintSavePath$NSPrintScalingFactor$NSPrintSelectionOnly$NSPrintSpoolJob$NSPrintTime$NSPrintTopMargin$NSPrintVerticalPagination$NSPrintVerticallyCentered$NSPrintingCommunicationException$NSRTFDPboardType$NSRTFDTextDocumentType$NSRTFPboardType$NSRTFPropertyStackOverflowException$NSRTFTextDocumentType$NSRaisesForNotApplicableKeysBindingOption$NSReadOnlyDocumentAttribute$NSRecentSearchesBinding$NSRepresentedFilenameBinding$NSRightMarginDocumentAttribute$NSRowHeightBinding$NSRuleEditorPredicateComparisonModifier$NSRuleEditorPredicateCompoundType$NSRuleEditorPredicateCustomSelector$NSRuleEditorPredicateLeftExpression$NSRuleEditorPredicateOperatorType$NSRuleEditorPredicateOptions$NSRuleEditorPredicateRightExpression$NSRuleEditorRowsDidChangeNotification$NSRulerPboard$NSRulerPboardType$NSRulerViewUnitCentimeters$NSRulerViewUnitInches$NSRulerViewUnitPicas$NSRulerViewUnitPoints$NSScreenColorSpaceDidChangeNotification$NSScrollViewDidEndLiveMagnifyNotification$NSScrollViewDidEndLiveScrollNotification$NSScrollViewDidLiveScrollNotification$NSScrollViewWillStartLiveMagnifyNotification$NSScrollViewWillStartLiveScrollNotification$NSSelectedIdentifierBinding$NSSelectedIndexBinding$NSSelectedLabelBinding$NSSelectedObjectBinding$NSSelectedObjectsBinding$NSSelectedTagBinding$NSSelectedValueBinding$NSSelectedValuesBinding$NSSelectionIndexPathsBinding$NSSelectionIndexesBinding$NSSelectorNameBindingOption$NSSelectsAllWhenSettingContentBindingOption$NSShadowAttributeName$NSSharingServiceNameAddToAperture$NSSharingServiceNameAddToIPhoto$NSSharingServiceNameAddToSafariReadingList$NSSharingServiceNameCloudSharing$NSSharingServiceNameComposeEmail$NSSharingServiceNameComposeMessage$NSSharingServiceNamePostImageOnFlickr$NSSharingServiceNamePostOnFacebook$NSSharingServiceNamePostOnLinkedIn$NSSharingServiceNamePostOnSinaWeibo$NSSharingServiceNamePostOnTencentWeibo$NSSharingServiceNamePostOnTwitter$NSSharingServiceNamePostVideoOnTudou$NSSharingServiceNamePostVideoOnVimeo$NSSharingServiceNamePostVideoOnYouku$NSSharingServiceNameSendViaAirDrop$NSSharingServiceNameUseAsDesktopPicture$NSSharingServiceNameUseAsFacebookProfileImage$NSSharingServiceNameUseAsLinkedInProfileImage$NSSharingServiceNameUseAsTwitterProfileImage$NSShellCommandFileType$NSSortDescriptorsBinding$NSSoundPboardType$NSSpeechCharacterModeProperty$NSSpeechCommandDelimiterProperty$NSSpeechCommandPrefix$NSSpeechCommandSuffix$NSSpeechCurrentVoiceProperty$NSSpeechDictionaryAbbreviations$NSSpeechDictionaryEntryPhonemes$NSSpeechDictionaryEntrySpelling$NSSpeechDictionaryLocaleIdentifier$NSSpeechDictionaryModificationDate$NSSpeechDictionaryPronunciations$NSSpeechErrorCount$NSSpeechErrorNewestCharacterOffset$NSSpeechErrorNewestCode$NSSpeechErrorOldestCharacterOffset$NSSpeechErrorOldestCode$NSSpeechErrorsProperty$NSSpeechInputModeProperty$NSSpeechModeLiteral$NSSpeechModeNormal$NSSpeechModePhoneme$NSSpeechModeText$NSSpeechNumberModeProperty$NSSpeechOutputToFileURLProperty$NSSpeechPhonemeInfoExample$NSSpeechPhonemeInfoHiliteEnd$NSSpeechPhonemeInfoHiliteStart$NSSpeechPhonemeInfoOpcode$NSSpeechPhonemeInfoSymbol$NSSpeechPhonemeSymbolsProperty$NSSpeechPitchBaseProperty$NSSpeechPitchModProperty$NSSpeechRateProperty$NSSpeechRecentSyncProperty$NSSpeechResetProperty$NSSpeechStatusNumberOfCharactersLeft$NSSpeechStatusOutputBusy$NSSpeechStatusOutputPaused$NSSpeechStatusPhonemeCode$NSSpeechStatusProperty$NSSpeechSynthesizerInfoIdentifier$NSSpeechSynthesizerInfoProperty$NSSpeechSynthesizerInfoVersion$NSSpeechVolumeProperty$NSSpellCheckerDidChangeAutomaticCapitalizationNotification$NSSpellCheckerDidChangeAutomaticDashSubstitutionNotification$NSSpellCheckerDidChangeAutomaticPeriodSubstitutionNotification$NSSpellCheckerDidChangeAutomaticQuoteSubstitutionNotification$NSSpellCheckerDidChangeAutomaticSpellingCorrectionNotification$NSSpellCheckerDidChangeAutomaticTextCompletionNotification$NSSpellCheckerDidChangeAutomaticTextReplacementNotification$NSSpellingStateAttributeName$NSSplitViewControllerAutomaticDimension@f$NSSplitViewDidResizeSubviewsNotification$NSSplitViewItemUnspecifiedDimension@f$NSSplitViewWillResizeSubviewsNotification$NSStrikethroughColorAttributeName$NSStrikethroughStyleAttributeName$NSStringPboardType$NSStrokeColorAttributeName$NSStrokeWidthAttributeName$NSSubjectDocumentAttribute$NSSuperscriptAttributeName$NSSystemColorsDidChangeNotification$NSTIFFException$NSTIFFPboardType$NSTabColumnTerminatorsAttributeName$NSTableViewColumnDidMoveNotification$NSTableViewColumnDidResizeNotification$NSTableViewRowViewKey$NSTableViewSelectionDidChangeNotification$NSTableViewSelectionIsChangingNotification$NSTabularTextPboardType$NSTargetBinding$NSTextAlternativesAttributeName$NSTextAlternativesSelectedAlternativeStringNotification$NSTextCheckingDocumentAuthorKey$NSTextCheckingDocumentTitleKey$NSTextCheckingDocumentURLKey$NSTextCheckingOrthographyKey$NSTextCheckingQuotesKey$NSTextCheckingReferenceDateKey$NSTextCheckingReferenceTimeZoneKey$NSTextCheckingRegularExpressionsKey$NSTextCheckingReplacementsKey$NSTextCheckingSelectedRangeKey$NSTextColorBinding$NSTextDidBeginEditingNotification$NSTextDidChangeNotification$NSTextDidEndEditingNotification$NSTextEffectAttributeName$NSTextEffectLetterpressStyle$NSTextEncodingNameDocumentAttribute$NSTextEncodingNameDocumentOption$NSTextFinderCaseInsensitiveKey$NSTextFinderMatchingTypeKey$NSTextInputContextKeyboardSelectionDidChangeNotification$NSTextLayoutSectionOrientation$NSTextLayoutSectionRange$NSTextLayoutSectionsAttribute$NSTextLineTooLongException$NSTextListMarkerBox$NSTextListMarkerCheck$NSTextListMarkerCircle$NSTextListMarkerDecimal$NSTextListMarkerDiamond$NSTextListMarkerDisc$NSTextListMarkerHyphen$NSTextListMarkerLowercaseAlpha$NSTextListMarkerLowercaseHexadecimal$NSTextListMarkerLowercaseLatin$NSTextListMarkerLowercaseRoman$NSTextListMarkerOctal$NSTextListMarkerSquare$NSTextListMarkerUppercaseAlpha$NSTextListMarkerUppercaseHexadecimal$NSTextListMarkerUppercaseLatin$NSTextListMarkerUppercaseRoman$NSTextMovementUserInfoKey$NSTextNoSelectionException$NSTextReadException$NSTextSizeMultiplierDocumentOption$NSTextStorageDidProcessEditingNotification$NSTextStorageWillProcessEditingNotification$NSTextViewDidChangeSelectionNotification$NSTextViewDidChangeTypingAttributesNotification$NSTextViewWillChangeNotifyingTextViewNotification$NSTextWriteException$NSTimeoutDocumentOption$NSTitleBinding$NSTitleDocumentAttribute$NSToolTipAttributeName$NSToolTipBinding$NSToolbarCloudSharingItemIdentifier$NSToolbarCustomizeToolbarItemIdentifier$NSToolbarDidRemoveItemNotification$NSToolbarFlexibleSpaceItemIdentifier$NSToolbarPrintItemIdentifier$NSToolbarSeparatorItemIdentifier$NSToolbarShowColorsItemIdentifier$NSToolbarShowFontsItemIdentifier$NSToolbarSpaceItemIdentifier$NSToolbarToggleSidebarItemIdentifier$NSToolbarWillAddItemNotification$NSTopMarginDocumentAttribute$NSTouchBarItemIdentifierCandidateList$NSTouchBarItemIdentifierCharacterPicker$NSTouchBarItemIdentifierFixedSpaceLarge$NSTouchBarItemIdentifierFixedSpaceSmall$NSTouchBarItemIdentifierFlexibleSpace$NSTouchBarItemIdentifierOtherItemsProxy$NSTouchBarItemIdentifierTextAlignment$NSTouchBarItemIdentifierTextColorPicker$NSTouchBarItemIdentifierTextFormat$NSTouchBarItemIdentifierTextList$NSTouchBarItemIdentifierTextStyle$NSTransparentBinding$NSTypeIdentifierAddressText$NSTypeIdentifierDateText$NSTypeIdentifierPhoneNumberText$NSTypeIdentifierTransitInformationText$NSTypedStreamVersionException$NSURLPboardType$NSUnderlineColorAttributeName$NSUnderlineStyleAttributeName$NSUserActivityDocumentURLKey$NSUsesScreenFontsDocumentAttribute$NSVCardPboardType$NSValidatesImmediatelyBindingOption$NSValueBinding$NSValuePathBinding$NSValueTransformerBindingOption$NSValueTransformerNameBindingOption$NSValueURLBinding$NSVerticalGlyphFormAttributeName$NSViewAnimationEffectKey$NSViewAnimationEndFrameKey$NSViewAnimationFadeInEffect$NSViewAnimationFadeOutEffect$NSViewAnimationStartFrameKey$NSViewAnimationTargetKey$NSViewBoundsDidChangeNotification$NSViewDidUpdateTrackingAreasNotification$NSViewFocusDidChangeNotification$NSViewFrameDidChangeNotification$NSViewGlobalFrameDidChangeNotification$NSViewModeDocumentAttribute$NSViewNoIntrinsicMetric@f$NSViewSizeDocumentAttribute$NSViewZoomDocumentAttribute$NSVisibleBinding$NSVoiceAge$NSVoiceDemoText$NSVoiceGender$NSVoiceGenderFemale$NSVoiceGenderMale$NSVoiceGenderNeuter$NSVoiceIdentifier$NSVoiceIndividuallySpokenCharacters$NSVoiceLanguage$NSVoiceLocaleIdentifier$NSVoiceName$NSVoiceSupportedCharacters$NSWarningValueBinding$NSWebArchiveTextDocumentType$NSWebPreferencesDocumentOption$NSWebResourceLoadDelegateDocumentOption$NSWidthBinding$NSWindowDidBecomeKeyNotification$NSWindowDidBecomeMainNotification$NSWindowDidChangeBackingPropertiesNotification$NSWindowDidChangeOcclusionStateNotification$NSWindowDidChangeScreenNotification$NSWindowDidChangeScreenProfileNotification$NSWindowDidDeminiaturizeNotification$NSWindowDidEndLiveResizeNotification$NSWindowDidEndSheetNotification$NSWindowDidEnterFullScreenNotification$NSWindowDidEnterVersionBrowserNotification$NSWindowDidExitFullScreenNotification$NSWindowDidExitVersionBrowserNotification$NSWindowDidExposeNotification$NSWindowDidMiniaturizeNotification$NSWindowDidMoveNotification$NSWindowDidResignKeyNotification$NSWindowDidResignMainNotification$NSWindowDidResizeNotification$NSWindowDidUpdateNotification$NSWindowServerCommunicationException$NSWindowWillBeginSheetNotification$NSWindowWillCloseNotification$NSWindowWillEnterFullScreenNotification$NSWindowWillEnterVersionBrowserNotification$NSWindowWillExitFullScreenNotification$NSWindowWillExitVersionBrowserNotification$NSWindowWillMiniaturizeNotification$NSWindowWillMoveNotification$NSWindowWillStartLiveResizeNotification$NSWordMLTextDocumentType$NSWordTablesReadException$NSWordTablesWriteException$NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification$NSWorkspaceActiveSpaceDidChangeNotification$NSWorkspaceApplicationKey$NSWorkspaceCompressOperation$NSWorkspaceCopyOperation$NSWorkspaceDecompressOperation$NSWorkspaceDecryptOperation$NSWorkspaceDesktopImageAllowClippingKey$NSWorkspaceDesktopImageFillColorKey$NSWorkspaceDesktopImageScalingKey$NSWorkspaceDestroyOperation$NSWorkspaceDidActivateApplicationNotification$NSWorkspaceDidChangeFileLabelsNotification$NSWorkspaceDidDeactivateApplicationNotification$NSWorkspaceDidHideApplicationNotification$NSWorkspaceDidLaunchApplicationNotification$NSWorkspaceDidMountNotification$NSWorkspaceDidPerformFileOperationNotification$NSWorkspaceDidRenameVolumeNotification$NSWorkspaceDidTerminateApplicationNotification$NSWorkspaceDidUnhideApplicationNotification$NSWorkspaceDidUnmountNotification$NSWorkspaceDidWakeNotification$NSWorkspaceDuplicateOperation$NSWorkspaceEncryptOperation$NSWorkspaceLaunchConfigurationAppleEvent$NSWorkspaceLaunchConfigurationArchitecture$NSWorkspaceLaunchConfigurationArguments$NSWorkspaceLaunchConfigurationEnvironment$NSWorkspaceLinkOperation$NSWorkspaceMoveOperation$NSWorkspaceRecycleOperation$NSWorkspaceScreensDidSleepNotification$NSWorkspaceScreensDidWakeNotification$NSWorkspaceSessionDidBecomeActiveNotification$NSWorkspaceSessionDidResignActiveNotification$NSWorkspaceVolumeLocalizedNameKey$NSWorkspaceVolumeOldLocalizedNameKey$NSWorkspaceVolumeOldURLKey$NSWorkspaceVolumeURLKey$NSWorkspaceWillLaunchApplicationNotification$NSWorkspaceWillPowerOffNotification$NSWorkspaceWillSleepNotification$NSWorkspaceWillUnmountNotification$NSWritingDirectionAttributeName$'''
constants = constants + '$NSBlack@%s$'%(sel32or64('f', 'd'),)
constants = constants + '$NSViewNoInstrinsicMetric@%s$'%(sel32or64('f', 'd'),)
constants = constants + '$NSDarkGray@%s$'%(sel32or64('f', 'd'),)
constants = constants + '$NSWhite@%s$'%(sel32or64('f', 'd'),)
constants = constants + '$NSFontIdentityMatrix@%s$'%(sel32or64('^f', '^d'),)
constants = constants + '$NSLightGray@%s$'%(sel32or64('f', 'd'),)
constants = constants + '$NSUnderlineStrikethroughMask@%s$'%(sel32or64('I', 'Q'),)
constants = constants + '$NSUnderlineByWordMask@%s$'%(sel32or64('I', 'Q'),)
enums = '''$NS16BitBigEndianBitmapFormat@1024$NS16BitLittleEndianBitmapFormat@256$NS32BitBigEndianBitmapFormat@2048$NS32BitLittleEndianBitmapFormat@512$NSAWTEventType@16$NSAboveBottom@4$NSAboveTop@1$NSAcceleratorButton@8$NSAccessibilityAnnotationPositionEnd@2$NSAccessibilityAnnotationPositionFullRange@0$NSAccessibilityAnnotationPositionStart@1$NSAccessibilityCustomRotorSearchDirectionNext@1$NSAccessibilityCustomRotorSearchDirectionPrevious@0$NSAccessibilityCustomRotorTypeAnnotation@2$NSAccessibilityCustomRotorTypeAny@1$NSAccessibilityCustomRotorTypeBoldText@3$NSAccessibilityCustomRotorTypeCustom@0$NSAccessibilityCustomRotorTypeHeading@4$NSAccessibilityCustomRotorTypeHeadingLevel1@5$NSAccessibilityCustomRotorTypeHeadingLevel2@6$NSAccessibilityCustomRotorTypeHeadingLevel3@7$NSAccessibilityCustomRotorTypeHeadingLevel4@8$NSAccessibilityCustomRotorTypeHeadingLevel5@9$NSAccessibilityCustomRotorTypeHeadingLevel6@10$NSAccessibilityCustomRotorTypeImage@11$NSAccessibilityCustomRotorTypeItalicText@12$NSAccessibilityCustomRotorTypeLandmark@13$NSAccessibilityCustomRotorTypeLink@14$NSAccessibilityCustomRotorTypeList@15$NSAccessibilityCustomRotorTypeMisspelledWord@16$NSAccessibilityCustomRotorTypeTable@17$NSAccessibilityCustomRotorTypeTextField@18$NSAccessibilityCustomRotorTypeUnderlinedText@19$NSAccessibilityCustomRotorTypeVisitedLink@20$NSAccessibilityOrientationHorizontal@2$NSAccessibilityOrientationUnknown@0$NSAccessibilityOrientationVertical@1$NSAccessibilityPriorityHigh@90$NSAccessibilityPriorityLow@10$NSAccessibilityPriorityMedium@50$NSAccessibilityRulerMarkerTypeIndentFirstLine@7$NSAccessibilityRulerMarkerTypeIndentHead@5$NSAccessibilityRulerMarkerTypeIndentTail@6$NSAccessibilityRulerMarkerTypeTabStopCenter@3$NSAccessibilityRulerMarkerTypeTabStopDecimal@4$NSAccessibilityRulerMarkerTypeTabStopLeft@1$NSAccessibilityRulerMarkerTypeTabStopRight@2$NSAccessibilityRulerMarkerTypeUnknown@0$NSAccessibilitySortDirectionAscending@1$NSAccessibilitySortDirectionDescending@2$NSAccessibilitySortDirectionUnknown@0$NSAccessibilityUnitsCentimeters@2$NSAccessibilityUnitsInches@1$NSAccessibilityUnitsPicas@4$NSAccessibilityUnitsPoints@3$NSAccessibilityUnitsUnknown@0$NSAddTraitFontAction@2$NSAdobeCNS1CharacterCollection@1$NSAdobeGB1CharacterCollection@2$NSAdobeJapan1CharacterCollection@3$NSAdobeJapan2CharacterCollection@4$NSAdobeKorea1CharacterCollection@5$NSAlertAlternateReturn@0$NSAlertDefaultReturn@1$NSAlertErrorReturn@-2$NSAlertFirstButtonReturn@1000$NSAlertOtherReturn@-1$NSAlertSecondButtonReturn@1001$NSAlertStyleCritical@2$NSAlertStyleInformational@1$NSAlertStyleWarning@0$NSAlertThirdButtonReturn@1002$NSAllScrollerParts@2$NSAlphaFirstBitmapFormat@1$NSAlphaNonpremultipliedBitmapFormat@2$NSAlphaShiftKeyMask@65536$NSAlternateKeyMask@524288$NSAnimationBlocking@0$NSAnimationEaseIn@1$NSAnimationEaseInOut@0$NSAnimationEaseOut@2$NSAnimationEffectDisappearingItemDefault@0$NSAnimationEffectPoof@10$NSAnimationLinear@3$NSAnimationNonblocking@1$NSAnimationNonblockingThreaded@2$NSAnyType@0$NSAppKitDefined@13$NSAppKitDefinedMask@8192$NSAppKitVersionNumber10_0@577$NSAppKitVersionNumber10_1@620$NSAppKitVersionNumber10_10@1343$NSAppKitVersionNumber10_10_2@1344$NSAppKitVersionNumber10_10_3@1347$NSAppKitVersionNumber10_10_4@1348$NSAppKitVersionNumber10_10_5@1348$NSAppKitVersionNumber10_10_Max@1349$NSAppKitVersionNumber10_11@1404.0$NSAppKitVersionNumber10_11_1@1404.13$NSAppKitVersionNumber10_11_2@1404.34$NSAppKitVersionNumber10_11_3@1404.34$NSAppKitVersionNumber10_12@1504$NSAppKitVersionNumber10_12_1@1504.6$NSAppKitVersionNumber10_12_2@1504.76$NSAppKitVersionNumber10_2@663$NSAppKitVersionNumber10_3@743$NSAppKitVersionNumber10_4@824$NSAppKitVersionNumber10_5@949$NSAppKitVersionNumber10_6@1038$NSAppKitVersionNumber10_7@1138$NSAppKitVersionNumber10_8@1187$NSAppKitVersionNumber10_9@1265$NSApplicationActivateAllWindows@1$NSApplicationActivateIgnoringOtherApps@2$NSApplicationActivatedEventType@1$NSApplicationActivationPolicyAccessory@1$NSApplicationActivationPolicyProhibited@2$NSApplicationActivationPolicyRegular@0$NSApplicationDeactivatedEventType@2$NSApplicationDefined@15$NSApplicationDefinedMask@32768$NSApplicationDelegateReplyCancel@1$NSApplicationDelegateReplyFailure@2$NSApplicationDelegateReplySuccess@0$NSApplicationOcclusionStateVisible@2$NSApplicationPresentationAutoHideDock@1$NSApplicationPresentationAutoHideMenuBar@4$NSApplicationPresentationAutoHideToolbar@2048$NSApplicationPresentationDefault@0$NSApplicationPresentationDisableAppleMenu@16$NSApplicationPresentationDisableCursorLocationAssistance@4096$NSApplicationPresentationDisableForceQuit@64$NSApplicationPresentationDisableHideApplication@256$NSApplicationPresentationDisableMenuBarTransparency@512$NSApplicationPresentationDisableProcessSwitching@32$NSApplicationPresentationDisableSessionTermination@128$NSApplicationPresentationFullScreen@1024$NSApplicationPresentationHideDock@2$NSApplicationPresentationHideMenuBar@8$NSAscendingPageOrder@1$NSAsciiWithDoubleByteEUCGlyphPacking@2$NSAtBottom@5$NSAtTop@2$NSAutoPagination@0$NSAutosaveAsOperation@5$NSAutosaveElsewhereOperation@3$NSAutosaveInPlaceOperation@4$NSAutosaveOperation@3$NSBMPFileType@1$NSBackTabCharacter@25$NSBackgroundStyleDark@1$NSBackgroundStyleLight@0$NSBackgroundStyleLowered@3$NSBackgroundStyleRaised@2$NSBackgroundTab@1$NSBackingStoreBuffered@2$NSBackingStoreNonretained@1$NSBackingStoreRetained@0$NSBackspaceCharacter@8$NSBacktabTextMovement@18$NSBeginFunctionKey@63274$NSBelowBottom@6$NSBelowTop@3$NSBevelLineJoinStyle@2$NSBezelBorder@2$NSBezelStyleCircular@7$NSBezelStyleDisclosure@5$NSBezelStyleHelpButton@9$NSBezelStyleInline@15$NSBezelStyleRecessed@13$NSBezelStyleRegularSquare@2$NSBezelStyleRoundRect@12$NSBezelStyleRounded@1$NSBezelStyleRoundedDisclosure@14$NSBezelStyleShadowlessSquare@6$NSBezelStyleSmallSquare@10$NSBezelStyleTexturedRounded@11$NSBezelStyleTexturedSquare@8$NSBitmapFormatAlphaFirst@1$NSBitmapFormatAlphaNonpremultiplied@2$NSBitmapFormatFloatingPointSamples@4$NSBitmapFormatSixteenBitBigEndian@1024$NSBitmapFormatSixteenBitLittleEndian@256$NSBitmapFormatThirtyTwoBitBigEndian@2048$NSBitmapFormatThirtyTwoBitLittleEndian@512$NSBitmapImageFileTypeBMP@1$NSBitmapImageFileTypeGIF@2$NSBitmapImageFileTypeJPEG@3$NSBitmapImageFileTypeJPEG2000@5$NSBitmapImageFileTypePNG@4$NSBitmapImageFileTypeTIFF@0$NSBlueControlTint@1$NSBoldFontMask@2$NSBorderlessWindowMask@0$NSBottomTabsBezelBorder@2$NSBoxCustom@4$NSBoxOldStyle@3$NSBoxPrimary@0$NSBoxSecondary@1$NSBoxSeparator@2$NSBreakFunctionKey@63282$NSBrowserAutoColumnResizing@1$NSBrowserDropAbove@1$NSBrowserDropOn@0$NSBrowserNoColumnResizing@0$NSBrowserUserColumnResizing@2$NSButtLineCapStyle@0$NSButtonTypeAccelerator@8$NSButtonTypeMomentaryChange@5$NSButtonTypeMomentaryLight@0$NSButtonTypeMomentaryPushIn@7$NSButtonTypeMultiLevelAccelerator@9$NSButtonTypeOnOff@6$NSButtonTypePushOnPushOff@1$NSButtonTypeRadio@4$NSButtonTypeSwitch@3$NSButtonTypeToggle@2$NSCMYKColorSpaceModel@2$NSCMYKModeColorPanel@2$NSCancelButton@0$NSCancelTextMovement@23$NSCarriageReturnCharacter@13$NSCellAllowsMixedState@16$NSCellChangesContents@14$NSCellDisabled@0$NSCellEditable@3$NSCellHasImageHorizontal@12$NSCellHasImageOnLeftOrBottom@13$NSCellHasOverlappingImage@11$NSCellHighlighted@5$NSCellHitContentArea@1$NSCellHitEditableTextArea@2$NSCellHitNone@0$NSCellHitTrackableArea@4$NSCellIsBordered@10$NSCellIsInsetButton@15$NSCellLightsByBackground@9$NSCellLightsByContents@6$NSCellLightsByGray@7$NSCellState@1$NSCenterTabStopType@2$NSCenterTextAlignment@2$NSChangeAutosaved@4$NSChangeBackgroundCell@8$NSChangeBackgroundCellMask@8$NSChangeCleared@2$NSChangeDiscardable@256$NSChangeDone@0$NSChangeGrayCell@4$NSChangeGrayCellMask@4$NSChangeReadOtherContents@3$NSChangeRedone@5$NSChangeUndone@1$NSCircularBezelStyle@7$NSCircularSlider@1$NSClearControlTint@7$NSClearDisplayFunctionKey@63290$NSClearLineFunctionKey@63289$NSClipPagination@2$NSClockAndCalendarDatePickerStyle@1$NSClosableWindowMask@2$NSClosePathBezierPathElement@3$NSCloudKitSharingServiceAllowPrivate@2$NSCloudKitSharingServiceAllowPublic@1$NSCloudKitSharingServiceAllowReadOnly@16$NSCloudKitSharingServiceAllowReadWrite@32$NSCloudKitSharingServiceStandard@0$NSCollectionElementCategoryDecorationView@2$NSCollectionElementCategoryInterItemGap@3$NSCollectionElementCategoryItem@0$NSCollectionElementCategorySupplementaryView@1$NSCollectionUpdateActionDelete@1$NSCollectionUpdateActionInsert@0$NSCollectionUpdateActionMove@3$NSCollectionUpdateActionNone@4$NSCollectionUpdateActionReload@2$NSCollectionViewDropBefore@1$NSCollectionViewDropOn@0$NSCollectionViewItemHighlightAsDropTarget@3$NSCollectionViewItemHighlightForDeselection@2$NSCollectionViewItemHighlightForSelection@1$NSCollectionViewItemHighlightNone@0$NSCollectionViewScrollDirectionHorizontal@1$NSCollectionViewScrollDirectionVertical@0$NSCollectionViewScrollPositionBottom@4$NSCollectionViewScrollPositionCenteredHorizontally@16$NSCollectionViewScrollPositionCenteredVertically@2$NSCollectionViewScrollPositionLeadingEdge@64$NSCollectionViewScrollPositionLeft@8$NSCollectionViewScrollPositionNearestHorizontalEdge@512$NSCollectionViewScrollPositionNearestVerticalEdge@256$NSCollectionViewScrollPositionNone@0$NSCollectionViewScrollPositionRight@32$NSCollectionViewScrollPositionTop@1$NSCollectionViewScrollPositionTrailingEdge@128$NSColorListModeColorPanel@5$NSColorPanelAllModesMask@65535$NSColorPanelCMYKModeMask@4$NSColorPanelColorListModeMask@32$NSColorPanelCrayonModeMask@128$NSColorPanelCustomPaletteModeMask@16$NSColorPanelGrayModeMask@1$NSColorPanelHSBModeMask@8$NSColorPanelModeCMYK@2$NSColorPanelModeColorList@5$NSColorPanelModeCrayon@7$NSColorPanelModeCustomPalette@4$NSColorPanelModeGray@0$NSColorPanelModeHSB@3$NSColorPanelModeNone@-1$NSColorPanelModeRGB@1$NSColorPanelModeWheel@6$NSColorPanelRGBModeMask@2$NSColorPanelWheelModeMask@64$NSColorRenderingIntentAbsoluteColorimetric@1$NSColorRenderingIntentDefault@0$NSColorRenderingIntentPerceptual@3$NSColorRenderingIntentRelativeColorimetric@2$NSColorRenderingIntentSaturation@4$NSColorSpaceModelCMYK@2$NSColorSpaceModelDeviceN@4$NSColorSpaceModelGray@0$NSColorSpaceModelIndexed@5$NSColorSpaceModelLAB@3$NSColorSpaceModelPatterned@6$NSColorSpaceModelRGB@1$NSColorSpaceModelUnknown@-1$NSColorTypeCatalog@2$NSColorTypeComponentBased@0$NSColorTypePattern@1$NSCommandKeyMask@1048576$NSCompositeClear@0$NSCompositeColor@27$NSCompositeColorBurn@20$NSCompositeColorDodge@19$NSCompositeCopy@1$NSCompositeDarken@17$NSCompositeDestinationAtop@9$NSCompositeDestinationIn@7$NSCompositeDestinationOut@8$NSCompositeDestinationOver@6$NSCompositeDifference@23$NSCompositeExclusion@24$NSCompositeHardLight@22$NSCompositeHighlight@12$NSCompositeHue@25$NSCompositeLighten@18$NSCompositeLuminosity@28$NSCompositeMultiply@14$NSCompositeOverlay@16$NSCompositePlusDarker@11$NSCompositePlusLighter@13$NSCompositeSaturation@26$NSCompositeScreen@15$NSCompositeSoftLight@21$NSCompositeSourceAtop@5$NSCompositeSourceIn@3$NSCompositeSourceOut@4$NSCompositeSourceOver@2$NSCompositeXOR@10$NSCompositingOperationClear@0$NSCompositingOperationColor@27$NSCompositingOperationColorBurn@20$NSCompositingOperationColorDodge@19$NSCompositingOperationCopy@1$NSCompositingOperationDarken@17$NSCompositingOperationDestinationAtop@9$NSCompositingOperationDestinationIn@7$NSCompositingOperationDestinationOut@8$NSCompositingOperationDestinationOver@6$NSCompositingOperationDifference@23$NSCompositingOperationExclusion@24$NSCompositingOperationHardLight@22$NSCompositingOperationHighlight@12$NSCompositingOperationHue@25$NSCompositingOperationLighten@18$NSCompositingOperationLuminosity@28$NSCompositingOperationMultiply@14$NSCompositingOperationOverlay@16$NSCompositingOperationPlusDarker@11$NSCompositingOperationPlusLighter@13$NSCompositingOperationSaturation@26$NSCompositingOperationScreen@15$NSCompositingOperationSoftLight@21$NSCompositingOperationSourceAtop@5$NSCompositingOperationSourceIn@3$NSCompositingOperationSourceOut@4$NSCompositingOperationSourceOver@2$NSCompositingOperationXOR@10$NSCompressedFontMask@512$NSCondensedFontMask@64$NSContentsCellMask@1$NSContinuousCapacityLevelIndicatorStyle@1$NSControlCharacterActionContainerBreak@32$NSControlCharacterActionHorizontalTab@4$NSControlCharacterActionLineBreak@8$NSControlCharacterActionParagraphBreak@16$NSControlCharacterActionWhitespace@2$NSControlCharacterActionZeroAdvancement@1$NSControlGlyph@16777215$NSControlKeyMask@262144$NSControlSizeMini@2$NSControlSizeRegular@0$NSControlSizeSmall@1$NSControlStateMixed@-1$NSControlStateOff@0$NSControlStateOn@1$NSControlStateValueMixed@-1$NSControlStateValueOff@0$NSControlStateValueOn@1$NSCorrectionIndicatorTypeDefault@0$NSCorrectionIndicatorTypeGuesses@2$NSCorrectionIndicatorTypeReversion@1$NSCorrectionResponseAccepted@1$NSCorrectionResponseEdited@4$NSCorrectionResponseIgnored@3$NSCorrectionResponseNone@0$NSCorrectionResponseRejected@2$NSCorrectionResponseReverted@5$NSCrayonModeColorPanel@7$NSCriticalAlertStyle@2$NSCriticalRequest@0$NSCursorPointingDevice@2$NSCursorUpdate@17$NSCursorUpdateMask@131072$NSCurveToBezierPathElement@2$NSCustomPaletteModeColorPanel@4$NSDecimalTabStopType@3$NSDefaultControlTint@0$NSDefaultTokenStyle@0$NSDeleteCharFunctionKey@63294$NSDeleteCharacter@127$NSDeleteFunctionKey@63272$NSDeleteLineFunctionKey@63292$NSDescendingPageOrder@-1$NSDeviceIndependentModifierFlagsMask@4294901760$NSDeviceNColorSpaceModel@4$NSDirectSelection@0$NSDisclosureBezelStyle@5$NSDiscreteCapacityLevelIndicatorStyle@2$NSDisplayGamutP3@2$NSDisplayGamutSRGB@1$NSDisplayWindowRunLoopOrdering@600000$NSDocModalWindowMask@64$NSDockWindowLevel@20$NSDoubleType@6$NSDownArrowFunctionKey@63233$NSDownTextMovement@22$NSDragOperationAll@15$NSDragOperationAll_Obsolete@15$NSDragOperationCopy@1$NSDragOperationDelete@32$NSDragOperationGeneric@4$NSDragOperationLink@2$NSDragOperationMove@16$NSDragOperationNone@0$NSDragOperationPrivate@8$NSDraggingContextOutsideApplication@0$NSDraggingContextWithinApplication@1$NSDraggingFormationDefault@0$NSDraggingFormationList@3$NSDraggingFormationNone@1$NSDraggingFormationPile@2$NSDraggingFormationStack@4$NSDraggingItemEnumerationClearNonenumeratedImages@65536$NSDraggingItemEnumerationConcurrent@1$NSDrawerClosedState@0$NSDrawerClosingState@3$NSDrawerOpenState@2$NSDrawerOpeningState@1$NSEndFunctionKey@63275$NSEnterCharacter@3$NSEraDatePickerElementFlag@256$NSEraserPointingDevice@3$NSEvenOddWindingRule@1$NSEventButtonMaskPenLowerSide@2$NSEventButtonMaskPenTip@1$NSEventButtonMaskPenUpperSide@4$NSEventGestureAxisHorizontal@1$NSEventGestureAxisNone@0$NSEventGestureAxisVertical@2$NSEventMaskAppKitDefined@8192$NSEventMaskApplicationDefined@32768$NSEventMaskBeginGesture@524288$NSEventMaskCursorUpdate@131072$NSEventMaskDirectTouch@137438953472$NSEventMaskEndGesture@1048576$NSEventMaskFlagsChanged@4096$NSEventMaskGesture@536870912$NSEventMaskKeyDown@1024$NSEventMaskKeyUp@2048$NSEventMaskLeftMouseDown@2$NSEventMaskLeftMouseDragged@64$NSEventMaskLeftMouseUp@4$NSEventMaskMagnify@1073741824$NSEventMaskMouseEntered@256$NSEventMaskMouseExited@512$NSEventMaskMouseMoved@32$NSEventMaskOtherMouseDown@33554432$NSEventMaskOtherMouseDragged@134217728$NSEventMaskOtherMouseUp@67108864$NSEventMaskPeriodic@65536$NSEventMaskPressure@17179869184$NSEventMaskRightMouseDown@8$NSEventMaskRightMouseDragged@128$NSEventMaskRightMouseUp@16$NSEventMaskRotate@262144$NSEventMaskScrollWheel@4194304$NSEventMaskSmartMagnify@4294967296$NSEventMaskSwipe@2147483648$NSEventMaskSystemDefined@16384$NSEventMaskTabletPoint@8388608$NSEventMaskTabletProximity@16777216$NSEventModifierFlagCapsLock@65536$NSEventModifierFlagCommand@1048576$NSEventModifierFlagControl@262144$NSEventModifierFlagDeviceIndependentFlagsMask@4294901760$NSEventModifierFlagFunction@8388608$NSEventModifierFlagHelp@4194304$NSEventModifierFlagNumericPad@2097152$NSEventModifierFlagOption@524288$NSEventModifierFlagShift@131072$NSEventPhaseBegan@1$NSEventPhaseCancelled@16$NSEventPhaseChanged@4$NSEventPhaseEnded@8$NSEventPhaseMayBegin@32$NSEventPhaseNone@0$NSEventPhaseStationary@2$NSEventSubtypeApplicationActivated@1$NSEventSubtypeApplicationDeactivated@2$NSEventSubtypeMouseEvent@0$NSEventSubtypePowerOff@1$NSEventSubtypeScreenChanged@8$NSEventSubtypeTabletPoint@1$NSEventSubtypeTabletProximity@2$NSEventSubtypeTouch@3$NSEventSubtypeWindowExposed@0$NSEventSubtypeWindowMoved@4$NSEventSwipeTrackingClampGestureAmount@2$NSEventSwipeTrackingLockDirection@1$NSEventTypeAppKitDefined@13$NSEventTypeApplicationDefined@15$NSEventTypeBeginGesture@19$NSEventTypeCursorUpdate@17$NSEventTypeDirectTouch@37$NSEventTypeEndGesture@20$NSEventTypeFlagsChanged@12$NSEventTypeGesture@29$NSEventTypeKeyDown@10$NSEventTypeKeyUp@11$NSEventTypeLeftMouseDown@1$NSEventTypeLeftMouseDragged@6$NSEventTypeLeftMouseUp@2$NSEventTypeMagnify@30$NSEventTypeMouseEntered@8$NSEventTypeMouseExited@9$NSEventTypeMouseMoved@5$NSEventTypeOtherMouseDown@25$NSEventTypeOtherMouseDragged@27$NSEventTypeOtherMouseUp@26$NSEventTypePeriodic@16$NSEventTypePressure@34$NSEventTypeQuickLook@33$NSEventTypeRightMouseDown@3$NSEventTypeRightMouseDragged@7$NSEventTypeRightMouseUp@4$NSEventTypeRotate@18$NSEventTypeScrollWheel@22$NSEventTypeSmartMagnify@32$NSEventTypeSwipe@31$NSEventTypeSystemDefined@14$NSEventTypeTabletPoint@23$NSEventTypeTabletProximity@24$NSExclude10_4ElementsIconCreationOption@4$NSExcludeQuickDrawElementsIconCreationOption@2$NSExecuteFunctionKey@63298$NSExpandedFontMask@32$NSF10FunctionKey@63245$NSF11FunctionKey@63246$NSF12FunctionKey@63247$NSF13FunctionKey@63248$NSF14FunctionKey@63249$NSF15FunctionKey@63250$NSF16FunctionKey@63251$NSF17FunctionKey@63252$NSF18FunctionKey@63253$NSF19FunctionKey@63254$NSF1FunctionKey@63236$NSF20FunctionKey@63255$NSF21FunctionKey@63256$NSF22FunctionKey@63257$NSF23FunctionKey@63258$NSF24FunctionKey@63259$NSF25FunctionKey@63260$NSF26FunctionKey@63261$NSF27FunctionKey@63262$NSF28FunctionKey@63263$NSF29FunctionKey@63264$NSF2FunctionKey@63237$NSF30FunctionKey@63265$NSF31FunctionKey@63266$NSF32FunctionKey@63267$NSF33FunctionKey@63268$NSF34FunctionKey@63269$NSF35FunctionKey@63270$NSF3FunctionKey@63238$NSF4FunctionKey@63239$NSF5FunctionKey@63240$NSF6FunctionKey@63241$NSF7FunctionKey@63242$NSF8FunctionKey@63243$NSF9FunctionKey@63244$NSFPCurrentField@134$NSFPPreviewButton@131$NSFPPreviewField@128$NSFPRevertButton@130$NSFPSetButton@132$NSFPSizeField@129$NSFPSizeTitle@133$NSFileHandlingPanelCancelButton@0$NSFileHandlingPanelOKButton@1$NSFileWrapperReadingImmediate@1$NSFileWrapperReadingWithoutMapping@2$NSFileWrapperWritingAtomic@1$NSFileWrapperWritingWithNameUpdating@2$NSFindFunctionKey@63301$NSFindPanelActionNext@2$NSFindPanelActionPrevious@3$NSFindPanelActionReplace@5$NSFindPanelActionReplaceAll@4$NSFindPanelActionReplaceAllInSelection@8$NSFindPanelActionReplaceAndFind@6$NSFindPanelActionSelectAll@9$NSFindPanelActionSelectAllInSelection@10$NSFindPanelActionSetFindString@7$NSFindPanelActionShowFindPanel@1$NSFindPanelSubstringMatchTypeContains@0$NSFindPanelSubstringMatchTypeEndsWith@3$NSFindPanelSubstringMatchTypeFullWord@2$NSFindPanelSubstringMatchTypeStartsWith@1$NSFitPagination@1$NSFixedPitchFontMask@1024$NSFlagsChanged@12$NSFlagsChangedMask@4096$NSFloatType@3$NSFloatingPointSamplesBitmapFormat@4$NSFloatingWindowLevel@3$NSFocusRingAbove@2$NSFocusRingBelow@1$NSFocusRingOnly@0$NSFocusRingTypeDefault@0$NSFocusRingTypeExterior@2$NSFocusRingTypeNone@1$NSFontAntialiasedIntegerAdvancementsRenderingMode@3$NSFontAntialiasedRenderingMode@1$NSFontAssetDownloadError@66304$NSFontAssetRequestOptionUsesStandardUI@1$NSFontBoldTrait@2$NSFontClarendonSerifsClass@1073741824$NSFontCollectionApplicationOnlyMask@1$NSFontCollectionVisibilityComputer@4$NSFontCollectionVisibilityProcess@1$NSFontCollectionVisibilityUser@2$NSFontCondensedTrait@64$NSFontDefaultRenderingMode@0$NSFontDescriptorClassClarendonSerifs@1073741824$NSFontDescriptorClassFreeformSerifs@1879048192$NSFontDescriptorClassMask@4026531840$NSFontDescriptorClassModernSerifs@805306368$NSFontDescriptorClassOldStyleSerifs@268435456$NSFontDescriptorClassOrnamentals@2415919104$NSFontDescriptorClassSansSerif@2147483648$NSFontDescriptorClassScripts@2684354560$NSFontDescriptorClassSlabSerifs@1342177280$NSFontDescriptorClassSymbolic@3221225472$NSFontDescriptorClassTransitionalSerifs@536870912$NSFontDescriptorClassUnknown@0$NSFontDescriptorTraitBold@2$NSFontDescriptorTraitCondensed@64$NSFontDescriptorTraitExpanded@32$NSFontDescriptorTraitItalic@1$NSFontDescriptorTraitLooseLeading@65536$NSFontDescriptorTraitMonoSpace@1024$NSFontDescriptorTraitTightLeading@32768$NSFontDescriptorTraitUIOptimized@4096$NSFontDescriptorTraitVertical@2048$NSFontErrorMaximum@66335$NSFontErrorMinimum@66304$NSFontExpandedTrait@32$NSFontFamilyClassMask@4026531840$NSFontFreeformSerifsClass@1879048192$NSFontIntegerAdvancementsRenderingMode@2$NSFontItalicTrait@1$NSFontModernSerifsClass@805306368$NSFontMonoSpaceTrait@1024$NSFontOldStyleSerifsClass@268435456$NSFontOrnamentalsClass@2415919104$NSFontPanelAllEffectsModeMask@1048320$NSFontPanelAllModesMask@4294967295$NSFontPanelCollectionModeMask@4$NSFontPanelDocumentColorEffectModeMask@2048$NSFontPanelFaceModeMask@1$NSFontPanelModeMaskAllEffects@1048320$NSFontPanelModeMaskCollection@4$NSFontPanelModeMaskDocumentColorEffect@2048$NSFontPanelModeMaskFace@1$NSFontPanelModeMaskShadowEffect@4096$NSFontPanelModeMaskSize@2$NSFontPanelModeMaskStrikethroughEffect@512$NSFontPanelModeMaskTextColorEffect@1024$NSFontPanelModeMaskUnderlineEffect@256$NSFontPanelModesMaskAllModes@4294967295$NSFontPanelModesMaskStandardModes@65535$NSFontPanelShadowEffectModeMask@4096$NSFontPanelSizeModeMask@2$NSFontPanelStandardModesMask@65535$NSFontPanelStrikethroughEffectModeMask@512$NSFontPanelTextColorEffectModeMask@1024$NSFontPanelUnderlineEffectModeMask@256$NSFontSansSerifClass@2147483648$NSFontScriptsClass@2684354560$NSFontSlabSerifsClass@1342177280$NSFontSymbolicClass@3221225472$NSFontTransitionalSerifsClass@536870912$NSFontUIOptimizedTrait@4096$NSFontUnknownClass@0$NSFontVerticalTrait@2048$NSFormFeedCharacter@12$NSFourByteGlyphPacking@4$NSFullScreenWindowMask@16384$NSFullSizeContentViewWindowMask@32768$NSFunctionKeyMask@8388608$NSGIFFileType@2$NSGestureRecognizerStateBegan@1$NSGestureRecognizerStateCancelled@4$NSGestureRecognizerStateChanged@2$NSGestureRecognizerStateEnded@3$NSGestureRecognizerStateFailed@5$NSGestureRecognizerStatePossible@0$NSGestureRecognizerStateRecognized@3$NSGlyphAbove@2$NSGlyphAttributeBidiLevel@2$NSGlyphAttributeElastic@1$NSGlyphAttributeInscribe@5$NSGlyphAttributeSoft@0$NSGlyphBelow@1$NSGlyphInscribeAbove@2$NSGlyphInscribeBase@0$NSGlyphInscribeBelow@1$NSGlyphInscribeOverBelow@4$NSGlyphInscribeOverstrike@3$NSGlyphLayoutAgainstAPoint@1$NSGlyphLayoutAtAPoint@0$NSGlyphLayoutWithPrevious@2$NSGlyphPropertyControlCharacter@2$NSGlyphPropertyElastic@4$NSGlyphPropertyNonBaseCharacter@8$NSGlyphPropertyNull@1$NSGradientConcaveStrong@2$NSGradientConcaveWeak@1$NSGradientConvexStrong@4$NSGradientConvexWeak@3$NSGradientDrawsAfterEndingLocation@2$NSGradientDrawsBeforeStartingLocation@1$NSGradientNone@0$NSGraphiteControlTint@6$NSGrayColorSpaceModel@0$NSGrayModeColorPanel@0$NSGridCellPlacementBottom@3$NSGridCellPlacementCenter@4$NSGridCellPlacementFill@5$NSGridCellPlacementInherited@0$NSGridCellPlacementLeading@2$NSGridCellPlacementNone@1$NSGridCellPlacementTop@2$NSGridCellPlacementTrailing@3$NSGridRowAlignmentFirstBaseline@2$NSGridRowAlignmentInherited@0$NSGridRowAlignmentLastBaseline@3$NSGridRowAlignmentNone@1$NSGrooveBorder@3$NSHSBModeColorPanel@3$NSHUDWindowMask@8192$NSHapticFeedbackPatternAlignment@1$NSHapticFeedbackPatternGeneric@0$NSHapticFeedbackPatternLevelChange@2$NSHapticFeedbackPerformanceTimeDefault@0$NSHapticFeedbackPerformanceTimeDrawCompleted@2$NSHapticFeedbackPerformanceTimeNow@1$NSHeavierFontAction@5$NSHelpButtonBezelStyle@9$NSHelpFunctionKey@63302$NSHelpKeyMask@4194304$NSHighlightModeMatrix@1$NSHomeFunctionKey@63273$NSHorizontalRuler@0$NSHourMinuteDatePickerElementFlag@12$NSHourMinuteSecondDatePickerElementFlag@14$NSIdentityMappingCharacterCollection@0$NSIllegalTextMovement@0$NSImageAbove@5$NSImageAlignBottom@5$NSImageAlignBottomLeft@6$NSImageAlignBottomRight@7$NSImageAlignCenter@0$NSImageAlignLeft@4$NSImageAlignRight@8$NSImageAlignTop@1$NSImageAlignTopLeft@2$NSImageAlignTopRight@3$NSImageBelow@4$NSImageCacheAlways@1$NSImageCacheBySize@2$NSImageCacheDefault@0$NSImageCacheNever@3$NSImageCellType@2$NSImageFrameButton@4$NSImageFrameGrayBezel@2$NSImageFrameGroove@3$NSImageFrameNone@0$NSImageFramePhoto@1$NSImageInterpolationDefault@0$NSImageInterpolationHigh@3$NSImageInterpolationLow@2$NSImageInterpolationMedium@4$NSImageInterpolationNone@1$NSImageLayoutDirectionLeftToRight@2$NSImageLayoutDirectionRightToLeft@3$NSImageLayoutDirectionUnspecified@-1$NSImageLeading@7$NSImageLeft@2$NSImageLoadStatusCancelled@1$NSImageLoadStatusCompleted@0$NSImageLoadStatusInvalidData@2$NSImageLoadStatusReadError@4$NSImageLoadStatusUnexpectedEOF@3$NSImageOnly@1$NSImageOverlaps@6$NSImageRepLoadStatusCompleted@-6$NSImageRepLoadStatusInvalidData@-4$NSImageRepLoadStatusReadingHeader@-2$NSImageRepLoadStatusUnexpectedEOF@-5$NSImageRepLoadStatusUnknownType@-1$NSImageRepLoadStatusWillNeedAllData@-3$NSImageRepMatchesDevice@0$NSImageResizingModeStretch@0$NSImageResizingModeTile@1$NSImageRight@3$NSImageScaleAxesIndependently@1$NSImageScaleNone@2$NSImageScaleProportionallyDown@0$NSImageScaleProportionallyUpOrDown@3$NSImageTrailing@8$NSIndexedColorSpaceModel@5$NSInformationalAlertStyle@1$NSInformationalRequest@10$NSInlineBezelStyle@15$NSInsertCharFunctionKey@63293$NSInsertFunctionKey@63271$NSInsertLineFunctionKey@63291$NSIntType@1$NSItalicFontMask@1$NSJPEG2000FileType@5$NSJPEGFileType@3$NSJapaneseEUCGlyphPacking@1$NSJustifiedTextAlignment@3$NSKeyDown@10$NSKeyDownMask@1024$NSKeyUp@11$NSKeyUpMask@2048$NSLABColorSpaceModel@3$NSLandscapeOrientation@1$NSLayoutAttributeBaseline@11$NSLayoutAttributeBottom@4$NSLayoutAttributeCenterX@9$NSLayoutAttributeCenterY@10$NSLayoutAttributeFirstBaseline@12$NSLayoutAttributeHeight@8$NSLayoutAttributeLeading@5$NSLayoutAttributeLeft@1$NSLayoutAttributeNotAnAttribute@0$NSLayoutAttributeRight@2$NSLayoutAttributeTop@3$NSLayoutAttributeTrailing@6$NSLayoutAttributeWidth@7$NSLayoutCantFit@2$NSLayoutConstraintOrientationHorizontal@0$NSLayoutConstraintOrientationVertical@1$NSLayoutDone@1$NSLayoutFormatAlignAllBaseline@2048$NSLayoutFormatAlignAllBottom@16$NSLayoutFormatAlignAllCenterX@512$NSLayoutFormatAlignAllCenterY@1024$NSLayoutFormatAlignAllFirstBaseline@4096$NSLayoutFormatAlignAllLeading@32$NSLayoutFormatAlignAllLeft@2$NSLayoutFormatAlignAllRight@4$NSLayoutFormatAlignAllTop@8$NSLayoutFormatAlignAllTrailing@64$NSLayoutFormatAlignmentMask@65535$NSLayoutFormatDirectionLeadingToTrailing@0$NSLayoutFormatDirectionLeftToRight@65536$NSLayoutFormatDirectionMask@196608$NSLayoutFormatDirectionRightToLeft@131072$NSLayoutLeftToRight@0$NSLayoutNotDone@0$NSLayoutOutOfGlyphs@3$NSLayoutPriorityDefaultHigh@750$NSLayoutPriorityDefaultLow@250$NSLayoutPriorityDragThatCanResizeWindow@510$NSLayoutPriorityDragThatCannotResizeWindow@490$NSLayoutPriorityFittingSizeCompression@50$NSLayoutPriorityRequired@1000$NSLayoutPriorityWindowSizeStayPut@500$NSLayoutRelationEqual@0$NSLayoutRelationGreaterThanOrEqual@1$NSLayoutRelationLessThanOrEqual@-1$NSLayoutRightToLeft@1$NSLeftArrowFunctionKey@63234$NSLeftMouseDown@1$NSLeftMouseDownMask@2$NSLeftMouseDragged@6$NSLeftMouseDraggedMask@64$NSLeftMouseUp@2$NSLeftMouseUpMask@4$NSLeftTabStopType@0$NSLeftTabsBezelBorder@1$NSLeftTextAlignment@0$NSLeftTextMovement@19$NSLevelIndicatorPlaceholderVisibilityAlways@1$NSLevelIndicatorPlaceholderVisibilityAutomatic@0$NSLevelIndicatorPlaceholderVisibilityWhileEditing@2$NSLevelIndicatorStyleContinuousCapacity@1$NSLevelIndicatorStyleDiscreteCapacity@2$NSLevelIndicatorStyleRating@3$NSLevelIndicatorStyleRelevancy@0$NSLighterFontAction@6$NSLineBorder@1$NSLineBreakByCharWrapping@1$NSLineBreakByClipping@2$NSLineBreakByTruncatingHead@3$NSLineBreakByTruncatingMiddle@5$NSLineBreakByTruncatingTail@4$NSLineBreakByWordWrapping@0$NSLineDoesntMove@0$NSLineMovesDown@3$NSLineMovesLeft@1$NSLineMovesRight@2$NSLineMovesUp@4$NSLineSeparatorCharacter@8232$NSLineSweepDown@2$NSLineSweepLeft@0$NSLineSweepRight@1$NSLineSweepUp@3$NSLineToBezierPathElement@1$NSLinearSlider@0$NSListModeMatrix@2$NSMacintoshInterfaceStyle@3$NSMainMenuWindowLevel@24$NSMediaLibraryAudio@1$NSMediaLibraryImage@2$NSMediaLibraryMovie@4$NSMenuFunctionKey@63285$NSMenuPropertyItemAccessibilityDescription@32$NSMenuPropertyItemAttributedTitle@2$NSMenuPropertyItemEnabled@16$NSMenuPropertyItemImage@8$NSMenuPropertyItemKeyEquivalent@4$NSMenuPropertyItemTitle@1$NSMiniControlSize@2$NSMiniaturizableWindowMask@4$NSMiterLineJoinStyle@0$NSMixedState@-1$NSModalPanelWindowLevel@8$NSModalResponseAbort@-1001$NSModalResponseCancel@0$NSModalResponseContinue@-1002$NSModalResponseOK@1$NSModalResponseStop@-1000$NSModeSwitchFunctionKey@63303$NSMomentaryChangeButton@5$NSMomentaryLight@7$NSMomentaryLightButton@0$NSMomentaryPushButton@0$NSMomentaryPushInButton@7$NSMouseEntered@8$NSMouseEnteredMask@256$NSMouseEventSubtype@0$NSMouseExited@9$NSMouseExitedMask@512$NSMouseMoved@5$NSMouseMovedMask@32$NSMoveToBezierPathElement@0$NSMultiLevelAcceleratorButton@9$NSNarrowFontMask@16$NSNativeShortGlyphPacking@5$NSNaturalTextAlignment@4$NSNewlineCharacter@10$NSNextFunctionKey@63296$NSNextStepInterfaceStyle@1$NSNoBorder@0$NSNoCellMask@0$NSNoFontChangeAction@0$NSNoImage@0$NSNoInterfaceStyle@0$NSNoModeColorPanel@-1$NSNoScrollerParts@0$NSNoTabsBezelBorder@4$NSNoTabsLineBorder@5$NSNoTabsNoBorder@6$NSNoTitle@0$NSNoUnderlineStyle@0$NSNonStandardCharacterSetFontMask@8$NSNonZeroWindingRule@0$NSNonactivatingPanelMask@128$NSNormalWindowLevel@0$NSNullCellType@0$NSNullGlyph@0$NSNumericPadKeyMask@2097152$NSOKButton@1$NSOPENGL_CURRENT_VERSION@1$NSOffState@0$NSOnOffButton@6$NSOnState@1$NSOneByteGlyphPacking@0$NSOnlyScrollerArrows@1$NSOpenGLCPCurrentRendererID@309$NSOpenGLCPGPUFragmentProcessing@311$NSOpenGLCPGPUVertexProcessing@310$NSOpenGLCPHasDrawable@314$NSOpenGLCPMPSwapsInFlight@315$NSOpenGLCPRasterizationEnable@221$NSOpenGLCPReclaimResources@308$NSOpenGLCPStateValidation@301$NSOpenGLCPSurfaceBackingSize@304$NSOpenGLCPSurfaceOpacity@236$NSOpenGLCPSurfaceOrder@235$NSOpenGLCPSurfaceSurfaceVolatile@306$NSOpenGLCPSwapInterval@222$NSOpenGLCPSwapRectangle@200$NSOpenGLCPSwapRectangleEnable@201$NSOpenGLContextParameterCurrentRendererID@309$NSOpenGLContextParameterGPUFragmentProcessing@311$NSOpenGLContextParameterGPUVertexProcessing@310$NSOpenGLContextParameterHasDrawable@314$NSOpenGLContextParameterMPSwapsInFlight@315$NSOpenGLContextParameterRasterizationEnable@221$NSOpenGLContextParameterReclaimResources@308$NSOpenGLContextParameterStateValidation@301$NSOpenGLContextParameterSurfaceBackingSize@304$NSOpenGLContextParameterSurfaceOpacity@236$NSOpenGLContextParameterSurfaceOrder@235$NSOpenGLContextParameterSurfaceSurfaceVolatile@306$NSOpenGLContextParameterSwapInterval@222$NSOpenGLContextParameterSwapRectangle@200$NSOpenGLContextParameterSwapRectangleEnable@201$NSOpenGLGOClearFormatCache@502$NSOpenGLGOFormatCacheSize@501$NSOpenGLGOResetLibrary@504$NSOpenGLGORetainRenderers@503$NSOpenGLGOUseBuildCache@506$NSOpenGLPFAAccelerated@73$NSOpenGLPFAAcceleratedCompute@97$NSOpenGLPFAAccumSize@14$NSOpenGLPFAAllRenderers@1$NSOpenGLPFAAllowOfflineRenderers@96$NSOpenGLPFAAlphaSize@11$NSOpenGLPFAAuxBuffers@7$NSOpenGLPFAAuxDepthStencil@57$NSOpenGLPFABackingStore@76$NSOpenGLPFAClosestPolicy@74$NSOpenGLPFAColorFloat@58$NSOpenGLPFAColorSize@8$NSOpenGLPFACompliant@83$NSOpenGLPFADepthSize@12$NSOpenGLPFADoubleBuffer@5$NSOpenGLPFAFullScreen@54$NSOpenGLPFAMPSafe@78$NSOpenGLPFAMaximumPolicy@52$NSOpenGLPFAMinimumPolicy@51$NSOpenGLPFAMultiScreen@81$NSOpenGLPFAMultisample@59$NSOpenGLPFANoRecovery@72$NSOpenGLPFAOffScreen@53$NSOpenGLPFAOpenGLProfile@99$NSOpenGLPFAPixelBuffer@90$NSOpenGLPFARemotePixelBuffer@91$NSOpenGLPFARendererID@70$NSOpenGLPFARobust@75$NSOpenGLPFASampleAlpha@61$NSOpenGLPFASampleBuffers@55$NSOpenGLPFASamples@56$NSOpenGLPFAScreenMask@84$NSOpenGLPFASingleRenderer@71$NSOpenGLPFAStencilSize@13$NSOpenGLPFAStereo@6$NSOpenGLPFASupersample@60$NSOpenGLPFATripleBuffer@3$NSOpenGLPFAVirtualScreenCount@128$NSOpenGLPFAWindow@80$NSOpenGLProfileVersion3_2Core@12800$NSOpenGLProfileVersion4_1Core@16640$NSOpenGLProfileVersionLegacy@4096$NSOtherMouseDown@25$NSOtherMouseDownMask@33554432$NSOtherMouseDragged@27$NSOtherMouseDraggedMask@134217728$NSOtherMouseUp@26$NSOtherMouseUpMask@67108864$NSOtherTextMovement@0$NSOutlineViewDropOnItemIndex@-1$NSPDFPanelRequestsParentDirectory@16777216$NSPDFPanelShowsOrientation@8$NSPDFPanelShowsPaperSize@4$NSPNGFileType@4$NSPageControllerTransitionStyleHorizontalStrip@2$NSPageControllerTransitionStyleStackBook@1$NSPageControllerTransitionStyleStackHistory@0$NSPageDownFunctionKey@63277$NSPageUpFunctionKey@63276$NSPaperOrientationLandscape@1$NSPaperOrientationPortrait@0$NSParagraphSeparatorCharacter@8233$NSPasteboardContentsCurrentHostOnly@1$NSPasteboardReadingAsData@0$NSPasteboardReadingAsKeyedArchive@4$NSPasteboardReadingAsPropertyList@2$NSPasteboardReadingAsString@1$NSPasteboardWritingPromised@512$NSPathStyleNavigationBar@1$NSPathStylePopUp@2$NSPathStyleStandard@0$NSPatternColorSpaceModel@6$NSPauseFunctionKey@63280$NSPenLowerSideMask@2$NSPenPointingDevice@1$NSPenTipMask@1$NSPenUpperSideMask@4$NSPeriodic@16$NSPeriodicMask@65536$NSPlainTextTokenStyle@1$NSPointingDeviceTypeCursor@2$NSPointingDeviceTypeEraser@3$NSPointingDeviceTypePen@1$NSPointingDeviceTypeUnknown@0$NSPopUpArrowAtBottom@2$NSPopUpArrowAtCenter@1$NSPopUpMenuWindowLevel@101$NSPopUpNoArrow@0$NSPopoverAppearanceHUD@1$NSPopoverAppearanceMinimal@0$NSPopoverBehaviorApplicationDefined@0$NSPopoverBehaviorSemitransient@2$NSPopoverBehaviorTransient@1$NSPortraitOrientation@0$NSPositiveDoubleType@7$NSPositiveFloatType@4$NSPositiveIntType@2$NSPosterFontMask@256$NSPowerOffEventType@1$NSPressedTab@2$NSPressureBehaviorPrimaryAccelerator@3$NSPressureBehaviorPrimaryClick@1$NSPressureBehaviorPrimaryDeepClick@5$NSPressureBehaviorPrimaryDeepDrag@6$NSPressureBehaviorPrimaryDefault@0$NSPressureBehaviorPrimaryGeneric@2$NSPressureBehaviorUnknown@-1$NSPrevFunctionKey@63295$NSPrintFunctionKey@63288$NSPrintPanelShowsCopies@1$NSPrintPanelShowsOrientation@8$NSPrintPanelShowsPageRange@2$NSPrintPanelShowsPageSetupAccessory@256$NSPrintPanelShowsPaperSize@4$NSPrintPanelShowsPreview@131072$NSPrintPanelShowsPrintSelection@32$NSPrintPanelShowsScaling@16$NSPrintRenderingQualityBest@0$NSPrintRenderingQualityResponsive@1$NSPrintScreenFunctionKey@63278$NSPrinterTableError@2$NSPrinterTableNotFound@1$NSPrinterTableOK@0$NSPrintingCancelled@0$NSPrintingFailure@3$NSPrintingReplyLater@2$NSPrintingSuccess@1$NSProgressIndicatorBarStyle@0$NSProgressIndicatorPreferredAquaThickness@12$NSProgressIndicatorPreferredLargeThickness@18$NSProgressIndicatorPreferredSmallThickness@10$NSProgressIndicatorPreferredThickness@14$NSProgressIndicatorSpinningStyle@1$NSProgressIndicatorStyleBar@0$NSProgressIndicatorStyleSpinning@1$NSPushInCell@2$NSPushInCellMask@2$NSPushOnPushOffButton@1$NSQTMovieLoopingBackAndForthPlayback@2$NSQTMovieLoopingPlayback@1$NSQTMovieNormalPlayback@0$NSRGBColorSpaceModel@1$NSRGBModeColorPanel@1$NSRadioButton@4$NSRadioModeMatrix@0$NSRangeDateMode@1$NSRatingLevelIndicatorStyle@3$NSRecessedBezelStyle@13$NSRedoFunctionKey@63300$NSRegularControlSize@0$NSRegularSquareBezelStyle@2$NSRelevancyLevelIndicatorStyle@0$NSRemoteNotificationTypeAlert@4$NSRemoteNotificationTypeBadge@1$NSRemoteNotificationTypeNone@0$NSRemoteNotificationTypeSound@2$NSRemoveTraitFontAction@7$NSResetCursorRectsRunLoopOrdering@700000$NSResetFunctionKey@63283$NSResizableWindowMask@8$NSReturnTextMovement@16$NSRightArrowFunctionKey@63235$NSRightMouseDown@3$NSRightMouseDownMask@8$NSRightMouseDragged@7$NSRightMouseDraggedMask@128$NSRightMouseUp@4$NSRightMouseUpMask@16$NSRightTabStopType@1$NSRightTabsBezelBorder@3$NSRightTextAlignment@1$NSRightTextMovement@20$NSRoundLineCapStyle@1$NSRoundLineJoinStyle@1$NSRoundRectBezelStyle@12$NSRoundedBezelStyle@1$NSRoundedDisclosureBezelStyle@14$NSRoundedTokenStyle@2$NSRuleEditorNestingModeCompound@2$NSRuleEditorNestingModeList@1$NSRuleEditorNestingModeSimple@3$NSRuleEditorNestingModeSingle@0$NSRuleEditorRowTypeCompound@1$NSRuleEditorRowTypeSimple@0$NSRunAbortedResponse@-1001$NSRunContinuesResponse@-1002$NSRunStoppedResponse@-1000$NSSaveAsOperation@1$NSSaveOperation@0$NSSaveToOperation@2$NSScaleNone@2$NSScaleProportionally@0$NSScaleToFit@1$NSScreenChangedEventType@8$NSScreenSaverWindowLevel@1000$NSScrollElasticityAllowed@2$NSScrollElasticityAutomatic@0$NSScrollElasticityNone@1$NSScrollLockFunctionKey@63279$NSScrollViewFindBarPositionAboveContent@1$NSScrollViewFindBarPositionAboveHorizontalRuler@0$NSScrollViewFindBarPositionBelowContent@2$NSScrollWheel@22$NSScrollWheelMask@4194304$NSScrollerArrowsDefaultSetting@0$NSScrollerArrowsMaxEnd@0$NSScrollerArrowsMinEnd@1$NSScrollerArrowsNone@2$NSScrollerDecrementArrow@1$NSScrollerDecrementLine@4$NSScrollerDecrementPage@1$NSScrollerIncrementArrow@0$NSScrollerIncrementLine@5$NSScrollerIncrementPage@3$NSScrollerKnob@2$NSScrollerKnobSlot@6$NSScrollerKnobStyleDark@1$NSScrollerKnobStyleDefault@0$NSScrollerKnobStyleLight@2$NSScrollerNoPart@0$NSScrollerStyleLegacy@0$NSScrollerStyleOverlay@1$NSScrubberAlignmentCenter@3$NSScrubberAlignmentLeading@1$NSScrubberAlignmentNone@0$NSScrubberAlignmentTrailing@2$NSScrubberModeFixed@0$NSScrubberModeFree@1$NSSearchFieldClearRecentsMenuItemTag@1002$NSSearchFieldNoRecentsMenuItemTag@1003$NSSearchFieldRecentsMenuItemTag@1001$NSSearchFieldRecentsTitleMenuItemTag@1000$NSSegmentDistributionFill@1$NSSegmentDistributionFillEqually@2$NSSegmentDistributionFillProportionally@3$NSSegmentDistributionFit@0$NSSegmentStyleAutomatic@0$NSSegmentStyleCapsule@5$NSSegmentStyleRoundRect@3$NSSegmentStyleRounded@1$NSSegmentStyleSeparated@8$NSSegmentStyleSmallSquare@6$NSSegmentStyleTexturedRounded@2$NSSegmentStyleTexturedSquare@4$NSSegmentSwitchTrackingMomentary@2$NSSegmentSwitchTrackingMomentaryAccelerator@3$NSSegmentSwitchTrackingSelectAny@1$NSSegmentSwitchTrackingSelectOne@0$NSSelectByCharacter@0$NSSelectByParagraph@2$NSSelectByWord@1$NSSelectFunctionKey@63297$NSSelectedTab@0$NSSelectingNext@1$NSSelectingPrevious@2$NSSelectionAffinityDownstream@1$NSSelectionAffinityUpstream@0$NSServiceApplicationLaunchFailedError@66561$NSServiceApplicationNotFoundError@66560$NSServiceErrorMaximum@66817$NSServiceErrorMinimum@66560$NSServiceInvalidPasteboardDataError@66563$NSServiceMalformedServiceDictionaryError@66564$NSServiceMiscellaneousError@66800$NSServiceRequestTimedOutError@66562$NSShadowlessSquareBezelStyle@6$NSSharingContentScopeFull@2$NSSharingContentScopeItem@0$NSSharingContentScopePartial@1$NSSharingServiceErrorMaximum@67327$NSSharingServiceErrorMinimum@67072$NSSharingServiceNotConfiguredError@67072$NSShiftKeyMask@131072$NSShowControlGlyphs@1$NSShowInvisibleGlyphs@2$NSSingleDateMode@0$NSSingleUnderlineStyle@1$NSSizeDownFontAction@4$NSSizeUpFontAction@3$NSSliderTypeCircular@1$NSSliderTypeLinear@0$NSSmallCapsFontMask@128$NSSmallControlSize@1$NSSmallIconButtonBezelStyle@2$NSSmallSquareBezelStyle@10$NSSpecialPageOrder@0$NSSpeechImmediateBoundary@0$NSSpeechSentenceBoundary@2$NSSpeechWordBoundary@1$NSSpellingStateGrammarFlag@2$NSSpellingStateSpellingFlag@1$NSSplitViewDividerStylePaneSplitter@3$NSSplitViewDividerStyleThick@1$NSSplitViewDividerStyleThin@2$NSSplitViewItemBehaviorContentList@2$NSSplitViewItemBehaviorDefault@0$NSSplitViewItemBehaviorSidebar@1$NSSplitViewItemCollapseBehaviorDefault@0$NSSplitViewItemCollapseBehaviorPreferResizingSiblingsWithFixedSplitView@2$NSSplitViewItemCollapseBehaviorPreferResizingSplitViewWithFixedSiblings@1$NSSplitViewItemCollapseBehaviorUseConstraints@3$NSSpringLoadingContinuousActivation@2$NSSpringLoadingDisabled@0$NSSpringLoadingEnabled@1$NSSpringLoadingHighlightEmphasized@2$NSSpringLoadingHighlightNone@0$NSSpringLoadingHighlightStandard@1$NSSpringLoadingNoHover@4$NSSquareLineCapStyle@2$NSSquareStatusItemLength@-2$NSStackViewDistributionEqualCentering@4$NSStackViewDistributionEqualSpacing@3$NSStackViewDistributionFill@0$NSStackViewDistributionFillEqually@1$NSStackViewDistributionFillProportionally@2$NSStackViewDistributionGravityAreas@-1$NSStackViewGravityBottom@3$NSStackViewGravityCenter@2$NSStackViewGravityLeading@1$NSStackViewGravityTop@1$NSStackViewGravityTrailing@3$NSStackViewVisibilityPriorityDetachOnlyIfNecessary@900$NSStackViewVisibilityPriorityMustHold@1000$NSStackViewVisibilityPriorityNotVisible@0$NSStatusItemBehaviorRemovalAllowed@2$NSStatusItemBehaviorTerminationOnRemoval@4$NSStatusWindowLevel@25$NSStopFunctionKey@63284$NSStringDrawingDisableScreenFontSubstitution@4$NSStringDrawingOneShot@16$NSStringDrawingTruncatesLastVisibleLine@32$NSStringDrawingUsesDeviceMetrics@8$NSStringDrawingUsesFontLeading@2$NSStringDrawingUsesLineFragmentOrigin@1$NSSubmenuWindowLevel@3$NSSwitchButton@3$NSSysReqFunctionKey@63281$NSSystemDefined@14$NSSystemDefinedMask@16384$NSSystemFunctionKey@63287$NSTIFFCompressionCCITTFAX3@3$NSTIFFCompressionCCITTFAX4@4$NSTIFFCompressionJPEG@6$NSTIFFCompressionLZW@5$NSTIFFCompressionNEXT@32766$NSTIFFCompressionNone@1$NSTIFFCompressionOldJPEG@32865$NSTIFFCompressionPackBits@32773$NSTIFFFileType@0$NSTabCharacter@9$NSTabPositionBottom@3$NSTabPositionLeft@2$NSTabPositionNone@0$NSTabPositionRight@4$NSTabPositionTop@1$NSTabTextMovement@17$NSTabViewBorderTypeBezel@2$NSTabViewBorderTypeLine@1$NSTabViewBorderTypeNone@0$NSTabViewControllerTabStyleSegmentedControlOnBottom@1$NSTabViewControllerTabStyleSegmentedControlOnTop@0$NSTabViewControllerTabStyleToolbar@2$NSTabViewControllerTabStyleUnspecified@-1$NSTableColumnAutoresizingMask@1$NSTableColumnNoResizing@0$NSTableColumnUserResizingMask@2$NSTableRowActionEdgeLeading@0$NSTableRowActionEdgeTrailing@1$NSTableViewAnimationEffectFade@1$NSTableViewAnimationEffectGap@2$NSTableViewAnimationEffectNone@0$NSTableViewAnimationSlideDown@32$NSTableViewAnimationSlideLeft@48$NSTableViewAnimationSlideRight@64$NSTableViewAnimationSlideUp@16$NSTableViewDashedHorizontalGridLineMask@8$NSTableViewDraggingDestinationFeedbackStyleGap@2$NSTableViewDraggingDestinationFeedbackStyleNone@-1$NSTableViewDraggingDestinationFeedbackStyleRegular@0$NSTableViewDraggingDestinationFeedbackStyleSourceList@1$NSTableViewDropAbove@1$NSTableViewDropOn@0$NSTableViewFirstColumnOnlyAutoresizingStyle@5$NSTableViewGridNone@0$NSTableViewLastColumnOnlyAutoresizingStyle@4$NSTableViewNoColumnAutoresizing@0$NSTableViewReverseSequentialColumnAutoresizingStyle@3$NSTableViewRowActionStyleDestructive@1$NSTableViewRowActionStyleRegular@0$NSTableViewRowSizeStyleCustom@0$NSTableViewRowSizeStyleDefault@-1$NSTableViewRowSizeStyleLarge@3$NSTableViewRowSizeStyleMedium@2$NSTableViewRowSizeStyleSmall@1$NSTableViewSelectionHighlightStyleNone@-1$NSTableViewSelectionHighlightStyleRegular@0$NSTableViewSelectionHighlightStyleSourceList@1$NSTableViewSequentialColumnAutoresizingStyle@2$NSTableViewSolidHorizontalGridLineMask@2$NSTableViewSolidVerticalGridLineMask@1$NSTableViewUniformColumnAutoresizingStyle@1$NSTabletPoint@23$NSTabletPointEventSubtype@1$NSTabletPointMask@8388608$NSTabletProximity@24$NSTabletProximityEventSubtype@2$NSTabletProximityMask@16777216$NSTerminateCancel@0$NSTerminateLater@2$NSTerminateNow@1$NSTextAlignmentCenter@2$NSTextAlignmentJustified@3$NSTextAlignmentLeft@0$NSTextAlignmentNatural@4$NSTextAlignmentRight@1$NSTextBlockAbsoluteValueType@0$NSTextBlockBaselineAlignment@3$NSTextBlockBorder@0$NSTextBlockBottomAlignment@2$NSTextBlockHeight@4$NSTextBlockMargin@1$NSTextBlockMaximumHeight@6$NSTextBlockMaximumWidth@2$NSTextBlockMiddleAlignment@1$NSTextBlockMinimumHeight@5$NSTextBlockMinimumWidth@1$NSTextBlockPadding@-1$NSTextBlockPercentageValueType@1$NSTextBlockTopAlignment@0$NSTextBlockWidth@0$NSTextCellType@1$NSTextFieldAndStepperDatePickerStyle@0$NSTextFieldDatePickerStyle@2$NSTextFieldRoundedBezel@1$NSTextFieldSquareBezel@0$NSTextFinderActionHideFindInterface@11$NSTextFinderActionHideReplaceInterface@13$NSTextFinderActionNextMatch@2$NSTextFinderActionPreviousMatch@3$NSTextFinderActionReplace@5$NSTextFinderActionReplaceAll@4$NSTextFinderActionReplaceAllInSelection@8$NSTextFinderActionReplaceAndFind@6$NSTextFinderActionSelectAll@9$NSTextFinderActionSelectAllInSelection@10$NSTextFinderActionSetSearchString@7$NSTextFinderActionShowFindInterface@1$NSTextFinderActionShowReplaceInterface@12$NSTextFinderMatchingTypeContains@0$NSTextFinderMatchingTypeEndsWith@3$NSTextFinderMatchingTypeFullWord@2$NSTextFinderMatchingTypeStartsWith@1$NSTextLayoutOrientationHorizontal@0$NSTextLayoutOrientationVertical@1$NSTextListPrependEnclosingMarker@1$NSTextMovementBacktab@18$NSTextMovementCancel@23$NSTextMovementDown@22$NSTextMovementLeft@19$NSTextMovementOther@0$NSTextMovementReturn@16$NSTextMovementRight@20$NSTextMovementTab@17$NSTextMovementUp@21$NSTextReadInapplicableDocumentTypeError@65806$NSTextReadWriteErrorMaximum@66303$NSTextReadWriteErrorMinimum@65792$NSTextStorageEditedAttributes@1$NSTextStorageEditedCharacters@2$NSTextTableAutomaticLayoutAlgorithm@0$NSTextTableFixedLayoutAlgorithm@1$NSTextWriteInapplicableDocumentTypeError@66062$NSTextWritingDirectionEmbedding@0$NSTextWritingDirectionOverride@2$NSTexturedBackgroundWindowMask@256$NSTexturedRoundedBezelStyle@11$NSTexturedSquareBezelStyle@8$NSThickSquareBezelStyle@3$NSThickerSquareBezelStyle@4$NSTickMarkAbove@1$NSTickMarkBelow@0$NSTickMarkLeft@1$NSTickMarkPositionAbove@1$NSTickMarkPositionBelow@0$NSTickMarkPositionLeading@1$NSTickMarkPositionTrailing@0$NSTickMarkRight@0$NSTimeZoneDatePickerElementFlag@16$NSTitledWindowMask@1$NSToggleButton@2$NSTokenStyleDefault@0$NSTokenStyleNone@1$NSTokenStylePlainSquared@4$NSTokenStyleRounded@2$NSTokenStyleSquared@3$NSToolbarDisplayModeDefault@0$NSToolbarDisplayModeIconAndLabel@1$NSToolbarDisplayModeIconOnly@2$NSToolbarDisplayModeLabelOnly@3$NSToolbarItemVisibilityPriorityHigh@1000$NSToolbarItemVisibilityPriorityLow@-1000$NSToolbarItemVisibilityPriorityStandard@0$NSToolbarItemVisibilityPriorityUser@2000$NSToolbarSizeModeDefault@0$NSToolbarSizeModeRegular@1$NSToolbarSizeModeSmall@2$NSTopTabsBezelBorder@0$NSTornOffMenuWindowLevel@3$NSTouchBarItemPriorityHigh@1000.0$NSTouchBarItemPriorityLow@-1000.0$NSTouchBarItemPriorityNormal@0.0$NSTouchEventSubtype@3$NSTouchPhaseBegan@1$NSTouchPhaseCancelled@16$NSTouchPhaseEnded@8$NSTouchPhaseMoved@2$NSTouchPhaseStationary@4$NSTouchPhaseTouching@7$NSTouchTypeDirect@0$NSTouchTypeIndirect@1$NSTouchTypeMaskDirect@1$NSTouchTypeMaskIndirect@2$NSTrackModeMatrix@3$NSTrackingActiveAlways@128$NSTrackingActiveInActiveApp@64$NSTrackingActiveInKeyWindow@32$NSTrackingActiveWhenFirstResponder@16$NSTrackingAssumeInside@256$NSTrackingCursorUpdate@4$NSTrackingEnabledDuringMouseDrag@1024$NSTrackingInVisibleRect@512$NSTrackingMouseEnteredAndExited@1$NSTrackingMouseMoved@2$NSTwoByteGlyphPacking@3$NSTypesetterBehavior_10_2@2$NSTypesetterBehavior_10_2_WithCompatibility@1$NSTypesetterBehavior_10_3@3$NSTypesetterBehavior_10_4@4$NSTypesetterContainerBreakAction@32$NSTypesetterHorizontalTabAction@4$NSTypesetterLatestBehavior@-1$NSTypesetterLineBreakAction@8$NSTypesetterOriginalBehavior@0$NSTypesetterParagraphBreakAction@16$NSTypesetterWhitespaceAction@2$NSTypesetterZeroAdvancementAction@1$NSUnboldFontMask@4$NSUnderlinePatternDash@512$NSUnderlinePatternDashDot@768$NSUnderlinePatternDashDotDot@1024$NSUnderlinePatternDot@256$NSUnderlinePatternSolid@0$NSUnderlineStyleDouble@9$NSUnderlineStyleNone@0$NSUnderlineStyleSingle@1$NSUnderlineStyleThick@2$NSUndoFunctionKey@63299$NSUnifiedTitleAndToolbarWindowMask@4096$NSUnitalicFontMask@16777216$NSUnknownColorSpaceModel@-1$NSUnknownPageOrder@2$NSUnknownPointingDevice@0$NSUnscaledWindowMask@2048$NSUpArrowFunctionKey@63232$NSUpTextMovement@21$NSUpdateWindowsRunLoopOrdering@500000$NSUserFunctionKey@63286$NSUserInterfaceLayoutDirectionLeftToRight@0$NSUserInterfaceLayoutDirectionRightToLeft@1$NSUserInterfaceLayoutOrientationHorizontal@0$NSUserInterfaceLayoutOrientationVertical@1$NSUtilityWindowMask@16$NSVariableStatusItemLength@-1$NSVerticalRuler@1$NSViaPanelFontAction@1$NSViewControllerTransitionAllowUserInteraction@4096$NSViewControllerTransitionCrossfade@1$NSViewControllerTransitionNone@0$NSViewControllerTransitionSlideBackward@384$NSViewControllerTransitionSlideDown@32$NSViewControllerTransitionSlideForward@320$NSViewControllerTransitionSlideLeft@64$NSViewControllerTransitionSlideRight@128$NSViewControllerTransitionSlideUp@16$NSViewHeightSizable@16$NSViewLayerContentsPlacementBottom@8$NSViewLayerContentsPlacementBottomLeft@9$NSViewLayerContentsPlacementBottomRight@7$NSViewLayerContentsPlacementCenter@3$NSViewLayerContentsPlacementLeft@10$NSViewLayerContentsPlacementRight@6$NSViewLayerContentsPlacementScaleAxesIndependently@0$NSViewLayerContentsPlacementScaleProportionallyToFill@2$NSViewLayerContentsPlacementScaleProportionallyToFit@1$NSViewLayerContentsPlacementTop@4$NSViewLayerContentsPlacementTopLeft@11$NSViewLayerContentsPlacementTopRight@5$NSViewLayerContentsRedrawBeforeViewResize@3$NSViewLayerContentsRedrawCrossfade@4$NSViewLayerContentsRedrawDuringViewResize@2$NSViewLayerContentsRedrawNever@0$NSViewLayerContentsRedrawOnSetNeedsDisplay@1$NSViewMaxXMargin@4$NSViewMaxYMargin@32$NSViewMinXMargin@1$NSViewMinYMargin@8$NSViewNotSizable@0$NSViewWidthSizable@2$NSVisualEffectBlendingModeBehindWindow@0$NSVisualEffectBlendingModeWithinWindow@1$NSVisualEffectMaterialAppearanceBased@0$NSVisualEffectMaterialDark@2$NSVisualEffectMaterialLight@1$NSVisualEffectMaterialMediumLight@8$NSVisualEffectMaterialMenu@5$NSVisualEffectMaterialPopover@6$NSVisualEffectMaterialSelection@4$NSVisualEffectMaterialSidebar@7$NSVisualEffectMaterialTitlebar@3$NSVisualEffectMaterialUltraDark@9$NSVisualEffectStateActive@1$NSVisualEffectStateFollowsWindowActiveState@0$NSVisualEffectStateInactive@2$NSWantsBidiLevels@4$NSWarningAlertStyle@0$NSWheelModeColorPanel@6$NSWindowAbove@1$NSWindowAnimationBehaviorAlertPanel@5$NSWindowAnimationBehaviorDefault@0$NSWindowAnimationBehaviorDocumentWindow@3$NSWindowAnimationBehaviorNone@2$NSWindowAnimationBehaviorUtilityWindow@4$NSWindowBackingLocationDefault@0$NSWindowBackingLocationMainMemory@2$NSWindowBackingLocationVideoMemory@1$NSWindowBelow@-1$NSWindowCloseButton@0$NSWindowCollectionBehaviorCanJoinAllSpaces@1$NSWindowCollectionBehaviorDefault@0$NSWindowCollectionBehaviorFullScreenAllowsTiling@2048$NSWindowCollectionBehaviorFullScreenAuxiliary@256$NSWindowCollectionBehaviorFullScreenDisallowsTiling@4096$NSWindowCollectionBehaviorFullScreenNone@512$NSWindowCollectionBehaviorFullScreenPrimary@128$NSWindowCollectionBehaviorIgnoresCycle@64$NSWindowCollectionBehaviorManaged@4$NSWindowCollectionBehaviorMoveToActiveSpace@2$NSWindowCollectionBehaviorParticipatesInCycle@32$NSWindowCollectionBehaviorStationary@16$NSWindowCollectionBehaviorTransient@8$NSWindowDepthOnehundredtwentyeightBitRGB@544$NSWindowDepthSixtyfourBitRGB@528$NSWindowDepthTwentyfourBitRGB@520$NSWindowDocumentIconButton@4$NSWindowDocumentVersionsButton@6$NSWindowExposedEventType@0$NSWindowFullScreenButton@7$NSWindowListOrderedFrontToBack@1$NSWindowMiniaturizeButton@1$NSWindowMovedEventType@4$NSWindowNumberListAllApplications@1$NSWindowNumberListAllSpaces@16$NSWindowOcclusionStateVisible@2$NSWindowOut@0$NSWindowSharingNone@0$NSWindowSharingReadOnly@1$NSWindowSharingReadWrite@2$NSWindowStyleMaskBorderless@0$NSWindowStyleMaskClosable@2$NSWindowStyleMaskDocModalWindow@64$NSWindowStyleMaskFullScreen@16384$NSWindowStyleMaskFullSizeContentView@32768$NSWindowStyleMaskHUDWindow@8192$NSWindowStyleMaskMiniaturizable@4$NSWindowStyleMaskNonactivatingPanel@128$NSWindowStyleMaskResizable@8$NSWindowStyleMaskTexturedBackground@256$NSWindowStyleMaskTitled@1$NSWindowStyleMaskUnifiedTitleAndToolbar@4096$NSWindowStyleMaskUtilityWindow@16$NSWindowTabbingModeAutomatic@0$NSWindowTabbingModeDisallowed@2$NSWindowTabbingModePreferred@1$NSWindowTitleHidden@1$NSWindowTitleVisible@0$NSWindowToolbarButton@3$NSWindowUserTabbingPreferenceAlways@1$NSWindowUserTabbingPreferenceInFullScreen@2$NSWindowUserTabbingPreferenceManual@0$NSWindowZoomButton@2$NSWindows95InterfaceStyle@2$NSWorkspaceLaunchAllowingClassicStartup@131072$NSWorkspaceLaunchAndHide@1048576$NSWorkspaceLaunchAndHideOthers@2097152$NSWorkspaceLaunchAndPrint@2$NSWorkspaceLaunchAsync@65536$NSWorkspaceLaunchDefault@65536$NSWorkspaceLaunchInhibitingBackgroundOnly@128$NSWorkspaceLaunchNewInstance@524288$NSWorkspaceLaunchPreferringClassic@262144$NSWorkspaceLaunchWithErrorPresentation@64$NSWorkspaceLaunchWithoutActivation@512$NSWorkspaceLaunchWithoutAddingToRecents@256$NSWritingDirectionEmbedding@0$NSWritingDirectionLeftToRight@0$NSWritingDirectionNatural@-1$NSWritingDirectionOverride@2$NSWritingDirectionRightToLeft@1$NSYearMonthDatePickerElementFlag@192$NSYearMonthDayDatePickerElementFlag@224$NumGlyphsToGetEachTime@20$'''
misc.update({'NSAnyEventMask': sel32or64(4294967295, 18446744073709551615), 'NSTouchPhaseAny': sel32or64(4294967295, 18446744073709551615), 'NS_USER_ACTIVITY_SUPPORTED': sel32or64(0, 1), 'NSAttachmentCharacter': b'\xef\xbf\xbc'.decode("utf-8"), 'NSDragOperationEvery': sel32or64(4294967295, 18446744073709551615)})
misc.update({'NSAppKitVersionNumber10_4_1': 824.1, 'NSAppKitVersionNumber10_4_3': 824.23, 'NSAppKitVersionNumber10_3_9': 743.36, 'NSAppKitVersionNumber10_4_4': 824.33, 'NSAppKitVersionNumber10_4_7': 824.41, 'NSAppKitVersionNumber10_3_2': 743.14, 'NSAppKitVersionNumber10_3_3': 743.2, 'NSAppKitVersionNumber10_3_7': 743.33, 'NSAppKitVersionNumber10_3_5': 743.24, 'NSAppKitVersionNumberWithDockTilePlugInSupport': 1001.0, 'NSAppKitVersionNumberWithCursorSizeSupport': 682.0, 'NSAppKitVersionNumber10_5_2': 949.27, 'NSAppKitVersionNumber10_5_3': 949.33, 'NSAppKitVersionNumberWithCustomSheetPosition': 686.0, 'NSAppKitVersionNumber10_2_3': 663.6, 'NSAppKitVersionNumberWithDirectionalTabs': 631.0, 'NSAppKitVersionNumberWithColumnResizingBrowser': 685.0, 'NSAppKitVersionNumberWithDeferredWindowDisplaySupport': 1019.0, 'NSAppKitVersionNumberWithContinuousScrollingBrowser': 680.0, 'NSAppKitVersionNumberWithPatternColorLeakFix': 641.0, 'NSAppKitVersionNumber10_7_4': 1138.47, 'NSAppKitVersionNumber10_7_2': 1138.23, 'NSAppKitVersionNumber10_7_3': 1138.32, 'NSBaselineNotSet': -1.0})
functions={'NSRectClipList': (sel32or64(b'v^{_NSRect={_NSPoint=ff}{_NSSize=ff}}i', b'v^{CGRect={CGPoint=dd}{CGSize=dd}}q'), '', {'arguments': {0: {'c_array_length_in_arg': 1, 'type_modifier': 'n'}}}), 'NSApplicationLoad': (b'Z',), 'NSCountWindows': (sel32or64(b'v^i', b'v^q'), '', {'arguments': {0: {'type_modifier': 'o'}}}), 'NSGetAlertPanel': (b'@@@@@@', '', {'arguments': {1: {'printf_format': True}}, 'variadic': True}), 'NSApplicationMain': (b'ii^^c',), 'NSOpenGLGetVersion': (b'v^i^i', '', {'arguments': {0: {'type_modifier': 'o'}, 1: {'type_modifier': 'o'}}}), 'NSAccessibilityActionDescription': (b'@@',), 'NSRunAlertPanelRelativeToWindow': (sel32or64(b'i@@@@@@', b'q@@@@@@'), '', {'arguments': {1: {'printf_format': 1}}, 'variadic': True}), 'NSTouchTypeMaskFromType': (sel32or64(b'II', b'QQ'), '', {'inline': True}), 'NSDrawLightBezel': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSDrawNinePartImage': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}@@@@@@@@@IfZ', b'v{CGRect={CGPoint=dd}{CGSize=dd}}@@@@@@@@@QdZ'),), 'NSOpenGLSetOption': (b'vIi',), 'NSRectClip': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSDottedFrameRect': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSDrawBitmap': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}iiiiiiZZ@[5^C]', b'v{CGRect={CGPoint=dd}{CGSize=dd}}qqqqqqZZ@[5^C]'),), 'NSConvertGlyphsToPackedGlyphs': (sel32or64(b'i^IiI^c', b'q^IqQ^c'),), 'NSGetFileType': (b'@@',), 'NSWindowList': (sel32or64(b'vi^i', b'vq^q'), '', {'arguments': {1: {'c_array_length_in_arg': 0, 'type_modifier': 'o'}}}), 'NSAccessibilityRaiseBadArgumentException': (b'v@@@',), 'NSAccessibilityUnignoredDescendant': (b'@@',), 'NSRectFill': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSGetCriticalAlertPanel': (b'@@@@@@', '', {'arguments': {1: {'printf_format': True}}, 'variadic': True}), 'NSAccessibilityFrameInView': (sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}@{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}@{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSDrawThreePartImage': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}@@@ZIfZ', b'v{CGRect={CGPoint=dd}{CGSize=dd}}@@@ZQdZ'),), 'NSAccessibilityRoleDescription': (b'@@@',), 'NSRunCriticalAlertPanel': (sel32or64(b'i@@@@@', b'q@@@@@'), '', {'arguments': {1: {'printf_format': 1}}, 'variadic': True}), 'NSFrameRect': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSDrawColorTiledRects': (sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}^I^@i', b'{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}^Q^@q'), '', {'arguments': {2: {'c_array_length_in_arg': 4, 'type_modifier': 'n'}, 3: {'c_array_length_in_arg': 4, 'type_modifier': 'n'}}}), 'NSBeginCriticalAlertSheet': (b'v@@@@@@::^v@', '', {'arguments': {9: {'printf_format': True}, 6: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 7: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}}, 'variadic': True}), 'NSBeginAlertSheet': (b'v@@@@@@::^v@', '', {'arguments': {9: {'printf_format': True}, 6: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 7: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}}, 'variadic': True}), 'NSCountWindowsForContext': (sel32or64(b'vi^i', b'vq^q'), '', {'arguments': {1: {'type_modifier': 'o'}}}), 'NSGetWindowServerMemory': (sel32or64(b'ii^i^i^@', b'qq^q^q^@'), '', {'arguments': {1: {'type_modifier': 'o'}, 2: {'type_modifier': 'o'}, 3: {'type_modifier': 'o'}}}), 'NSShowAnimationEffect': (sel32or64(b'vI{_NSPoint=ff}{_NSSize=ff}@:^v', b'vQ{CGPoint=dd}{CGSize=dd}@:^v'), '', {'arguments': {4: {'sel_of_type': b'v@:^v'}}}), 'NSRunCriticalAlertPanelRelativeToWindow': (sel32or64(b'i@@@@@@', b'q@@@@@@'), '', {'arguments': {1: {'printf_format': 1}}, 'variadic': True}), 'NSAccessibilityUnignoredChildren': (b'@@',), 'NSRectFillListUsingOperation': (sel32or64(b'v^{_NSRect={_NSPoint=ff}{_NSSize=ff}}iI', b'v^{CGRect={CGPoint=dd}{CGSize=dd}}qQ'), '', {'arguments': {0: {'c_array_length_in_arg': 1, 'type_modifier': 'n'}}}), 'NSCreateFilenamePboardType': (b'@@', '', {'retval': {'already_cfretained': True}}), 'NSInterfaceStyleForKey': (sel32or64(b'I@@', b'Q@@'),), 'NSAvailableWindowDepths': (b'^i', '', {'retval': {'c_array_delimited_by_null': True}}), 'NSBeginInformationalAlertSheet': (b'v@@@@@@::^v@', '', {'arguments': {9: {'printf_format': True}, 6: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 7: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}}, 'variadic': True}), 'NSUnregisterServicesProvider': (b'v@',), 'NSEventMaskFromType': (sel32or64(b'II', b'QQ'),), 'NSRectFillUsingOperation': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}I', b'v{CGRect={CGPoint=dd}{CGSize=dd}}Q'),), 'NSBitsPerSampleFromDepth': (sel32or64(b'ii', b'qi'),), 'NSEnableScreenUpdates': (b'v',), 'NSDrawDarkBezel': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSRunInformationalAlertPanelRelativeToWindow': (sel32or64(b'i@@@@@@', b'q@@@@@@'), '', {'arguments': {1: {'printf_format': 1}}, 'variadic': True}), 'NSPerformService': (b'Z@@',), 'NSGetFileTypes': (b'@@',), 'NSDrawWhiteBezel': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSReleaseAlertPanel': (b'v@',), 'NSAccessibilityUnignoredAncestor': (b'@@',), 'NSAccessibilityPostNotificationWithUserInfo': (b'v@@@',), 'NSSetFocusRingStyle': (sel32or64(b'vI', b'vQ'),), 'NSAccessibilityPostNotification': (b'v@@',), 'NSDrawTiledRects': (sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}^I^fi', b'{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}^Q^dq'), '', {'arguments': {2: {'c_array_length_in_arg': 4, 'type_modifier': 'n'}, 3: {'c_array_length_in_arg': 4, 'type_modifier': 'n'}}}), 'NSAccessibilityPointInView': (sel32or64(b'{_NSPoint=ff}@{_NSPoint=ff}', b'{CGPoint=dd}@{CGPoint=dd}'),), 'NSUpdateDynamicServices': (b'v',), 'NSIsControllerMarker': (b'Z@',), 'NSDrawButton': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSSetShowsServicesMenuItem': (sel32or64(b'i@Z', b'q@Z'),), 'NSOpenGLGetOption': (b'vI^i', '', {'arguments': {1: {'type_modifier': 'o'}}}), 'NSCreateFileContentsPboardType': (b'@@', '', {'retval': {'already_cfretained': True}}), 'NSCopyBits': (sel32or64(b'vi{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSPoint=ff}', b'vq{CGRect={CGPoint=dd}{CGSize=dd}}{CGPoint=dd}'), '', {'retval': {'already_cfretained': True}}), 'NSDisableScreenUpdates': (b'v',), 'NSEdgeInsetsMake': (sel32or64(b'{NSEdgeInsets=ffff}ffff', b'{NSEdgeInsets=dddd}dddd'),), 'NSReadPixel': (sel32or64(b'@{_NSPoint=ff}', b'@{CGPoint=dd}'),), 'NSWindowListForContext': (sel32or64(b'vii^i', b'vqq^q'), '', {'arguments': {2: {'c_array_length_in_arg': 1, 'type_modifier': 'o'}}}), 'NSAccessibilityRoleDescriptionForUIElement': (b'@@',), 'NSDrawWindowBackground': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSShowsServicesMenuItem': (b'Z@',), 'NSPlanarFromDepth': (b'Zi',), 'NSHighlightRect': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSFrameRectWithWidthUsingOperation': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}fI', b'v{CGRect={CGPoint=dd}{CGSize=dd}}dQ'),), 'NSRectFillListWithColorsUsingOperation': (sel32or64(b'v^{_NSRect={_NSPoint=ff}{_NSSize=ff}}^@iI', b'v^{CGRect={CGPoint=dd}{CGSize=dd}}^@qQ'), '', {'arguments': {0: {'c_array_length_in_arg': 2, 'type_modifier': 'n'}, 1: {'c_array_length_in_arg': 2, 'type_modifier': 'n'}}}), 'NSDrawGroove': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSNumberOfColorComponents': (sel32or64(b'i@', b'q@'),), 'NSFrameRectWithWidth': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}f', b'v{CGRect={CGPoint=dd}{CGSize=dd}}d'),), 'NSEraseRect': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSRectFillListWithColors': (sel32or64(b'v^{_NSRect={_NSPoint=ff}{_NSSize=ff}}^@i', b'v^{CGRect={CGPoint=dd}{CGSize=dd}}^@q'), '', {'arguments': {0: {'c_array_length_in_arg': 2, 'type_modifier': 'n'}, 1: {'c_array_length_in_arg': 2, 'type_modifier': 'n'}}}), 'NSBestDepth': (sel32or64(b'i@iiZ^Z', b'i@qqZ^Z'), '', {'arguments': {4: {'type_modifier': 'o'}}}), 'NSColorSpaceFromDepth': (b'@i',), 'NSBeep': (b'v',), 'NSAccessibilitySetMayContainProtectedContent': (b'ZZ',), 'NSBitsPerPixelFromDepth': (sel32or64(b'ii', b'qi'),), 'NSAccessibilityUnignoredChildrenForOnlyChild': (b'@@',), 'NSDrawGrayBezel': (sel32or64(b'v{_NSRect={_NSPoint=ff}{_NSSize=ff}}{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'v{CGRect={CGPoint=dd}{CGSize=dd}}{CGRect={CGPoint=dd}{CGSize=dd}}'),), 'NSRectFillList': (sel32or64(b'v^{_NSRect={_NSPoint=ff}{_NSSize=ff}}i', b'v^{CGRect={CGPoint=dd}{CGSize=dd}}q'), '', {'arguments': {0: {'c_array_length_in_arg': 1, 'type_modifier': 'n'}}}), 'NSRunAlertPanel': (sel32or64(b'i@@@@@', b'q@@@@@'), '', {'arguments': {1: {'printf_format': 1}}, 'variadic': True}), 'NSGetInformationalAlertPanel': (b'@@@@@@', '', {'arguments': {1: {'printf_format': True}}, 'variadic': True}), 'NSRectFillListWithGrays': (sel32or64(b'v^{_NSRect={_NSPoint=ff}{_NSSize=ff}}^fi', b'v^{CGRect={CGPoint=dd}{CGSize=dd}}^dq'), '', {'arguments': {0: {'c_array_length_in_arg': 2, 'type_modifier': 'n'}, 1: {'c_array_length_in_arg': 2, 'type_modifier': 'n'}}}), 'NSRunInformationalAlertPanel': (sel32or64(b'i@@@@@', b'q@@@@@'), '', {'arguments': {1: {'printf_format': 1}}, 'variadic': True}), 'NSRegisterServicesProvider': (b'v@@',)}
aliases = {'NSLayoutFormatAlignAllLastBaseline': 'NSLayoutFormatAlignAllBaseline', 'NSImageRepRegistryChangedNotification': 'NSImageRepRegistryDidChangeNotification', 'NSDragOperationAll': 'NSDragOperationAll_Obsolete', 'NSTickMarkRight': 'NSTickMarkBelow', 'NSModalPanelWindowLevel': 'kCGModalPanelWindowLevel', 'NSSubmenuWindowLevel': 'kCGTornOffMenuWindowLevel', 'NSGestureRecognizerStateRecognized': 'NSGestureRecognizerStateEnded', 'NSTornOffMenuWindowLevel': 'kCGTornOffMenuWindowLevel', 'NSPopUpMenuWindowLevel': 'kCGPopUpMenuWindowLevel', 'NSMainMenuWindowLevel': 'kCGMainMenuWindowLevel', 'NSDraggingItemEnumerationConcurrent': 'NSEnumerationConcurrent', 'NSScreenSaverWindowLevel': 'kCGScreenSaverWindowLevel', 'NSEventDurationForever': 'DBL_MAX', 'APPKIT_PRIVATE_EXTERN': '__private_extern__', 'NSLayoutAttributeLastBaseline': 'NSLayoutAttributeBaseline', 'IBAction': 'void', 'NSFileHandlingPanelCancelButton': 'NSModalResponseCancel', 'NSNormalWindowLevel': 'kCGNormalWindowLevel', 'NSFileHandlingPanelOKButton': 'NSModalResponseOK', 'NSFloatingWindowLevel': 'kCGFloatingWindowLevel', 'NSDockWindowLevel': 'kCGDockWindowLevel', 'NSTickMarkLeft': 'NSTickMarkAbove', 'NSStackViewSpacingUseDefault': 'FLT_MAX', 'NSStatusWindowLevel': 'kCGStatusWindowLevel'}
misc.update({'NSModalSession': objc.createOpaquePointerType('NSModalSession', b'^{_NSModalSession}')})
r = objc.registerMetaDataForSelector
objc._updatingMetadata(True)
try:
r(b'CIImage', b'drawAtPoint:fromRect:operation:fraction:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'CIImage', b'drawInRect:fromRect:operation:fraction:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSATSTypesetter', b'bidiProcessingEnabled', {'retval': {'type': 'Z'}})
r(b'NSATSTypesetter', b'boundingBoxForControlGlyphAtIndex:forTextContainer:proposedLineFragment:glyphPosition:characterIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 6: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSATSTypesetter', b'characterRangeForGlyphRange:actualGlyphRange:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o'}}})
r(b'NSATSTypesetter', b'deleteGlyphsInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSATSTypesetter', b'getGlyphsInRange:glyphs:characterIndexes:glyphInscriptions:elasticBits:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 4: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 5: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 6: {'type': '^Z', 'type_modifier': b'o', 'c_array_length_in_arg': 2}}})
r(b'NSATSTypesetter', b'getLineFragmentRect:usedRect:forParagraphSeparatorGlyphRange:atProposedOrigin:', {'retval': {'type': 'v'}, 'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSATSTypesetter', b'glyphRangeForCharacterRange:actualCharacterRange:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o'}}})
r(b'NSATSTypesetter', b'layoutParagraphAtPoint:', {'arguments': {2: {'type_modifier': b'N'}}})
r(b'NSATSTypesetter', b'lineFragmentRectForProposedRect:remainingRect:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type_modifier': b'o'}}})
r(b'NSATSTypesetter', b'lineSpacingAfterGlyphAtIndex:withProposedLineFragmentRect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSATSTypesetter', b'paragraphGlyphRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSATSTypesetter', b'paragraphSeparatorGlyphRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSATSTypesetter', b'paragraphSpacingAfterGlyphAtIndex:withProposedLineFragmentRect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSATSTypesetter', b'paragraphSpacingBeforeGlyphAtIndex:withProposedLineFragmentRect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSATSTypesetter', b'setAttachmentSize:forGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSATSTypesetter', b'setBidiLevels:forGlyphRange:', {'arguments': {2: {'type': '^z', 'type_modifier': b'n', 'c_array_length_in_arg': 3}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSATSTypesetter', b'setBidiProcessingEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSATSTypesetter', b'setDrawsOutsideLineFragment:forGlyphRange:', {'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSATSTypesetter', b'setHardInvalidation:forGlyphRange:', {'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSATSTypesetter', b'setLineFragmentRect:forGlyphRange:usedRect:baselineOffset:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'f', b'd')}}})
r(b'NSATSTypesetter', b'setLocation:withAdvancements:forStartOfGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSATSTypesetter', b'setNotShownAttribute:forGlyphRange:', {'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSATSTypesetter', b'setParagraphGlyphRange:separatorGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSATSTypesetter', b'setUsesFontLeading:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSATSTypesetter', b'shouldBreakLineByHyphenatingBeforeCharacterAtIndex:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSATSTypesetter', b'shouldBreakLineByWordBeforeCharacterAtIndex:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSATSTypesetter', b'substituteGlyphsInRange:withGlyphs:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 2}}})
r(b'NSATSTypesetter', b'usesFontLeading', {'retval': {'type': 'Z'}})
r(b'NSATSTypesetter', b'willSetLineFragmentRect:forGlyphRange:usedRect:baselineOffset:', {'arguments': {2: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 5: {'type': sel32or64(b'^f', b'^d'), 'type_modifier': b'N'}}})
r(b'NSAccessibilityCustomAction', b'handler', {'retval': {'callable': {'retval': {'type': b'Z'}, 'arguments': {0: {'type': b'^v'}}}}})
r(b'NSAccessibilityCustomAction', b'initWithName:handler:', {'arguments': {3: {'callable': {'retval': {'type': b'Z'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSAccessibilityCustomAction', b'initWithName:target:selector:', {'arguments': {4: {'sel_of_type': b'Z@:'}}})
r(b'NSAccessibilityCustomAction', b'setHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'Z'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSActionCell', b'setAction:', {'retval': {'type': 'v'}, 'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSActionCell', b'setBezeled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSActionCell', b'setBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSActionCell', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSActionCell', b'setFloatingPointFormat:left:right:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSAlert', b'alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat:', {'arguments': {6: {'printf_format': True, 'type': '@'}}, 'variadic': True})
r(b'NSAlert', b'beginSheetModalForWindow:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSAlert', b'beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:', {'arguments': {4: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 5: {'type': '^v'}}})
r(b'NSAlert', b'setShowsHelp:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSAlert', b'setShowsSuppressionButton:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSAlert', b'showsHelp', {'retval': {'type': 'Z'}})
r(b'NSAlert', b'showsSuppressionButton', {'retval': {'type': 'Z'}})
r(b'NSAnimation', b'isAnimating', {'retval': {'type': 'Z'}})
r(b'NSAnimationContext', b'allowsImplicitAnimation', {'retval': {'type': b'Z'}})
r(b'NSAnimationContext', b'completionHandler', {'retval': {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}})
r(b'NSAnimationContext', b'runAnimationGroup:completionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}, 3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSAnimationContext', b'setAllowsImplicitAnimation:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSAnimationContext', b'setCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSAppearance', b'allowsVibrancy', {'retval': {'type': b'Z'}})
r(b'NSApplication', b'activateIgnoringOtherApps:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSApplication', b'addWindowsItem:title:filename:', {'arguments': {4: {'type': 'Z'}}})
r(b'NSApplication', b'beginSheet:modalForWindow:modalDelegate:didEndSelector:contextInfo:', {'arguments': {5: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 6: {'type': '^v'}}})
r(b'NSApplication', b'changeWindowsItem:title:filename:', {'arguments': {4: {'type': 'Z'}}})
r(b'NSApplication', b'detachDrawingThread:toTarget:withObject:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSApplication', b'enumerateWindowsWithOptions:usingBlock:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'o^Z'}}}}}})
r(b'NSApplication', b'isActive', {'retval': {'type': 'Z'}})
r(b'NSApplication', b'isAutomaticCustomizeTouchBarMenuItemEnabled', {'retval': {'type': 'Z'}})
r(b'NSApplication', b'isFullKeyboardAccessEnabled', {'retval': {'type': 'Z'}})
r(b'NSApplication', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSApplication', b'isRunning', {'retval': {'type': 'Z'}})
r(b'NSApplication', b'makeWindowsPerform:inOrder:', {'arguments': {2: {'sel_of_type': b'v@:'}, 3: {'type': 'Z'}}})
r(b'NSApplication', b'nextEventMatchingMask:untilDate:inMode:dequeue:', {'arguments': {5: {'type': 'Z'}}})
r(b'NSApplication', b'postEvent:atStart:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSApplication', b'replyToApplicationShouldTerminate:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSApplication', b'restoreWindowWithIdentifier:state:completionHandler:', {'retval': {'type': b'Z'}, 'arguments': {4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}, 'type': '@?'}}})
r(b'NSApplication', b'searchString:inUserInterfaceItemString:searchRange:foundRange:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSApplication', b'sendAction:to:from:', {'retval': {'type': 'Z'}, 'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSApplication', b'setActivationPolicy:', {'retval': {'type': 'Z'}})
r(b'NSApplication', b'setAutomaticCustomizeTouchBarMenuItemEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSApplication', b'setWindowsNeedUpdate:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSApplication', b'targetForAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSApplication', b'targetForAction:to:from:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSApplication', b'tryToPerform:with:', {'retval': {'type': 'Z'}, 'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSArrayController', b'addSelectedObjects:', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'addSelectionIndexes:', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'alwaysUsesMultipleValuesMarker', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'automaticallyRearrangesObjects', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'avoidsEmptySelection', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'canInsert', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'canSelectNext', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'canSelectPrevious', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'clearsFilterPredicateOnInsertion', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'preservesSelection', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'removeSelectedObjects:', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'removeSelectionIndexes:', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'selectsInsertedObjects', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'setAlwaysUsesMultipleValuesMarker:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSArrayController', b'setAutomaticallyRearrangesObjects:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSArrayController', b'setAvoidsEmptySelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSArrayController', b'setClearsFilterPredicateOnInsertion:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSArrayController', b'setPreservesSelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSArrayController', b'setSelectedObjects:', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'setSelectionIndex:', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'setSelectionIndexes:', {'retval': {'type': 'Z'}})
r(b'NSArrayController', b'setSelectsInsertedObjects:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSAttributedString', b'RTFDFileWrapperFromRange:documentAttributes:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSAttributedString', b'RTFDFromRange:documentAttributes:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSAttributedString', b'RTFFromRange:documentAttributes:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSAttributedString', b'URLAtIndex:effectiveRange:', {'arguments': {3: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSAttributedString', b'boundingRectWithSize:options:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSAttributedString', b'containsAttachments', {'retval': {'type': 'Z'}})
r(b'NSAttributedString', b'containsAttachmentsInRange:', {'retval': {'type': 'Z'}})
r(b'NSAttributedString', b'dataFromRange:documentAttributes:error:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'docFormatFromRange:documentAttributes:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSAttributedString', b'doubleClickAtIndex:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSAttributedString', b'drawAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSAttributedString', b'drawInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSAttributedString', b'drawWithRect:options:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSAttributedString', b'fileWrapperFromRange:documentAttributes:error:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'fontAttributesInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSAttributedString', b'initWithData:options:documentAttributes:error:', {'arguments': {4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithDocFormat:documentAttributes:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithHTML:baseURL:documentAttributes:', {'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithHTML:documentAttributes:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithHTML:options:documentAttributes:', {'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithPath:documentAttributes:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithRTF:documentAttributes:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithRTFD:documentAttributes:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithRTFDFileWrapper:documentAttributes:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithURL:documentAttributes:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'initWithURL:options:documentAttributes:error:', {'arguments': {4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}}})
r(b'NSAttributedString', b'lineBreakBeforeIndex:withinRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSAttributedString', b'lineBreakByHyphenatingBeforeIndex:withinRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSAttributedString', b'nextWordFromIndex:forward:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSAttributedString', b'rangeOfTextBlock:atIndex:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSAttributedString', b'rangeOfTextList:atIndex:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSAttributedString', b'rangeOfTextTable:atIndex:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSAttributedString', b'rulerAttributesInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSAttributedString', b'size', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSBezierPath', b'appendBezierPathWithArcFromPoint:toPoint:radius:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'appendBezierPathWithArcWithCenter:radius:startAngle:endAngle:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'appendBezierPathWithArcWithCenter:radius:startAngle:endAngle:clockwise:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 6: {'type': 'Z'}}})
r(b'NSBezierPath', b'appendBezierPathWithGlyphs:count:inFont:', {'arguments': {2: {'type_modifier': b'n', 'c_array_length_in_arg': 3}}})
r(b'NSBezierPath', b'appendBezierPathWithOvalInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBezierPath', b'appendBezierPathWithPackedGlyphs:', {'arguments': {2: {'c_array_delimited_by_null': True, 'type': '^v', 'type_modifier': b'n', 'c_array_length_in_arg': 3}}})
r(b'NSBezierPath', b'appendBezierPathWithPoints:count:', {'arguments': {2: {'type_modifier': b'n', 'c_array_length_in_arg': 3}}})
r(b'NSBezierPath', b'appendBezierPathWithRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBezierPath', b'appendBezierPathWithRoundedRect:xRadius:yRadius:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBezierPath', b'bezierPathWithOvalInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBezierPath', b'bezierPathWithRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBezierPath', b'bezierPathWithRoundedRect:xRadius:yRadius:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBezierPath', b'bounds', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSBezierPath', b'cachesBezierPath', {'retval': {'type': 'Z'}})
r(b'NSBezierPath', b'clipRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBezierPath', b'containsPoint:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'controlPointBounds', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSBezierPath', b'currentPoint', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSBezierPath', b'curveToPoint:controlPoint1:controlPoint2:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'drawPackedGlyphs:atPoint:', {'arguments': {2: {'c_array_delimited_by_null': True, 'type': '^v', 'type_modifier': b'n'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'elementAtIndex:associatedPoints:', {'arguments': {3: {'type_modifier': b'o', 'c_array_of_variable_length': True}}})
r(b'NSBezierPath', b'fillRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBezierPath', b'getLineDash:count:phase:', {'arguments': {2: {'type_modifier': b'o', 'c_array_length_in_arg': 3}, 3: {'type_modifier': b'N'}, 4: {'type_modifier': b'o'}}})
r(b'NSBezierPath', b'isEmpty', {'retval': {'type': 'Z'}})
r(b'NSBezierPath', b'lineToPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'moveToPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'relativeCurveToPoint:controlPoint1:controlPoint2:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'relativeLineToPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'relativeMoveToPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'setAssociatedPoints:atIndex:', {'arguments': {2: {'c_array_of_variable_length': True}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSBezierPath', b'setCachesBezierPath:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBezierPath', b'setLineDash:count:phase:', {'arguments': {2: {'type_modifier': b'n', 'c_array_length_in_arg': 3}}})
r(b'NSBezierPath', b'strokeLineFromPoint:toPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSBezierPath', b'strokeRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBitmapImageRep', b'CGImage', {'retval': {'type': '^{CGImage=}'}})
r(b'NSBitmapImageRep', b'bitmapData', {'retval': {'type': '^v', 'c_array_of_variable_length': True}})
r(b'NSBitmapImageRep', b'canBeCompressedUsing:', {'retval': {'type': 'Z'}})
r(b'NSBitmapImageRep', b'getBitmapDataPlanes:', {'arguments': {2: {'type': '^*', 'c_array_of_variable_length': True}}})
r(b'NSBitmapImageRep', b'getCompression:factor:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSBitmapImageRep', b'getPixel:atX:y:', {'arguments': {2: {'type_modifier': b'o', 'c_array_of_variable_length': True}}})
r(b'NSBitmapImageRep', b'getTIFFCompressionTypes:count:', {'arguments': {2: {'type': sel32or64(b'^^I', b'^^Q'), 'type_modifier': b'o', 'c_array_length_in_arg': 3}, 3: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'o', 'c_array_length_in_arg': 3}}})
r(b'NSBitmapImageRep', b'incrementalLoadFromData:complete:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSBitmapImageRep', b'initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bitmapFormat:bytesPerRow:bitsPerPixel:', {'arguments': {2: {'type': '^*'}, 7: {'type': b'Z'}, 8: {'type': b'Z'}}})
r(b'NSBitmapImageRep', b'initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bytesPerRow:bitsPerPixel:', {'arguments': {2: {'type': '^*'}, 7: {'type': b'Z'}, 8: {'type': b'Z'}}})
r(b'NSBitmapImageRep', b'initWithCGImage:', {'arguments': {2: {'type': '^{CGImage=}'}}})
r(b'NSBitmapImageRep', b'initWithFocusedViewRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBitmapImageRep', b'isPlanar', {'retval': {'type': 'Z'}})
r(b'NSBitmapImageRep', b'setPixel:atX:y:', {'arguments': {2: {'type': sel32or64(b'^I', b'^Q'), 'type_modifier': b'n', 'c_array_of_variable_length': True}}})
r(b'NSBox', b'borderRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSBox', b'contentViewMargins', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSBox', b'isTransparent', {'retval': {'type': 'Z'}})
r(b'NSBox', b'setContentViewMargins:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSBox', b'setFrameFromContentFrame:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBox', b'setTransparent:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBox', b'titleRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSBrowser', b'acceptsArrowKeys', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'allowsBranchSelection', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'allowsEmptySelection', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'allowsMultipleSelection', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'allowsTypeSelect', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'autohidesScroller', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'canDragRowsWithIndexes:inColumn:withEvent:', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'draggingImageForRowsWithIndexes:inColumn:withEvent:offset:', {'arguments': {5: {'type_modifier': b'N'}}})
r(b'NSBrowser', b'drawTitleOfColumn:inRect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSBrowser', b'editItemAtIndexPath:withEvent:select:', {'arguments': {4: {'type': 'Z'}}})
r(b'NSBrowser', b'frameOfColumn:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSBrowser', b'frameOfInsideOfColumn:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSBrowser', b'getRow:column:forPoint:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSBrowser', b'hasHorizontalScroller', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'isLeafItem:', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'isLoaded', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'isTitled', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'prefersAllColumnUserResizing', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'reusesColumns', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'sendAction', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'sendsActionOnArrowKeys', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'separatesColumns', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'setAcceptsArrowKeys:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setAllowsBranchSelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setAllowsEmptySelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setAllowsMultipleSelection:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setAllowsTypeSelect:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setAutohidesScroller:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setDoubleAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSBrowser', b'setDraggingSourceOperationMask:forLocal:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSBrowser', b'setHasHorizontalScroller:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setPath:', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'setPrefersAllColumnUserResizing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setReusesColumns:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setSendsActionOnArrowKeys:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setSeparatesColumns:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setTakesTitleFromPreviousColumn:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'setTitled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowser', b'takesTitleFromPreviousColumn', {'retval': {'type': 'Z'}})
r(b'NSBrowser', b'titleFrameOfColumn:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSBrowserCell', b'isLeaf', {'retval': {'type': 'Z'}})
r(b'NSBrowserCell', b'isLoaded', {'retval': {'type': 'Z'}})
r(b'NSBrowserCell', b'setLeaf:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSBrowserCell', b'setLoaded:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSBundle', b'loadNibFile:externalNameTable:withZone:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type': '^{_NSZone=}'}}})
r(b'NSBundle', b'loadNibNamed:owner:', {'retval': {'type': 'Z'}})
r(b'NSBundle', b'loadNibNamed:owner:topLevelObjects:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSButton', b'allowsMixedState', {'retval': {'type': 'Z'}})
r(b'NSButton', b'buttonWithImage:target:action:', {'arguments': {4: {'sel_of_type': b'v@:@'}}})
r(b'NSButton', b'buttonWithTitle:image:target:action:', {'arguments': {5: {'sel_of_type': b'v@:@'}}})
r(b'NSButton', b'buttonWithTitle:target:action:', {'arguments': {4: {'sel_of_type': b'v@:@'}}})
r(b'NSButton', b'checkboxWithTitle:target:action:', {'arguments': {4: {'sel_of_type': b'v@:@'}}})
r(b'NSButton', b'getPeriodicDelay:interval:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSButton', b'highlight:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButton', b'imageHugsTitle', {'retval': {'type': 'Z'}})
r(b'NSButton', b'isBordered', {'retval': {'type': 'Z'}})
r(b'NSButton', b'isSpringLoaded', {'retval': {'type': b'Z'}})
r(b'NSButton', b'isTransparent', {'retval': {'type': 'Z'}})
r(b'NSButton', b'performKeyEquivalent:', {'retval': {'type': 'Z'}})
r(b'NSButton', b'radioButtonWithTitle:target:action:', {'arguments': {4: {'sel_of_type': b'v@:@'}}})
r(b'NSButton', b'setAllowsMixedState:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButton', b'setBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButton', b'setImageHugsTitle:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButton', b'setShowsBorderOnlyWhileMouseInside:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButton', b'setSpringLoaded:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSButton', b'setTransparent:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButton', b'showsBorderOnlyWhileMouseInside', {'retval': {'type': 'Z'}})
r(b'NSButtonCell', b'drawBezelWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSButtonCell', b'drawImage:withFrame:inView:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSButtonCell', b'drawTitle:withFrame:inView:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSButtonCell', b'getPeriodicDelay:interval:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSButtonCell', b'imageDimsWhenDisabled', {'retval': {'type': 'Z'}})
r(b'NSButtonCell', b'isOpaque', {'retval': {'type': 'Z'}})
r(b'NSButtonCell', b'isTransparent', {'retval': {'type': 'Z'}})
r(b'NSButtonCell', b'setImageDimsWhenDisabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButtonCell', b'setShowsBorderOnlyWhileMouseInside:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButtonCell', b'setTransparent:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSButtonCell', b'showsBorderOnlyWhileMouseInside', {'retval': {'type': 'Z'}})
r(b'NSCachedImageRep', b'initWithSize:depth:separate:alpha:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 4: {'type': 'Z'}, 5: {'type': 'Z'}}})
r(b'NSCachedImageRep', b'initWithWindow:rect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCachedImageRep', b'rect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSCandidateListTouchBarItem', b'allowsCollapsing', {'retval': {'type': 'Z'}})
r(b'NSCandidateListTouchBarItem', b'allowsTextInputContextCandidates', {'retval': {'type': 'Z'}})
r(b'NSCandidateListTouchBarItem', b'attributedStringForCandidate', {'retval': {'callable': {'retval': {'type': b'@'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': sel32or64(b'i', b'q')}}}}})
r(b'NSCandidateListTouchBarItem', b'isCandidateListVisible', {'retval': {'type': 'Z'}})
r(b'NSCandidateListTouchBarItem', b'isCollapsed', {'retval': {'type': 'Z'}})
r(b'NSCandidateListTouchBarItem', b'setAllowsCollapsing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCandidateListTouchBarItem', b'setAllowsTextInputContextCandidates:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCandidateListTouchBarItem', b'setAttributedStringForCandidate:', {'arguments': {2: {'callable': {'retval': {'type': b'@'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSCandidateListTouchBarItem', b'setCandidateListVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCandidateListTouchBarItem', b'setCollapsed:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCandidateListTouchBarItem', b'updateWithInsertionPointVisibility:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'acceptsFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSCell', b'action', {'retval': {'type': ':', 'sel_of_type': b'v@:@'}})
r(b'NSCell', b'allowsEditingTextAttributes', {'retval': {'type': 'Z'}})
r(b'NSCell', b'allowsMixedState', {'retval': {'type': 'Z'}})
r(b'NSCell', b'allowsUndo', {'retval': {'type': 'Z'}})
r(b'NSCell', b'calcDrawInfo:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'cellSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSCell', b'cellSizeForBounds:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'continueTracking:at:inView:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSCell', b'drawInteriorWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'drawWithExpansionFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'drawWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'drawingRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'editWithFrame:inView:editor:delegate:event:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'expansionFrameWithFrame:inView:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'getPeriodicDelay:interval:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSCell', b'hasValidObjectValue', {'retval': {'type': 'Z'}})
r(b'NSCell', b'highlight:withFrame:inView:', {'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'highlightColorWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'hitTestForEvent:inRect:ofView:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'imageRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'importsGraphics', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isBezeled', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isBordered', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isContinuous', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isEntryAcceptable:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': '@'}}})
r(b'NSCell', b'isHighlighted', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isOpaque', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isScrollable', {'retval': {'type': 'Z'}})
r(b'NSCell', b'isSelectable', {'retval': {'type': 'Z'}})
r(b'NSCell', b'menuForEvent:inRect:ofView:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'prefersTrackingUntilMouseUp', {'retval': {'type': 'Z'}})
r(b'NSCell', b'refusesFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSCell', b'resetCursorRect:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'selectWithFrame:inView:editor:delegate:start:length:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'sendsActionOnEndEditing', {'retval': {'type': 'Z'}})
r(b'NSCell', b'setAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSCell', b'setAllowsEditingTextAttributes:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setAllowsMixedState:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setAllowsUndo:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setAttributedStringValue:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': '@'}}})
r(b'NSCell', b'setBezeled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setContinuous:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setFloatingPointFormat:left:right:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setHighlighted:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setImportsGraphics:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setRefusesFirstResponder:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setScrollable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setSelectable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setSendsActionOnEndEditing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setShowsFirstResponder:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setTruncatesLastVisibleLine:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setUsesSingleLineMode:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'setWraps:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCell', b'showsFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSCell', b'startTrackingAt:inView:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSCell', b'stopTracking:at:inView:mouseIsUp:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': 'Z'}}})
r(b'NSCell', b'titleRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSCell', b'trackMouse:inRect:ofView:untilMouseUp:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': 'Z'}}})
r(b'NSCell', b'truncatesLastVisibleLine', {'retval': {'type': 'Z'}})
r(b'NSCell', b'usesSingleLineMode', {'retval': {'type': 'Z'}})
r(b'NSCell', b'wantsNotificationForMarkedText', {'retval': {'type': 'Z'}})
r(b'NSCell', b'wraps', {'retval': {'type': 'Z'}})
r(b'NSClipView', b'automaticallyAdjustsContentInsets', {'retval': {'type': b'Z'}})
r(b'NSClipView', b'autoscroll:', {'retval': {'type': 'Z'}})
r(b'NSClipView', b'copiesOnScroll', {'retval': {'type': 'Z'}})
r(b'NSClipView', b'documentRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSClipView', b'documentVisibleRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSClipView', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSClipView', b'onstrainScrollPoint:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSClipView', b'scrollToPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSClipView', b'setAutomaticallyAdjustsContentInsets:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSClipView', b'setCopiesOnScroll:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSClipView', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionView', b'allowsEmptySelection', {'retval': {'type': 'Z'}})
r(b'NSCollectionView', b'allowsMultipleSelection', {'retval': {'type': 'Z'}})
r(b'NSCollectionView', b'backgroundViewScrollsWithContent', {'retval': {'type': 'Z'}})
r(b'NSCollectionView', b'draggingImageForItemsAtIndexPaths:withEvent:offset:', {'arguments': {4: {'type_modifier': b'N'}}})
r(b'NSCollectionView', b'draggingImageForItemsAtIndexes:withEvent:offset:', {'arguments': {4: {'type_modifier': b'N'}}})
r(b'NSCollectionView', b'frameForItemAtIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSCollectionView', b'isFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSCollectionView', b'isSelectable', {'retval': {'type': 'Z'}})
r(b'NSCollectionView', b'maxItemSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSCollectionView', b'minItemSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSCollectionView', b'performBatchUpdates:completionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}, 3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'Z'}}}}}})
r(b'NSCollectionView', b'setAllowsEmptySelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionView', b'setAllowsMultipleSelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionView', b'setBackgroundViewScrollsWithContent:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionView', b'setDraggingSourceOperationMask:forLocal:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSCollectionView', b'setMaxItemSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSCollectionView', b'setMinItemSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSCollectionView', b'setSelectable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionViewFlowLayout', b'invalidateFlowLayoutDelegateMetrics', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewFlowLayout', b'sectionAtIndexIsCollapsed:', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewFlowLayout', b'sectionFootersPinToVisibleBounds', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewFlowLayout', b'sectionHeadersPinToVisibleBounds', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewFlowLayout', b'setSectionFootersPinToVisibleBounds:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionViewFlowLayout', b'setSectionHeadersPinToVisibleBounds:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionViewFlowLayout', b'shouldInvalidateLayoutForBoundsChange:', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewFlowLayoutInvalidationContext', b'invalidateFlowLayoutAttributes', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewFlowLayoutInvalidationContext', b'invalidateFlowLayoutDelegateMetrics', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewFlowLayoutInvalidationContext', b'setInvalidateFlowLayoutAttributes:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionViewFlowLayoutInvalidationContext', b'setInvalidateFlowLayoutDelegateMetrics:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionViewItem', b'isSelected', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewItem', b'setSelected:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionViewLayout', b'shouldInvalidateLayoutForBoundsChange:', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewLayout', b'shouldInvalidateLayoutForPreferredLayoutAttributes:withOriginalAttributes:', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewLayoutAttributes', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewLayoutAttributes', b'setHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCollectionViewLayoutInvalidationContext', b'invalidateDataSourceCounts', {'retval': {'type': 'Z'}})
r(b'NSCollectionViewLayoutInvalidationContext', b'invalidateEverything', {'retval': {'type': 'Z'}})
r(b'NSColor', b'colorWithColorSpace:components:count:', {'arguments': {3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}}})
r(b'NSColor', b'drawSwatchInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSColor', b'getComponents:', {'arguments': {2: {'type': sel32or64(b'^f', b'^d'), 'type_modifier': b'o', 'c_array_of_variable_length': True}}})
r(b'NSColor', b'getCyan:magenta:yellow:black:alpha:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}, 4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}, 6: {'type_modifier': b'o'}}})
r(b'NSColor', b'getHue:saturation:brightness:alpha:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}, 4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}}})
r(b'NSColor', b'getRed:green:blue:alpha:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}, 4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}}})
r(b'NSColor', b'getWhite:alpha:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSColor', b'ignoresAlpha', {'retval': {'type': 'Z'}})
r(b'NSColor', b'setIgnoresAlpha:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSColorList', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSColorList', b'writeToFile:', {'retval': {'type': 'Z'}})
r(b'NSColorList', b'writeToURL:error:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSColorPanel', b'dragColor:withEvent:fromView:', {'retval': {'type': 'Z'}})
r(b'NSColorPanel', b'isContinuous', {'retval': {'type': 'Z'}})
r(b'NSColorPanel', b'setAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSColorPanel', b'setContinuous:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSColorPanel', b'setShowsAlpha:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSColorPanel', b'sharedColorPanelExists', {'retval': {'type': 'Z'}})
r(b'NSColorPanel', b'showsAlpha', {'retval': {'type': 'Z'}})
r(b'NSColorPicker', b'minContentSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSColorPickerTouchBarItem', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSColorPickerTouchBarItem', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSColorPickerTouchBarItem', b'setShowsAlpha:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSColorPickerTouchBarItem', b'showsAlpha', {'retval': {'type': 'Z'}})
r(b'NSColorSpace', b'CGColorSpace', {'retval': {'type': '^{CGColorSpace=}'}})
r(b'NSColorSpace', b'colorSyncProfile', {'retval': {'type': '^{OpaqueCMProfileRef=}'}})
r(b'NSColorSpace', b'initWithCGColorSpace:', {'arguments': {2: {'type': '^{CGColorSpace=}'}}})
r(b'NSColorSpace', b'initWithColorSyncProfile:', {'arguments': {2: {'type': '^{OpaqueCMProfileRef=}'}}})
r(b'NSColorWell', b'activate:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSColorWell', b'drawWellInside:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSColorWell', b'isActive', {'retval': {'type': 'Z'}})
r(b'NSColorWell', b'isBordered', {'retval': {'type': 'Z'}})
r(b'NSColorWell', b'setBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBox', b'completes', {'retval': {'type': 'Z'}})
r(b'NSComboBox', b'hasVerticalScroller', {'retval': {'type': 'Z'}})
r(b'NSComboBox', b'intercellSpacing', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSComboBox', b'isButtonBordered', {'retval': {'type': 'Z'}})
r(b'NSComboBox', b'setButtonBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBox', b'setCompletes:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBox', b'setHasVerticalScroller:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBox', b'setIntercellSpacing:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSComboBox', b'setUsesDataSource:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBox', b'usesDataSource', {'retval': {'type': 'Z'}})
r(b'NSComboBoxCell', b'completes', {'retval': {'type': 'Z'}})
r(b'NSComboBoxCell', b'hasVerticalScroller', {'retval': {'type': 'Z'}})
r(b'NSComboBoxCell', b'intercellSpacing', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSComboBoxCell', b'isButtonBordered', {'retval': {'type': 'Z'}})
r(b'NSComboBoxCell', b'setButtonBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBoxCell', b'setCompletes:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBoxCell', b'setHasVerticalScroller:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBoxCell', b'setIntercellSpacing:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSComboBoxCell', b'setUsesDataSource:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSComboBoxCell', b'usesDataSource', {'retval': {'type': 'Z'}})
r(b'NSControl', b'abortEditing', {'retval': {'type': 'Z'}})
r(b'NSControl', b'action', {'retval': {'type': ':', 'sel_of_type': b'v@:@'}})
r(b'NSControl', b'allowsExpansionToolTips', {'retval': {'type': b'Z'}})
r(b'NSControl', b'ignoresMultiClick', {'retval': {'type': 'Z'}})
r(b'NSControl', b'initWithFrame:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSControl', b'isContinuous', {'retval': {'type': 'Z'}})
r(b'NSControl', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSControl', b'isHighlighted', {'retval': {'type': b'Z'}})
r(b'NSControl', b'refusesFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSControl', b'sendAction:to:', {'retval': {'type': 'Z'}, 'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSControl', b'setAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSControl', b'setAllowsExpansionToolTips:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSControl', b'setContinuous:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSControl', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSControl', b'setFloatingPointFormat:left:right:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSControl', b'setHighlighted:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSControl', b'setIgnoresMultiClick:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSControl', b'setRefusesFirstResponder:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSControl', b'setUsesSingleLineMode:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSControl', b'usesSingleLineMode', {'retval': {'type': b'Z'}})
r(b'NSController', b'commitEditing', {'retval': {'type': 'Z'}})
r(b'NSController', b'commitEditingWithDelegate:didCommitSelector:contextInfo:', {'arguments': {3: {'type': ':', 'sel_of_type': b'v@:@Z^v'}, 4: {'type': '^v'}}})
r(b'NSController', b'isEditing', {'retval': {'type': 'Z'}})
r(b'NSCursor', b'hotSpot', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSCursor', b'initWithImage:foregroundColorHint:backgroundColorHint:hotSpot:', {'arguments': {5: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSCursor', b'initWithImage:hotSpot:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSCursor', b'isSetOnMouseEntered', {'retval': {'type': 'Z'}})
r(b'NSCursor', b'isSetOnMouseExited', {'retval': {'type': 'Z'}})
r(b'NSCursor', b'setHiddenUntilMouseMoves:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCursor', b'setOnMouseEntered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCursor', b'setOnMouseExited:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSCustomImageRep', b'drawingHandler', {'retval': {'callable': {'retval': {'type': b'Z'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}}}})
r(b'NSCustomImageRep', b'initWithDrawSelector:delegate:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSCustomImageRep', b'initWithSize:flipped:drawingHandler:', {'arguments': {3: {'type': b'Z'}, 4: {'callable': {'retval': {'type': b'Z'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}}}}})
r(b'NSDatePicker', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSDatePicker', b'isBezeled', {'retval': {'type': 'Z'}})
r(b'NSDatePicker', b'isBordered', {'retval': {'type': 'Z'}})
r(b'NSDatePicker', b'setBezeled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDatePicker', b'setBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDatePicker', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDatePickerCell', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSDatePickerCell', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDockTile', b'performActivityWithSynchronousWaiting:usingBlock:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSDockTile', b'setShowsApplicationBadge:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDockTile', b'showsApplicationBadge', {'retval': {'type': 'Z'}})
r(b'NSDockTile', b'size', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSDocument', b'allowsDocumentSharing', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'autosaveDocumentWithDelegate:didAutosaveSelector:contextInfo:', {'arguments': {3: {'sel_of_type': b'v@:@Z^v'}, 4: {'type': '^v'}}})
r(b'NSDocument', b'autosaveWithImplicitCancellability:completionHandler:', {'arguments': {2: {'type': b'Z'}, 3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSDocument', b'autosavesDrafts', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'autosavesInPlace', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'autosavingIsImplicitlyCancellable', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'canAsynchronouslyWriteToURL:ofType:forSaveOperation:', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo:', {'arguments': {3: {'sel_of_type': b'v@:@Z^v'}, 4: {'type': '^v'}}})
r(b'NSDocument', b'canConcurrentlyReadDocumentsOfType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'checkAutosavingSafetyAndReturnError:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type_modifier': b'o'}}})
r(b'NSDocument', b'continueActivityUsingBlock:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSDocument', b'continueAsynchronousWorkOnMainThreadUsingBlock:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSDocument', b'dataOfType:error:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSDocument', b'duplicateAndReturnError:', {'arguments': {2: {'type_modifier': b'o'}}})
r(b'NSDocument', b'duplicateDocumentWithDelegate:didDuplicateSelector:contextInfo:', {'arguments': {3: {'sel_of_type': b'v@Z^v'}, 4: {'type': '^v'}}})
r(b'NSDocument', b'fileAttributesToWriteToURL:ofType:forSaveOperation:originalContentsURL:error:', {'arguments': {6: {'type_modifier': b'o'}}})
r(b'NSDocument', b'fileNameExtensionWasHiddenInLastRunSavePanel', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'fileWrapperOfType:error:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSDocument', b'hasUnautosavedChanges', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'hasUndoManager', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'initForURL:withContentsOfURL:ofType:error:', {'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSDocument', b'initWithContentsOfURL:ofType:error:', {'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSDocument', b'initWithType:error:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSDocument', b'isBrowsingVersions', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'isDocumentEdited', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'isDraft', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'isEntireFileLoaded', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'isInViewingMode', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'isLocked', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'isNativeType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'keepBackupFile', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'loadDataRepresentation:ofType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'loadFileWrapperRepresentation:ofType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'lockDocumentWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'Z'}}}}}})
r(b'NSDocument', b'lockWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSDocument', b'moveDocumentWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'Z'}}}}}})
r(b'NSDocument', b'moveToURL:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'Z'}}}}}})
r(b'NSDocument', b'performActivityWithSynchronousWaiting:usingBlock:', {'arguments': {2: {'type': b'Z'}, 3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSDocument', b'performAsynchronousFileAccessUsingBlock:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'callable': {'retval': {'type': 'v'}, 'arguments': {0: {'type': '^v'}}}, 'type': b'@?'}}}}}})
r(b'NSDocument', b'performSynchronousFileAccessUsingBlock:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSDocument', b'preparePageLayout:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'prepareSavePanel:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'presentError:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'presentError:modalForWindow:delegate:didPresentSelector:contextInfo:', {'arguments': {5: {'sel_of_type': b'v@:Z^v'}, 6: {'type': '^v'}}})
r(b'NSDocument', b'preservesVersions', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'printDocumentWithSettings:showPrintPanel:delegate:didPrintSelector:contextInfo:', {'arguments': {3: {'type': 'Z'}, 5: {'sel_of_type': b'v@:@Z^v'}, 6: {'type': '^v'}}})
r(b'NSDocument', b'printOperationWithSettings:error:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSDocument', b'printShowingPrintPanel:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDocument', b'readFromData:ofType:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSDocument', b'readFromFile:ofType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'readFromFileWrapper:ofType:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSDocument', b'readFromURL:ofType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'readFromURL:ofType:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSDocument', b'restoreDocumentWindowWithIdentifier:state:completionHandler:', {'arguments': {4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}}}})
r(b'NSDocument', b'revertToContentsOfURL:ofType:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSDocument', b'revertToSavedFromFile:ofType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'revertToSavedFromURL:ofType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'runModalPageLayoutWithPrintInfo:delegate:didRunSelector:contextInfo:', {'arguments': {4: {'sel_of_type': b'v@:@Z^v'}, 5: {'type': '^v'}}})
r(b'NSDocument', b'runModalPrintOperation:delegate:didRunSelector:contextInfo:', {'arguments': {4: {'sel_of_type': b'v@:@Z^v'}, 5: {'type': '^v'}}})
r(b'NSDocument', b'runModalSavePanelForSaveOperation:delegate:didSaveSelector:contextInfo:', {'arguments': {4: {'sel_of_type': b'v@:@Z^v'}, 5: {'type': '^v'}}})
r(b'NSDocument', b'saveDocumentWithDelegate:didSaveSelector:contextInfo:', {'arguments': {3: {'sel_of_type': b'v@:@Z^v'}, 4: {'type': '^v'}}})
r(b'NSDocument', b'saveToFile:saveOperation:delegate:didSaveSelector:contextInfo:', {'arguments': {5: {'sel_of_type': b'v@:@Z^v'}, 6: {'type': '^v'}}})
r(b'NSDocument', b'saveToURL:ofType:forSaveOperation:completionHandler:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSDocument', b'saveToURL:ofType:forSaveOperation:delegate:didSaveSelector:contextInfo:', {'arguments': {6: {'sel_of_type': b'v@:@Z^v'}, 7: {'type': '^v'}}})
r(b'NSDocument', b'saveToURL:ofType:forSaveOperation:error:', {'retval': {'type': 'Z'}, 'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSDocument', b'setDraft:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSDocument', b'setHasUndoManager:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDocument', b'shareDocumentWithSharingService:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'Z'}}}}}})
r(b'NSDocument', b'shouldChangePrintInfo:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'shouldCloseWindowController:delegate:shouldCloseSelector:contextInfo:', {'arguments': {4: {'sel_of_type': b'v@:@Z^v'}, 5: {'type': '^v'}}})
r(b'NSDocument', b'shouldRunSavePanelWithAccessoryView', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'stopBrowsingVersionsWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSDocument', b'unlockDocumentWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'Z'}}}}}})
r(b'NSDocument', b'unlockWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSDocument', b'usesUbiquitousStorage', {'retval': {'type': b'Z'}})
r(b'NSDocument', b'validateUserInterfaceItem:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'writeSafelyToURL:ofType:forSaveOperation:error:', {'retval': {'type': 'Z'}, 'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSDocument', b'writeToFile:ofType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'writeToFile:ofType:originalFile:saveOperation:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'writeToURL:ofType:', {'retval': {'type': 'Z'}})
r(b'NSDocument', b'writeToURL:ofType:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSDocument', b'writeToURL:ofType:forSaveOperation:originalContentsURL:error:', {'retval': {'type': 'Z'}, 'arguments': {6: {'type_modifier': b'o'}}})
r(b'NSDocument', b'writeWithBackupToFile:ofType:saveOperation:', {'retval': {'type': 'Z'}})
r(b'NSDocumentController', b'allowsAutomaticShareMenu', {'retval': {'type': 'Z'}})
r(b'NSDocumentController', b'beginOpenPanel:forTypes:completionHandler:', {'arguments': {4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSDocumentController', b'beginOpenPanelWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSDocumentController', b'closeAllDocumentsWithDelegate:didCloseAllSelector:contextInfo:', {'arguments': {3: {'sel_of_type': b'v@:@Z^v'}, 4: {'type': '^v'}}})
r(b'NSDocumentController', b'duplicateDocumentWithContentsOfURL:copying:displayName:error:', {'arguments': {3: {'type': b'Z'}, 5: {'type_modifier': b'o'}}})
r(b'NSDocumentController', b'hasEditedDocuments', {'retval': {'type': 'Z'}})
r(b'NSDocumentController', b'makeDocumentForURL:withContentsOfURL:ofType:error:', {'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSDocumentController', b'makeDocumentWithContentsOfURL:ofType:error:', {'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSDocumentController', b'makeUntitledDocumentOfType:error:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSDocumentController', b'openDocumentWithContentsOfFile:display:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSDocumentController', b'openDocumentWithContentsOfURL:display:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSDocumentController', b'openDocumentWithContentsOfURL:display:completionHandler:', {'arguments': {3: {'type': b'Z'}, 4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSDocumentController', b'openDocumentWithContentsOfURL:display:error:', {'arguments': {3: {'type': 'Z'}, 4: {'type_modifier': b'o'}}})
r(b'NSDocumentController', b'openUntitledDocumentAndDisplay:error:', {'arguments': {2: {'type': 'Z'}, 3: {'type_modifier': b'o'}}})
r(b'NSDocumentController', b'openUntitledDocumentOfType:display:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSDocumentController', b'presentError:', {'retval': {'type': 'Z'}})
r(b'NSDocumentController', b'presentError:modalForWindow:delegate:didPresentSelector:contextInfo:', {'arguments': {5: {'sel_of_type': b'v@:Z^v'}, 6: {'type': '^v'}}})
r(b'NSDocumentController', b'reopenDocumentForURL:withContentsOfURL:display:completionHandler:', {'arguments': {4: {'type': b'Z'}, 5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'Z'}, 3: {'type': b'@'}}}}}})
r(b'NSDocumentController', b'reopenDocumentForURL:withContentsOfURL:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSDocumentController', b'reviewUnsavedDocumentsWithAlertTitle:cancellable:delegate:didReviewAllSelector:contextInfo:', {'arguments': {3: {'type': 'Z'}, 5: {'sel_of_type': b'v@:@Z^v'}, 6: {'type': '^v'}}})
r(b'NSDocumentController', b'setAllowsAutomaticShareMenu:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDocumentController', b'setShouldCreateUI:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSDocumentController', b'shouldCreateUI', {'retval': {'type': 'Z'}})
r(b'NSDocumentController', b'typeForContentsOfURL:error:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSDocumentController', b'validateUserInterfaceItem:', {'retval': {'type': 'Z'}})
r(b'NSDraggingItem', b'imageComponentsProvider', {'retval': {'callable': {'retval': {'type': b'@'}, 'arguments': {0: {'type': b'^v'}}}}})
r(b'NSDraggingItem', b'setImageComponentsProvider:', {'arguments': {2: {'callable': {'retval': {'type': b'@'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSDraggingSession', b'animatesToStartingPositionsOnCancelOrFail', {'retval': {'type': b'Z'}})
r(b'NSDraggingSession', b'enumerateDraggingItemsWithOptions:forView:classes:searchOptions:usingBlock:', {'arguments': {6: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': sel32or64(b'i', b'q')}, 3: {'type': b'o^Z'}}}}}})
r(b'NSDraggingSession', b'setAnimatesToStartingPositionsOnCancelOrFail:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSDrawer', b'contentSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSDrawer', b'initWithContentSize:preferredEdge:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSDrawer', b'maxContentSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSDrawer', b'minContentSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSDrawer', b'setContentSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSDrawer', b'setMaxContentSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSDrawer', b'setMinContentSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSEPSImageRep', b'boundingBox', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSEvent', b'CGEvent', {'retval': {'type': '^{__CGEvent=}'}})
r(b'NSEvent', b'addGlobalMonitorForEventsMatchingMask:handler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSEvent', b'addLocalMonitorForEventsMatchingMask:handler:', {'arguments': {3: {'callable': {'retval': {'type': b'@'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSEvent', b'enterExitEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:trackingNumber:userData:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 10: {'type': '^v'}}})
r(b'NSEvent', b'eventRef', {'retval': {'type': 'r^{OpaqueEventRef=}'}})
r(b'NSEvent', b'eventWithCGEvent:', {'arguments': {2: {'type': '^{__CGEvent=}'}}})
r(b'NSEvent', b'eventWithEventRef:', {'arguments': {2: {'type': '^{OpaqueEventRef=}'}}})
r(b'NSEvent', b'hasPreciseScrollingDeltas', {'retval': {'type': b'Z'}})
r(b'NSEvent', b'isARepeat', {'retval': {'type': 'Z'}})
r(b'NSEvent', b'isDirectionInvertedFromDevice', {'retval': {'type': b'Z'}})
r(b'NSEvent', b'isEnteringProximity', {'retval': {'type': 'Z'}})
r(b'NSEvent', b'isMouseCoalescingEnabled', {'retval': {'type': 'Z'}})
r(b'NSEvent', b'isSwipeTrackingFromScrollEventsEnabled', {'retval': {'type': b'Z'}})
r(b'NSEvent', b'keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 10: {'type': 'Z'}}})
r(b'NSEvent', b'locationInWindow', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSEvent', b'mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSEvent', b'mouseLocation', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSEvent', b'otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSEvent', b'setMouseCoalescingEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSEvent', b'tilt', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSEvent', b'trackSwipeEventWithOptions:dampenAmountThresholdMin:max:usingHandler:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'f', b'd')}, 2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': b'Z'}, 4: {'type': b'o^Z'}}}}}})
r(b'NSEvent', b'userData', {'retval': {'type': '^v'}})
r(b'NSFilePromiseReceiver', b'receivePromisedFilesAtDestination:options:operationQueue:reader:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}}}})
r(b'NSFileWrapper', b'initWithURL:options:error:', {'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSFileWrapper', b'isDirectory', {'retval': {'type': 'Z'}})
r(b'NSFileWrapper', b'isRegularFile', {'retval': {'type': 'Z'}})
r(b'NSFileWrapper', b'isSymbolicLink', {'retval': {'type': 'Z'}})
r(b'NSFileWrapper', b'matchesContentsOfURL:', {'retval': {'type': 'Z'}})
r(b'NSFileWrapper', b'needsToBeUpdatedFromPath:', {'retval': {'type': 'Z'}})
r(b'NSFileWrapper', b'readFromURL:options:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSFileWrapper', b'updateFromPath:', {'retval': {'type': 'Z'}})
r(b'NSFileWrapper', b'writeToFile:atomically:updateFilenames:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': 'Z'}, 4: {'type': 'Z'}}})
r(b'NSFileWrapper', b'writeToURL:options:originalContentsURL:error:', {'retval': {'type': 'Z'}, 'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSFont', b'advancementForGlyph:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSFont', b'boundingRectForFont', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSFont', b'boundingRectForGlyph:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSFont', b'fontWithName:matrix:', {'arguments': {3: {'c_array_of_fixed_length': 6, 'type_modifier': b'n'}}})
r(b'NSFont', b'getAdvancements:forCGGlyphs:count:', {'arguments': {2: {'type_modifier': b'o', 'c_array_length_in_arg': 4}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}}})
r(b'NSFont', b'getAdvancements:forGlyphs:count:', {'arguments': {2: {'type_modifier': b'o', 'c_array_length_in_arg': 4}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}}})
r(b'NSFont', b'getAdvancements:forPackedGlyphs:length:', {'arguments': {2: {'type_modifier': b'o', 'c_array_length_in_arg': 4}, 3: {'c_array_delimited_by_null': True, 'type': '^t', 'type_modifier': b'n', 'c_array_length_in_arg': 4}}})
r(b'NSFont', b'getBoundingRects:forCGGlyphs:count:', {'arguments': {2: {'type_modifier': b'o', 'c_array_length_in_arg': 4}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}}})
r(b'NSFont', b'getBoundingRects:forGlyphs:count:', {'arguments': {2: {'type_modifier': b'o', 'c_array_length_in_arg': 4}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}}})
r(b'NSFont', b'glyphIsEncoded:', {'retval': {'type': 'Z'}})
r(b'NSFont', b'isBaseFont', {'retval': {'type': 'Z'}})
r(b'NSFont', b'isFixedPitch', {'retval': {'type': 'Z'}})
r(b'NSFont', b'isVertical', {'retval': {'type': b'Z'}})
r(b'NSFont', b'matrix', {'retval': {'c_array_of_fixed_length': 6}})
r(b'NSFont', b'maximumAdvancement', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSFont', b'positionOfGlyph:forCharacter:struckOverRect:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {3: {'type': 'S'}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSFont', b'positionOfGlyph:precededByGlyph:isNominal:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {4: {'type': '^Z', 'type_modifier': b'o'}}})
r(b'NSFont', b'positionOfGlyph:struckOverGlyph:metricsExist:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {4: {'type': '^Z', 'type_modifier': b'o'}}})
r(b'NSFont', b'positionOfGlyph:struckOverRect:metricsExist:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': '^Z', 'type_modifier': b'o'}}})
r(b'NSFont', b'positionOfGlyph:withRelation:toBaseGlyph:totalAdvancement:metricsExist:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {5: {'type_modifier': b'o'}, 6: {'type': '^Z', 'type_modifier': b'o'}}})
r(b'NSFont', b'positionsForCompositeSequence:numberOfGlyphs:pointArray:', {'arguments': {2: {'type_modifier': b'n', 'c_array_length_in_arg': 3}, 4: {'type_modifier': b'o', 'c_array_length_in_arg': 3}}})
r(b'NSFontAssetRequest', b'downloadFontAssetsWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'Z'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSFontCollection', b'hideFontCollectionWithName:visibility:error:', {'retval': {'type': b'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSFontCollection', b'renameFontCollectionWithName:visibility:toName:error:', {'retval': {'type': b'Z'}, 'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSFontCollection', b'showFontCollection:withName:visibility:error:', {'retval': {'type': b'Z'}, 'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSFontDescriptor', b'requiresFontAssetRequest', {'retval': {'type': 'Z'}})
r(b'NSFontDescriptor', b'setRequiresFontAssetRequest:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSFontManager', b'addCollection:options:', {'retval': {'type': 'Z'}})
r(b'NSFontManager', b'convertWeight:ofFont:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSFontManager', b'fontMenu:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSFontManager', b'fontNamed:hasTraits:', {'retval': {'type': 'Z'}})
r(b'NSFontManager', b'fontPanel:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSFontManager', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSFontManager', b'isMultiple', {'retval': {'type': 'Z'}})
r(b'NSFontManager', b'removeCollection:', {'retval': {'type': 'Z'}})
r(b'NSFontManager', b'sendAction', {'retval': {'type': 'Z'}})
r(b'NSFontManager', b'setAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSFontManager', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSFontManager', b'setSelectedAttributes:isMultiple:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSFontManager', b'setSelectedFont:isMultiple:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSFontPanel', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSFontPanel', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSFontPanel', b'setPanelFont:isMultiple:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSFontPanel', b'setWorksWhenModal:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSFontPanel', b'sharedFontPanelExists', {'retval': {'type': 'Z'}})
r(b'NSFontPanel', b'worksWhenModal', {'retval': {'type': 'Z'}})
r(b'NSForm', b'setBezeled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSForm', b'setBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSForm', b'setFrameSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSFormCell', b'isOpaque', {'retval': {'type': 'Z'}})
r(b'NSFormCell', b'titleWidth:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSGestureRecognizer', b'canBePreventedByGestureRecognizer:', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'canPreventGestureRecognizer:', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'delaysKeyEvents', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'delaysMagnificationEvents', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'delaysOtherMouseButtonEvents', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'delaysPrimaryMouseButtonEvents', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'delaysRotationEvents', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'delaysSecondaryMouseButtonEvents', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'initWithTarget:action:', {'arguments': {3: {'sel_of_type': b'v@:@'}}})
r(b'NSGestureRecognizer', b'isEnabled', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'setAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSGestureRecognizer', b'setDelaysKeyEvents:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSGestureRecognizer', b'setDelaysMagnificationEvents:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSGestureRecognizer', b'setDelaysOtherMouseButtonEvents:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSGestureRecognizer', b'setDelaysPrimaryMouseButtonEvents:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSGestureRecognizer', b'setDelaysRotationEvents:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSGestureRecognizer', b'setDelaysSecondaryMouseButtonEvents:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSGestureRecognizer', b'setEnabled:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSGestureRecognizer', b'shouldBeRequiredToFailByGestureRecognizer:', {'retval': {'type': b'Z'}})
r(b'NSGestureRecognizer', b'shouldRequireFailureOfGestureRecognizer:', {'retval': {'type': b'Z'}})
r(b'NSGlyphGenerator', b'generateGlyphsForGlyphStorage:desiredNumberOfCharacters:glyphIndex:characterIndex:', {'arguments': {4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}}})
r(b'NSGradient', b'drawFromCenter:radius:toCenter:radius:options:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'f', b'd')}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSGradient', b'drawFromPoint:toPoint:options:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSGradient', b'drawInBezierPath:relativeCenterPosition:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSGradient', b'drawInRect:angle:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSGradient', b'drawInRect:relativeCenterPosition:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSGradient', b'getColor:location:atIndex:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSGradient', b'initWithColors:atLocations:colorSpace:', {'arguments': {3: {'type_modifier': b'n', 'c_array_length_in_arg': 2}}})
r(b'NSGradient', b'initWithColorsAndLocations:', {'suggestion': 'use initWithColors:atLocation:colorSpace:', 'variadic': True})
r(b'NSGraphicsContext', b'currentContextDrawingToScreen', {'retval': {'type': 'Z'}})
r(b'NSGraphicsContext', b'focusStack', {'retval': {'type': '^v'}})
r(b'NSGraphicsContext', b'graphicsContextWithCGContext:flipped:', {'arguments': {3: {'type': b'Z'}}})
r(b'NSGraphicsContext', b'graphicsContextWithGraphicsPort:flipped:', {'arguments': {2: {'type': '^{CGContext=}'}, 3: {'type': 'Z'}}})
r(b'NSGraphicsContext', b'graphicsPort', {'retval': {'type': '^{CGContext=}'}})
r(b'NSGraphicsContext', b'isDrawingToScreen', {'retval': {'type': 'Z'}})
r(b'NSGraphicsContext', b'isFlipped', {'retval': {'type': 'Z'}})
r(b'NSGraphicsContext', b'patternPhase', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSGraphicsContext', b'setFocusStack:', {'arguments': {2: {'type': '^v'}}})
r(b'NSGraphicsContext', b'setPatternPhase:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSGraphicsContext', b'setShouldAntialias:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSGraphicsContext', b'shouldAntialias', {'retval': {'type': 'Z'}})
r(b'NSGridColumn', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSGridColumn', b'setHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSGridRow', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSGridRow', b'setHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSGridView', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSGridView', b'setHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSGroupTouchBarItem', b'prefersEqualWidths', {'retval': {'type': 'Z'}})
r(b'NSGroupTouchBarItem', b'setPrefersEqualWidths:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSHelpManager', b'isContextHelpModeActive', {'retval': {'type': 'Z'}})
r(b'NSHelpManager', b'registerBooksInBundle:', {'retval': {'type': b'Z'}})
r(b'NSHelpManager', b'setContextHelpModeActive:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSHelpManager', b'showContextHelpForObject:locationHint:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSImage', b'CGImageForProposedRect:context:hints:', {'arguments': {2: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'o'}}})
r(b'NSImage', b'alignmentRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSImage', b'bestRepresentationForRect:context:hints:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'cacheDepthMatchesImageDepth', {'retval': {'type': 'Z'}})
r(b'NSImage', b'canInitWithPasteboard:', {'retval': {'type': 'Z'}})
r(b'NSImage', b'compositeToPoint:fromRect:operation:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'compositeToPoint:fromRect:operation:fraction:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'compositeToPoint:operation:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSImage', b'compositeToPoint:operation:fraction:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSImage', b'dissolveToPoint:fraction:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSImage', b'dissolveToPoint:fromRect:fraction:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'drawAtPoint:fromRect:operation:fraction:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'drawInRect:fromRect:operation:fraction:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'drawInRect:fromRect:operation:fraction:respectFlipped:hints:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 6: {'type': 'Z'}}})
r(b'NSImage', b'drawRepresentation:inRect:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'hitTestRect:withImageDestinationRect:context:hints:flipped:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 6: {'type': 'Z'}}})
r(b'NSImage', b'hitTestRect:withImageDestinationRect:context_hints:flipped:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'imageWithSize:flipped:drawingHandler:', {'arguments': {3: {'type': b'Z'}, 4: {'callable': {'retval': {'type': b'Z'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}}}}})
r(b'NSImage', b'initWithCGImage:size:', {'arguments': {3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSImage', b'initWithIconRef:', {'arguments': {2: {'type': '^{OpaqueIconRef=}'}}})
r(b'NSImage', b'initWithSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSImage', b'isCachedSeparately', {'retval': {'type': 'Z'}})
r(b'NSImage', b'isDataRetained', {'retval': {'type': 'Z'}})
r(b'NSImage', b'isFlipped', {'retval': {'type': 'Z'}})
r(b'NSImage', b'isTemplate', {'retval': {'type': 'Z'}})
r(b'NSImage', b'isValid', {'retval': {'type': 'Z'}})
r(b'NSImage', b'lockFocusFlipped:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'matchesOnMultipleResolution', {'retval': {'type': 'Z'}})
r(b'NSImage', b'matchesOnlyOnBestFittingAxis', {'retval': {'type': b'Z'}})
r(b'NSImage', b'prefersColorMatch', {'retval': {'type': 'Z'}})
r(b'NSImage', b'scalesWhenResized', {'retval': {'type': 'Z'}})
r(b'NSImage', b'setAlignmentRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImage', b'setCacheDepthMatchesImageDepth:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'setCachedSeparately:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'setDataRetained:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'setFlipped:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'setMatchesOnMultipleResolution:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'setMatchesOnlyOnBestFittingAxis:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSImage', b'setName:', {'retval': {'type': 'Z'}})
r(b'NSImage', b'setPrefersColorMatch:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'setScalesWhenResized:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'setSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSImage', b'setTemplate:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'setUsesEPSOnResolutionMismatch:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImage', b'size', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSImage', b'usesEPSOnResolutionMismatch', {'retval': {'type': 'Z'}})
r(b'NSImageRep', b'CGImageForProposedRect:context:hints:', {'arguments': {2: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}}})
r(b'NSImageRep', b'canInitWithData:', {'retval': {'type': 'Z'}})
r(b'NSImageRep', b'canInitWithPasteboard:', {'retval': {'type': 'Z'}})
r(b'NSImageRep', b'draw', {'retval': {'type': 'Z'}})
r(b'NSImageRep', b'drawAtPoint:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSImageRep', b'drawInRect:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSImageRep', b'drawInRect:fromRect:operation:fraction:respectFlipped:hints:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 6: {'type': 'Z'}}})
r(b'NSImageRep', b'hasAlpha', {'retval': {'type': 'Z'}})
r(b'NSImageRep', b'isOpaque', {'retval': {'type': 'Z'}})
r(b'NSImageRep', b'setAlpha:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImageRep', b'setOpaque:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImageRep', b'setSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSImageRep', b'size', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSImageView', b'allowsCutCopyPaste', {'retval': {'type': 'Z'}})
r(b'NSImageView', b'animates', {'retval': {'type': 'Z'}})
r(b'NSImageView', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSImageView', b'setAllowsCutCopyPaste:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImageView', b'setAnimates:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSImageView', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSInputManager', b'handleMouseEvent:', {'retval': {'type': 'Z'}})
r(b'NSInputManager', b'markedTextSelectionChanged:client:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSInputManager', b'wantsToDelayTextChangeNotifications', {'retval': {'type': 'Z'}})
r(b'NSInputManager', b'wantsToHandleMouseEvents', {'retval': {'type': 'Z'}})
r(b'NSInputManager', b'wantsToInterpretAllKeystrokes', {'retval': {'type': 'Z'}})
r(b'NSItemProvider', b'loadItemForTypeIdentifier:options:completionHandler:', {'arguments': {4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}}}})
r(b'NSItemProvider', b'loadObjectOfClass:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}}}})
r(b'NSItemProvider', b'registerItemForTypeIdentifier:loadHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'callable': {'args': {0: {'type': '^@'}, 1: {'type': '@'}, 2: {'type': '@'}}, 'retval': {'type': 'v'}}, 'type': b'@?'}, 2: {'type': b'#'}, 3: {'type': b'@'}}}}}})
r(b'NSLayoutConstraint', b'isActive', {'retval': {'type': b'Z'}})
r(b'NSLayoutConstraint', b'setActive:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSLayoutConstraint', b'setShouldBeArchived:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSLayoutConstraint', b'shouldBeArchived', {'retval': {'type': b'Z'}})
r(b'NSLayoutGuide', b'hasAmbiguousLayout', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'CGGlyphAtIndex:isValidIndex:', {'arguments': {3: {'type': '^Z', 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'addTemporaryAttribute:value:forCharacterRange:', {'arguments': {4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'addTemporaryAttributes:forCharacterRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'allowsNonContiguousLayout', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'attachmentSizeForGlyphAtIndex:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSLayoutManager', b'backgroundLayoutEnabled', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'boundingRectForGlyphRange:inTextContainer:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'boundsRectForTextBlock:atIndex:effectiveRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'boundsRectForTextBlock:glyphRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'characterIndexForPoint:inTextContainer:fractionOfDistanceBetweenInsertionPoints:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'characterRangeForGlyphRange:actualGlyphRange:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'deleteGlyphsInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'drawBackgroundForGlyphRange:atPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSLayoutManager', b'drawGlyphsForGlyphRange:atPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSLayoutManager', b'drawStrikethroughForGlyphRange:strikethroughType:baselineOffset:lineFragmentRect:lineFragmentGlyphRange:containerOrigin:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 6: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 7: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSLayoutManager', b'drawUnderlineForGlyphRange:underlineType:baselineOffset:lineFragmentRect:lineFragmentGlyphRange:containerOrigin:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 6: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 7: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSLayoutManager', b'drawsOutsideLineFragmentForGlyphAtIndex:', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'ensureGlyphsForCharacterRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'ensureGlyphsForGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'ensureLayoutForBoundingRect:inTextContainer:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSLayoutManager', b'ensureLayoutForCharacterRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'ensureLayoutForGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'enumerateEnclosingRectsForGlyphRange:withinSelectedGlyphRange:inTextContainer:usingBlock:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 2: {'type': b'o^Z'}}}}}})
r(b'NSLayoutManager', b'enumerateLineFragmentsForGlyphRange:usingBlock:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': b'o^Z'}}}}}})
r(b'NSLayoutManager', b'extraLineFragmentRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSLayoutManager', b'extraLineFragmentUsedRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSLayoutManager', b'fillBackgroundRectArray:count:forCharacterRange:color:', {'arguments': {2: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N', 'c_array_length_in_arg': 3}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'fractionOfDistanceThroughGlyphForPoint:inTextContainer:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSLayoutManager', b'getFirstUnlaidCharacterIndex:glyphIndex:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'getGlyphs:range:', {'arguments': {2: {'type_modifier': b'o', 'c_array_length_in_arg': 3}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'getGlyphsInRange:glyphs:characterIndexes:glyphInscriptions:elasticBits:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 4: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 5: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 6: {'type': '^Z', 'type_modifier': b'o', 'c_array_length_in_arg': 2}}})
r(b'NSLayoutManager', b'getGlyphsInRange:glyphs:characterIndexes:glyphInscriptions:elasticBits:bidiLevels:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 4: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 5: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 6: {'type': '^Z', 'type_modifier': b'o', 'c_array_length_in_arg': 2}, 7: {'type': '^C', 'type_modifier': b'o', 'c_array_length_in_arg': 2}}})
r(b'NSLayoutManager', b'getGlyphsInRange:glyphs:properties:characterIndexes:bidiLevels:', {'arguments': {3: {'type': '^I', 'type_modifier': b'o', 'c_array_length_in_arg': 2}, 4: {'type': '^I', 'type_modifier': b'o', 'c_array_length_in_arg': 2}, 5: {'type': '^I', 'type_modifier': b'o', 'c_array_length_in_arg': 2}, 6: {'type': '^I', 'type_modifier': b'o', 'c_array_length_in_arg': 2}}})
r(b'NSLayoutManager', b'getLineFragmentInsertionPointsForCharacterAtIndex:alternatePositions:inDisplayOrder:positions:characterIndexes:', {'arguments': {3: {'type': 'Z'}, 4: {'type': 'Z'}, 5: {'type': sel32or64(b'r^f', b'r^d'), 'type_modifier': b'o'}, 6: {'type': sel32or64(b'^I', b'^Q'), 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'glyphAtIndex:isValidIndex:', {'arguments': {3: {'type': '^Z', 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'glyphIndexForPoint:inTextContainer:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSLayoutManager', b'glyphIndexForPoint:inTextContainer:fractionOfDistanceThroughGlyph:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'null_accepted': False, 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'glyphRangeForBoundingRect:inTextContainer:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSLayoutManager', b'glyphRangeForBoundingRectWithoutAdditionalLayout:inTextContainer:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSLayoutManager', b'glyphRangeForCharacterRange:actualCharacterRange:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'glyphRangeForTextContainer:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSLayoutManager', b'hasNonContiguousLayout', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'insertGlyphs:length:forStartingGlyphAtIndex:characterIndex:', {'arguments': {2: {'type': '^I', 'type_modifier': b'n', 'c_array_length_in_arg': 3}}})
r(b'NSLayoutManager', b'invalidateDisplayForCharacterRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'invalidateDisplayForGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'invalidateGlyphsForCharacterRange:changeInLength:actualCharacterRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'invalidateGlyphsOnLayoutInvalidationForGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'invalidateLayoutForCharacterRange:actualCharacterRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'invalidateLayoutForCharacterRange:isSoft:actualCharacterRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': 'Z'}, 4: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'isValidGlyphIndex:', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'layoutManagerOwnsFirstResponderInWindow:', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'layoutRectForTextBlock:atIndex:effectiveRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {4: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'layoutRectForTextBlock:glyphRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'lineFragmentRectForGlyphAtIndex:effectiveRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'lineFragmentRectForGlyphAtIndex:effectiveRange:withoutAdditionalLayout:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type_modifier': b'o'}, 4: {'type': 'Z'}}})
r(b'NSLayoutManager', b'lineFragmentUsedRectForGlyphAtIndex:effectiveRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'lineFragmentUsedRectForGlyphAtIndex:effectiveRange:withoutAdditionalLayout:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type_modifier': b'o'}, 4: {'type': 'Z'}}})
r(b'NSLayoutManager', b'locationForGlyphAtIndex:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSLayoutManager', b'notShownAttributeForGlyphAtIndex:', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'rangeOfNominallySpacedGlyphsContainingIndex:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSLayoutManager', b'rectArrayForCharacterRange:withinSelectedCharacterRange:inTextContainer:rectCount:', {'retval': {'c_array_length_in_arg': 5}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'rectArrayForGlyphRange:withinSelectedGlyphRange:inTextContainer:rectCount:', {'retval': {'c_array_length_in_arg': 5}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'removeTemporaryAttribute:forCharacterRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'rulerAccessoryViewForTextView:paragraphStyle:ruler:enabled:', {'arguments': {5: {'type': 'Z'}}})
r(b'NSLayoutManager', b'setAllowsNonContiguousLayout:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLayoutManager', b'setAttachmentSize:forGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'setBackgroundLayoutEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLayoutManager', b'setBoundsRect:forTextBlock:glyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'setDrawsOutsideLineFragment:forGlyphAtIndex:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLayoutManager', b'setExtraLineFragmentRect:usedRect:textContainer:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSLayoutManager', b'setGlyphs:properties:characterIndexes:font:forGlyphRange:', {'arguments': {2: {'type_modifier': b'n', 'c_array_length_in_arg': 6}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 6}, 4: {'type_modifier': b'n', 'c_array_length_in_arg': 6}}})
r(b'NSLayoutManager', b'setLayoutRect:forTextBlock:glyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'setLineFragmentRect:forGlyphRange:usedRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSLayoutManager', b'setLocation:forStartOfGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'setLocations:startingGlyphIndexes:count:forGlyphRange:', {'arguments': {2: {'type_modifier': b'n', 'c_array_length_in_arg': 4}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}, 5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'setNotShownAttribute:forGlyphAtIndex:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLayoutManager', b'setShowsControlCharacters:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLayoutManager', b'setShowsInvisibleCharacters:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLayoutManager', b'setTemporaryAttributes:forCharacterRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'setTextContainer:forGlyphRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'setUsesFontLeading:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLayoutManager', b'setUsesScreenFonts:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLayoutManager', b'showAttachmentCell:inRect:characterIndex:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSLayoutManager', b'showCGGlyphs:positions:count:font:matrix:attributes:inContext:', {'arguments': {2: {'type_modifier': b'n', 'c_array_length_in_arg': 4}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}}})
r(b'NSLayoutManager', b'showPackedGlyphs:length:glyphRange:atPoint:font:color:printingAdjustment:', {'arguments': {2: {'c_array_delimited_by_null': True, 'type': '^v', 'type_modifier': b'n', 'c_array_length_in_arg': 3}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 8: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSLayoutManager', b'showsControlCharacters', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'showsInvisibleCharacters', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'strikethroughGlyphRange:strikethroughType:lineFragmentRect:lineFragmentGlyphRange:containerOrigin:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 6: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSLayoutManager', b'temporaryAttribute:atCharacterIndex:effectiveRange:', {'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'temporaryAttribute:atCharacterIndex:longestEffectiveRange:inRange:', {'arguments': {4: {'type_modifier': b'o'}, 5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'temporaryAttributesAtCharacterIndex:effectiveRange:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'temporaryAttributesAtCharacterIndex:longestEffectiveRange:inRange:', {'arguments': {3: {'type_modifier': b'o'}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'textContainerForGlyphAtIndex:effectiveRange:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSLayoutManager', b'textContainerForGlyphAtIndex:effectiveRange:withoutAdditionalLayout:', {'arguments': {3: {'type_modifier': b'o'}, 4: {'type': 'Z'}}})
r(b'NSLayoutManager', b'textStorage:edited:range:changeInLength:invalidatedRange:', {'arguments': {3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 6: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSLayoutManager', b'underlineGlyphRange:underlineType:lineFragmentRect:lineFragmentGlyphRange:containerOrigin:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 6: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSLayoutManager', b'usedRectForTextContainer:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSLayoutManager', b'usesFontLeading', {'retval': {'type': 'Z'}})
r(b'NSLayoutManager', b'usesScreenFonts', {'retval': {'type': 'Z'}})
r(b'NSLevelIndicator', b'drawsTieredCapacityLevels', {'retval': {'type': 'Z'}})
r(b'NSLevelIndicator', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSLevelIndicator', b'rectOfTickMarkAtIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSLevelIndicator', b'setDrawsTieredCapacityLevels:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLevelIndicator', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSLevelIndicatorCell', b'rectOfTickMarkAtIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSMatrix', b'acceptsFirstMouse:', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'allowsEmptySelection', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'autorecalculatesCellSize', {'retval': {'type': b'Z'}})
r(b'NSMatrix', b'autosizesCells', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'cellFrameAtRow:column:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSMatrix', b'cellSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSMatrix', b'context:', {'arguments': {2: {'type': '^v'}}})
r(b'NSMatrix', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'drawsCellBackground', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'getNumberOfRows:columns:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSMatrix', b'getRow:column:forPoint:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSMatrix', b'getRow:column:ofCell:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}}})
r(b'NSMatrix', b'highlightCell:atRow:column:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'initWithFrame:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMatrix', b'initWithFrame:mode:cellClass:numberOfRows:numberOfColumns:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMatrix', b'initWithFrame:mode:prototype:numberOfRows:numberOfColumns:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMatrix', b'intercellSpacing', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSMatrix', b'isAutoscroll', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'isSelectionByRect', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'performKeyEquivalent:', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'selectCellWithTag:', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'sendAction', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'sendAction:to:forAllCells:', {'arguments': {2: {'sel_of_type': b'Z@:@'}, 4: {'type': 'Z'}}})
r(b'NSMatrix', b'setAllowsEmptySelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'setAutorecalculatesCellSize:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSMatrix', b'setAutoscroll:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'setAutosizesCells:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'setCellSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSMatrix', b'setDoubleAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSMatrix', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'setDrawsCellBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'setIntercellSpacing:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSMatrix', b'setScrollable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'setSelectionByRect:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'setSelectionFrom:to:anchor:highlight:', {'arguments': {5: {'type': 'Z'}}})
r(b'NSMatrix', b'setTabKeyTraversesCells:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'setValidateSize:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMatrix', b'sortUsingFunction:context:', {'arguments': {2: {'callable': {'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {0: {'type': b'@'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}, 'callable_retained': False}, 3: {'type': '@'}}})
r(b'NSMatrix', b'sortUsingSelector:', {'arguments': {2: {'sel_of_type': sel32or64(b'i@:@', b'q@:@')}}})
r(b'NSMatrix', b'tabKeyTraversesCells', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'textShouldBeginEditing:', {'retval': {'type': 'Z'}})
r(b'NSMatrix', b'textShouldEndEditing:', {'retval': {'type': 'Z'}})
r(b'NSMediaLibraryBrowserController', b'isVisible', {'retval': {'type': b'Z'}})
r(b'NSMediaLibraryBrowserController', b'setVisible:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSMenu', b'addItemWithTitle:action:keyEquivalent:', {'arguments': {3: {'sel_of_type': b'v@:@'}}})
r(b'NSMenu', b'allowsContextMenuPlugIns', {'retval': {'type': 'Z'}})
r(b'NSMenu', b'autoenablesItems', {'retval': {'type': 'Z'}})
r(b'NSMenu', b'indexOfItemWithTarget:andAction:', {'arguments': {3: {'sel_of_type': b'v@:@'}}})
r(b'NSMenu', b'insertItemWithTitle:action:keyEquivalent:atIndex:', {'arguments': {3: {'sel_of_type': b'v@:@'}}})
r(b'NSMenu', b'isAttached', {'retval': {'type': 'Z'}})
r(b'NSMenu', b'isTornOff', {'retval': {'type': 'Z'}})
r(b'NSMenu', b'locationForSubmenu:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSMenu', b'menuBarVisible', {'retval': {'type': 'Z'}})
r(b'NSMenu', b'menuChangedMessagesEnabled', {'retval': {'type': 'Z'}})
r(b'NSMenu', b'menuZone', {'retval': {'type': '^{_NSZone=}'}})
r(b'NSMenu', b'performKeyEquivalent:', {'retval': {'type': 'Z'}})
r(b'NSMenu', b'popUpMenuPositioningItem:atLocation:inView:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSMenu', b'setAllowsContextMenuPlugIns:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenu', b'setAutoenablesItems:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenu', b'setMenuBarVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenu', b'setMenuChangedMessagesEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenu', b'setMenuZone:', {'arguments': {2: {'type': '^{_NSZone=}'}}})
r(b'NSMenu', b'setShowsStateColumn:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenu', b'showsStateColumn', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'allowsKeyEquivalentWhenHidden', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'hasSubmenu', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'initWithTitle:action:keyEquivalent:', {'arguments': {3: {'sel_of_type': b'v@:@'}}})
r(b'NSMenuItem', b'isAlternate', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'isHiddenOrHasHiddenAncestor', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'isHighlighted', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'isSeparatorItem', {'retval': {'type': 'Z'}})
r(b'NSMenuItem', b'setAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSMenuItem', b'setAllowsKeyEquivalentWhenHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuItem', b'setAlternate:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuItem', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuItem', b'setHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuItem', b'setUsesUserKeyEquivalents:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuItem', b'usesUserKeyEquivalents', {'retval': {'type': 'Z'}})
r(b'NSMenuItemCell', b'drawBorderAndBackgroundWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuItemCell', b'drawImageWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuItemCell', b'drawKeyEquivalentWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuItemCell', b'drawSeparatorItemWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuItemCell', b'drawStateImageWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuItemCell', b'drawTitleWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuItemCell', b'keyEquivalentRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuItemCell', b'keyEquivalentWidth', {'retval': {'type': sel32or64(b'f', b'd')}})
r(b'NSMenuItemCell', b'needsDisplay', {'retval': {'type': 'Z'}})
r(b'NSMenuItemCell', b'needsSizing', {'retval': {'type': 'Z'}})
r(b'NSMenuItemCell', b'setNeedsDisplay:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuItemCell', b'setNeedsSizing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuItemCell', b'stateImageRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuItemCell', b'titleRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuView', b'indexOfItemAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSMenuView', b'initWithFrame:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuView', b'innerRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSMenuView', b'isAttached', {'retval': {'type': 'Z'}})
r(b'NSMenuView', b'isHorizontal', {'retval': {'type': 'Z'}})
r(b'NSMenuView', b'isTornOff', {'retval': {'type': 'Z'}})
r(b'NSMenuView', b'locationForSubmenu:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSMenuView', b'needsSizing', {'retval': {'type': 'Z'}})
r(b'NSMenuView', b'rectOfItemAtIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSMenuView', b'setHorizontal:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuView', b'setNeedsSizing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMenuView', b'setWindowFrameForAttachingToRect:onScreen:preferredEdge:popUpSelectedItem:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSMenuView', b'trackWithEvent:', {'retval': {'type': 'Z'}})
r(b'NSMovie', b'QTMovie', {'retval': {'type': '^^{MovieType}'}})
r(b'NSMovie', b'canInitWithPasteboard:', {'retval': {'type': 'Z'}})
r(b'NSMovie', b'initWithMovie:', {'arguments': {2: {'type': '^^{MovieType}'}}})
r(b'NSMovie', b'initWithURL:byReference:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSMovieView', b'isControllerVisible', {'retval': {'type': 'Z'}})
r(b'NSMovieView', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSMovieView', b'isMuted', {'retval': {'type': 'Z'}})
r(b'NSMovieView', b'isPlaying', {'retval': {'type': 'Z'}})
r(b'NSMovieView', b'movieController', {'retval': {'type': '^{ComponentInstanceRecord=[1l]}'}})
r(b'NSMovieView', b'movieRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSMovieView', b'playsEveryFrame', {'retval': {'type': 'Z'}})
r(b'NSMovieView', b'playsSelectionOnly', {'retval': {'type': 'Z'}})
r(b'NSMovieView', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMovieView', b'setMuted:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMovieView', b'setPlaysEveryFrame:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMovieView', b'setPlaysSelectionOnly:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSMovieView', b'showController:adjustingSize:', {'arguments': {2: {'type': 'Z'}, 3: {'type': 'Z'}}})
r(b'NSMovieView', b'sizeForMagnification:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSMutableAttributedString', b'applyFontTraits:range:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'fixAttachmentAttributeInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'fixAttributesInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'fixFontAttributeInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'fixParagraphStyleAttributeInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'readFromData:options:documentAttributes:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSMutableAttributedString', b'readFromData:options:documentAttributes:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}}})
r(b'NSMutableAttributedString', b'readFromURL:options:documentAttributes:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSMutableAttributedString', b'readFromURL:options:documentAttributes:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}}})
r(b'NSMutableAttributedString', b'setAlignment:range:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'setBaseWritingDirection:range:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'subscriptRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'superscriptRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableAttributedString', b'unscriptRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSMutableParagraphStyle', b'setAllowsDefaultTighteningForTruncation:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSNib', b'instantiateNibWithExternalNameTable:', {'retval': {'type': 'Z'}})
r(b'NSNib', b'instantiateNibWithOwner:topLevelObjects:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSNib', b'instantiateWithOwner:topLevelObjects:', {'retval': {'type': b'Z'}, 'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSObject', b'accessibilityActionDescription:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'accessibilityActionNames', {'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityActivationPoint', {'required': True, 'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSObject', b'accessibilityAllowedValues', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityApplicationFocusedUIElement', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityArrayAttributeCount:', {'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'accessibilityArrayAttributeValues:index:maxCount:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'accessibilityAttributeNames', {'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityAttributeValue:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'accessibilityAttributeValue:forParameter:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'accessibilityAttributedStringForRange:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'accessibilityCancelButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityCellForColumn:row:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'accessibilityChildren', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityClearButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityCloseButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityColumnCount', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityColumnHeaderUIElements', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityColumnIndexRange', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSObject', b'accessibilityColumnTitles', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityColumns', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityContents', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityCriticalValue', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityDecrementButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityDefaultButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityDisclosedByRow', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityDisclosedRows', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityDisclosureLevel', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityDocument', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityExtrasMenuBar', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityFilename', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityFocusedUIElement', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityFocusedWindow', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityFrame', {'required': True, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSObject', b'accessibilityFrameForRange:', {'required': True, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'accessibilityFullScreenButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityGrowArea', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityHandles', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityHeader', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityHeaderGroup', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityHelp', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityHitTest:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'accessibilityHorizontalScrollBar', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityHorizontalUnitDescription', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityHorizontalUnits', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityIdentifier', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityIncrementButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityIndex', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityIndexOfChild:', {'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'accessibilityInsertionPointLineNumber', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityIsAttributeSettable:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'accessibilityIsIgnored', {'retval': {'type': 'Z'}})
r(b'NSObject', b'accessibilityLabel', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityLabelUIElements', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityLabelValue', {'required': True, 'retval': {'type': b'f'}})
r(b'NSObject', b'accessibilityLayoutPointForScreenPoint:', {'required': True, 'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'accessibilityLayoutSizeForScreenSize:', {'required': True, 'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSObject', b'accessibilityLineForIndex:', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'accessibilityLinkedUIElements', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMainWindow', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMarkerGroupUIElement', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMarkerTypeDescription', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMarkerUIElements', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMarkerValues', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMaxValue', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMenuBar', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMinValue', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityMinimizeButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityNextContents', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityNotifiesWhenDestroyed', {'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityNumberOfCharacters', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityOrientation', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityOverflowButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityParameterizedAttributeNames', {'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityParent', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityPerformAction:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'accessibilityPerformCancel', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformConfirm', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformDecrement', {'required': False, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformDelete', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformIncrement', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformPick', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformPress', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformRaise', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformShowAlternateUI', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformShowDefaultUI', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPerformShowMenu', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'accessibilityPlaceholderValue', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityPreviousContents', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityProxy', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityRTFForRange:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'accessibilityRangeForIndex:', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'accessibilityRangeForLine:', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'accessibilityRangeForPosition:', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'accessibilityRole', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityRoleDescription', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityRowCount', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityRowHeaderUIElements', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityRowIndexRange', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSObject', b'accessibilityRows', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityRulerMarkerType', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityScreenPointForLayoutPoint:', {'required': True, 'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'accessibilityScreenSizeForLayoutSize:', {'required': True, 'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSObject', b'accessibilitySearchButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySearchMenu', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySelectedCells', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySelectedChildren', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySelectedColumns', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySelectedRows', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySelectedText', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySelectedTextRange', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSObject', b'accessibilitySelectedTextRanges', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityServesAsTitleForUIElements', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySetOverrideValue:forAttribute:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'accessibilitySetValue:forAttribute:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'accessibilitySharedCharacterRange', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSObject', b'accessibilitySharedFocusElements', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySharedTextUIElements', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityShownMenu', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilitySortDirection', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilitySplitters', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityStringForRange:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'accessibilityStyleRangeForIndex:', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'accessibilitySubrole', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityTabs', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityTitle', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityTitleUIElement', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityToolbarButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityTopLevelUIElement', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityURL', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityUnitDescription', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityUnits', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityValue', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityValueDescription', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityVerticalScrollBar', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityVerticalUnitDescription', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityVerticalUnits', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'accessibilityVisibleCells', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityVisibleCharacterRange', {'required': False, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSObject', b'accessibilityVisibleChildren', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityVisibleColumns', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityVisibleRows', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityWarningValue', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityWindow', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityWindows', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'accessibilityZoomButton', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'action', {'required': True, 'retval': {'type': ':'}})
r(b'NSObject', b'activeConversationChanged:toNewConversation:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'activeConversationWillChange:fromOldConversation:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'alertShowHelp:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'allowsMultipleSelection', {'required': False, 'retval': {'type': b'Z'}})
r(b'NSObject', b'alphaControlAddedOrRemoved:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'animateDismissalOfViewController:fromViewController:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'animatePresentationOfViewController:fromViewController:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'animatesToDestination', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'animation:didReachProgressMark:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': 'f'}}})
r(b'NSObject', b'animation:valueForProgress:', {'required': False, 'retval': {'type': 'f'}, 'arguments': {2: {'type': b'@'}, 3: {'type': 'f'}}})
r(b'NSObject', b'animationDidEnd:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'animationDidStop:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'animationForKey:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'animationShouldStart:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'animations', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'animator', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'appearance', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'application:continueUserActivity:restorationHandler:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}, 'type': b'@?'}}})
r(b'NSObject', b'application:delegateHandlesKey:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:didDecodeRestorableState:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:didFailToContinueUserActivityWithType:error:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'application:didFailToRegisterForRemoteNotificationsWithError:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:didReceiveRemoteNotification:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:didRegisterForRemoteNotificationsWithDeviceToken:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:didUpdateUserActivity:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:openFile:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:openFileWithoutUI:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:openFiles:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:openTempFile:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:printFile:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:printFiles:', {'retval': {'type': 'v'}})
r(b'NSObject', b'application:printFiles:withSettings:showPrintPanels:', {'required': False, 'retval': {'type': 'I'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': 'Z'}}})
r(b'NSObject', b'application:willContinueUserActivityWithType:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:willEncodeRestorableState:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'application:willPresentError:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'applicationDidBecomeActive:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationDidChangeOcclusionState:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationDidChangeScreenParameters:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationDidFinishLaunching:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationDidHide:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationDidResignActive:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationDidUnhide:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationDidUpdate:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationDockMenu:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationOpenUntitledFile:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationShouldHandleReopen:hasVisibleWindows:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': 'Z'}}})
r(b'NSObject', b'applicationShouldOpenUntitledFile:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationShouldTerminate:', {'required': False, 'retval': {'type': 'I'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationShouldTerminateAfterLastWindowClosed:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationWillBecomeActive:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationWillFinishLaunching:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationWillHide:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationWillResignActive:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationWillTerminate:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationWillUnhide:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'applicationWillUpdate:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'attachColorList:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'attachment', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'attributedString', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'attributedSubstringForProposedRange:actualRange:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSObject', b'attributedSubstringFromRange:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'awakeFromNib', {'retval': {'type': b'v'}})
r(b'NSObject', b'baselineDeltaForCharacterAtIndex:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'bind:toObject:withKeyPath:options:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}}})
r(b'NSObject', b'browser:acceptDrop:atRow:column:dropOperation:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': sel32or64(b'i', b'q')}, 6: {'type': 'I'}}})
r(b'NSObject', b'browser:canDragRowsWithIndexes:inColumn:withEvent:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': b'@'}}})
r(b'NSObject', b'browser:child:ofItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': b'@'}}})
r(b'NSObject', b'browser:createRowsForColumn:inMatrix:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': b'@'}}})
r(b'NSObject', b'browser:didChangeLastColumn:toColumn:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:draggingImageForRowsWithIndexes:inColumn:withEvent:offset:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': b'@'}, 6: {'type': sel32or64(b'N^{_NSPoint=ff}', b'N^{CGPoint=dd}')}}})
r(b'NSObject', b'browser:headerViewControllerForItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'browser:heightOfRow:inColumn:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:isColumnValid:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:isLeafItem:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'browser:namesOfPromisedFilesDroppedAtDestination:forDraggedRowsWithIndexes:inColumn:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:nextTypeSelectMatchFromRow:toRow:inColumn:forString:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': sel32or64(b'i', b'q')}, 6: {'type': b'@'}}})
r(b'NSObject', b'browser:numberOfChildrenOfItem:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'browser:numberOfRowsInColumn:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:objectValueForItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'browser:previewViewControllerForLeafItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'browser:selectCellWithString:inColumn:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:selectRow:inColumn:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:selectionIndexesForProposedSelection:inColumn:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:setObjectValue:forItem:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'browser:shouldEditItem:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'browser:shouldShowCellExpansionForRow:column:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:shouldSizeColumn:forUserResize:toWidth:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': 'Z'}, 5: {'type': sel32or64(b'f', b'd')}}})
r(b'NSObject', b'browser:shouldTypeSelectForEvent:withCurrentSearchString:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'browser:sizeToFitWidthOfColumn:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:titleOfColumn:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:typeSelectStringForRow:inColumn:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:validateDrop:proposedRow:column:dropOperation:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'N'}, 5: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'N'}, 6: {'type': sel32or64(b'^I', b'^Q'), 'type_modifier': b'N'}}})
r(b'NSObject', b'browser:willDisplayCell:atRow:column:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'browser:writeRowsWithIndexes:inColumn:toPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': b'@'}}})
r(b'NSObject', b'browserColumnConfigurationDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'browserDidScroll:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'browserWillScroll:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'buttonToolTip', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'canBeDisabled', {'required': True, 'retval': {'type': 'Z'}})
r(b'NSObject', b'candidateListTouchBarItem:beginSelectingCandidateAtIndex:', {'arguments': {3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'candidateListTouchBarItem:changeSelectionFromCandidateAtIndex:toIndex:', {'arguments': {3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'candidateListTouchBarItem:changedCandidateListVisibility:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSObject', b'candidateListTouchBarItem:endSelectingCandidateAtIndex:', {'arguments': {3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'cellBaselineOffset', {'required': True, 'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSObject', b'cellFrameForTextContainer:proposedLineFragment:glyphPosition:characterIndex:', {'required': True, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'cellSize', {'required': True, 'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSObject', b'changeColor:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'changeFont:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'changeSpelling:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'characterIndexForPoint:', {'required': True, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'collectionView:acceptDrop:index:dropOperation:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:acceptDrop:indexPath:dropOperation:', {'retval': {'type': 'Z'}, 'arguments': {5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:canDragItemsAtIndexPaths:withEvent:', {'retval': {'type': 'Z'}})
r(b'NSObject', b'collectionView:canDragItemsAtIndexes:withEvent:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'collectionView:didChangeItemsAtIndexPaths:toHighlightState:', {'arguments': {4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:draggingImageForItemsAtIndexPaths:withEvent:offset:', {'arguments': {5: {'type': sel32or64(b'^{_NSPoint=ff}', b'^{CGPoint=dd}'), 'type_modifier': b'N'}}})
r(b'NSObject', b'collectionView:draggingImageForItemsAtIndexes:withEvent:offset:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'^{_NSPoint=ff}', b'^{CGPoint=dd}'), 'type_modifier': b'N'}}})
r(b'NSObject', b'collectionView:draggingSession:endedAtPoint:dragOperation:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'collectionView:draggingSession:endedAtPoint:draggingOperation:', {'arguments': {4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:draggingSession:willBeginAtPoint:forItemsAtIndexPaths:', {'arguments': {4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'collectionView:draggingSession:willBeginAtPoint:forItemsAtIndexes:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': b'@'}}})
r(b'NSObject', b'collectionView:layout:insetForSectionAtIndex:', {'retval': {'type': sel32or64(b'{NSEdgeInsets=ffff}', b'{NSEdgeInsets=dddd}')}, 'arguments': {4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:layout:minimumInteritemSpacingForSectionAtIndex:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:layout:minimumLineSpacingForSectionAtIndex:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:layout:referenceSizeForFooterInSection:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:layout:referenceSizeForHeaderInSection:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:layout:sizeForItemAtIndexPath:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSObject', b'collectionView:namesOfPromisedFilesDroppedAtDestination:forDraggedItemsAtIndexes:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'collectionView:numberOfItemsInSection:', {'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:pasteboardWriterForItemAtIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:shouldChangeItemsAtIndexPaths:toHighlightState:', {'arguments': {4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'collectionView:updateDraggingItemsForDrag:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'collectionView:validateDrop:proposedIndex:dropOperation:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'N'}, 5: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'N'}}})
r(b'NSObject', b'collectionView:validateDrop:proposedIndexPath:dropOperation:', {'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {4: {'type': '^@', 'type_modifier': b'N'}}})
r(b'NSObject', b'collectionView:writeItemsAtIndexPaths:toPasteboard:', {'retval': {'type': 'Z'}})
r(b'NSObject', b'collectionView:writeItemsAtIndexes:toPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'comboBox:completedString:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'comboBox:indexOfItemWithStringValue:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'comboBox:objectValueForItemAtIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'comboBoxCell:completedString:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'comboBoxCell:indexOfItemWithStringValue:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'comboBoxCell:objectValueForItemAtIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'comboBoxSelectionDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'comboBoxSelectionIsChanging:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'comboBoxWillDismiss:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'comboBoxWillPopUp:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'commitEditing', {'retval': {'type': 'Z'}})
r(b'NSObject', b'commitEditingAndReturnError:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'^@'}}})
r(b'NSObject', b'commitEditingWithDelegate:didCommitSelector:contextInfo:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': ':', 'sel_of_type': b'v@:@Z^v'}, 4: {'type': '^v'}}})
r(b'NSObject', b'concludeDragOperation:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'confinementRectForMenu:onScreen:', {'required': False, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'contentView', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'contentViewAtIndex:effectiveCharacterRange:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': sel32or64(b'o^{_NSRange=II}', b'o^{_NSRange=QQ}')}}})
r(b'NSObject', b'control:didFailToFormatString:errorDescription:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'control:didFailToValidatePartialString:errorDescription:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'control:isValidObject:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'control:textShouldBeginEditing:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'control:textShouldEndEditing:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'control:textView:completions:forPartialWordRange:indexOfSelectedItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 6: {'null_accepted': False, 'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'N'}}})
r(b'NSObject', b'control:textView:doCommandBySelector:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': ':', 'sel_of_type': b'v@:@'}}})
r(b'NSObject', b'controlTextDidBeginEditing:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'controlTextDidChange:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'controlTextDidEndEditing:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'conversationIdentifier', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'currentMode', {'required': True, 'retval': {'type': 'i'}})
r(b'NSObject', b'customWindowsToEnterFullScreenForWindow:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'customWindowsToEnterFullScreenForWindow:onScreen:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'customWindowsToExitFullScreenForWindow:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'datePickerCell:validateProposedDateValue:timeInterval:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': '^@', 'type_modifier': b'N'}, 4: {'type': sel32or64(b'^f', b'^d'), 'type_modifier': b'N'}}})
r(b'NSObject', b'defaultAnimationForKey:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'defaultPlaceholderForMarker:withBinding:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'detachColorList:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'detachableWindowForPopover:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'didReplaceCharacters', {'required': False, 'retval': {'type': b'v'}})
r(b'NSObject', b'discardEditing', {'retval': {'type': b'v'}})
r(b'NSObject', b'doCommandBySelector:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': ':', 'sel_of_type': b'v@:@'}}})
r(b'NSObject', b'doCommandBySelector:client:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': ':', 'sel_of_type': b'v@:@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'dockMenu', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'draggedImage', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'draggedImage:beganAt:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'draggedImage:endedAt:deposited:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': 'Z'}}})
r(b'NSObject', b'draggedImage:endedAt:operation:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'draggedImage:movedTo:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'draggedImageLocation', {'required': True, 'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSObject', b'draggingDestinationWindow', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'draggingEnded:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'draggingEntered:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'draggingExited:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'draggingFormation', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'draggingLocation', {'required': True, 'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSObject', b'draggingPasteboard', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'draggingSequenceNumber', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'draggingSession:endedAtPoint:operation:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'draggingSession:movedToPoint:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'draggingSession:sourceOperationMaskForDraggingContext', {'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'draggingSession:sourceOperationMaskForDraggingContext:', {'required': True, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'draggingSession:willBeginAtPoint:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'draggingSource', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'draggingSourceOperationMask', {'required': True, 'retval': {'type': sel32or64(b'I', b'Q')}})
r(b'NSObject', b'draggingSourceOperationMaskForLocal:', {'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSObject', b'draggingUpdated:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'drawCharactersInRange:forContentView:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': b'@'}}})
r(b'NSObject', b'drawWithFrame:inView:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': b'@'}}})
r(b'NSObject', b'drawWithFrame:inView:characterIndex:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'drawWithFrame:inView:characterIndex:layoutManager:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}, 5: {'type': b'@'}}})
r(b'NSObject', b'drawerDidClose:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'drawerDidOpen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'drawerShouldClose:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'drawerShouldOpen:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'drawerWillClose:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'drawerWillOpen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'drawerWillResizeContents:toSize:', {'required': False, 'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSObject', b'drawsVerticallyForCharacterAtIndex:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'editable', {'retval': {'type': b'Z'}})
r(b'NSObject', b'effectiveAppearance', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'enumerateDraggingItemsWithOptions:forView:classes:searchOptions:usingBlock:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}, 6: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': sel32or64(b'i', b'q')}, 3: {'type': b'o^Z'}}}, 'type': b'@?'}}})
r(b'NSObject', b'exposeBinding:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'exposedBindings', {'retval': {'type': b'@'}})
r(b'NSObject', b'filePromiseProvider:writePromiseToURL:completionHandler:', {'arguments': {4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}, 'type': '@?'}}})
r(b'NSObject', b'findBarView', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'findBarViewDidChangeHeight', {'required': True, 'retval': {'type': b'v'}})
r(b'NSObject', b'findBarVisible', {'retval': {'type': b'Z'}})
r(b'NSObject', b'firstRectForCharacterRange:', {'required': True, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'firstRectForCharacterRange:actualRange:', {'required': True, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSObject', b'firstSelectedRange', {'required': False, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSObject', b'fontManager:willIncludeFont:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'fractionOfDistanceThroughGlyphForPoint:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'gestureRecognizer:shouldAttemptToRecognizeWithEvent:', {'retval': {'type': 'Z'}})
r(b'NSObject', b'gestureRecognizer:shouldBeRequiredToFailByGestureRecognizer:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'gestureRecognizer:shouldReceiveTouch:', {'retval': {'type': 'Z'}})
r(b'NSObject', b'gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'gestureRecognizer:shouldRequireFailureOfGestureRecognizer:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'gestureRecognizerShouldBegin:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'hasMarkedText', {'required': True, 'retval': {'type': 'Z'}})
r(b'NSObject', b'highlight:withFrame:inView:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': b'@'}}})
r(b'NSObject', b'hyphenCharacterForGlyphAtIndex:', {'retval': {'type': 'i'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'hyphenationFactorForGlyphAtIndex:', {'retval': {'type': 'f'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'identifier', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'ignoreModifierKeysForDraggingSession:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'ignoreModifierKeysWhileDragging', {'retval': {'type': 'Z'}})
r(b'NSObject', b'ignoreSpelling:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'image:didLoadPartOfRepresentation:withValidRows:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'image:didLoadRepresentation:withStatus:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'image:didLoadRepresentationHeader:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'image:willLoadRepresentation:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'imageDidNotDraw:inRect:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'imageForBounds:textContainer:characterIndex:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'infoForBinding:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'initWithPasteboardPropertyList:ofType:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'initWithPickerMask:colorPanel:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': b'@'}}})
r(b'NSObject', b'inputClientBecomeActive:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'inputClientDisabled:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'inputClientEnabled:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'inputClientResignActive:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'insertGlyphs:length:forStartingGlyphAtIndex:characterIndex:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': '^I', 'type_modifier': b'n', 'c_array_length_in_arg': 3}, 3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'I', b'Q')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'insertNewButtonImage:in:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': '@'}, 3: {'type': '@'}}})
r(b'NSObject', b'insertText:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': '@'}}})
r(b'NSObject', b'insertText:client:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': '@'}, 3: {'type': '@'}}})
r(b'NSObject', b'insertText:replacementRange:', {'required': True, 'retval': {'type': 'v'}, 'arguments': {2: {'type': '@'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'ioCommandBySelector:', {'arguments': {2: {'type': ':', 'sel_of_type': b'v@:@'}}})
r(b'NSObject', b'isAccessibilityAlternateUIVisible', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityDisclosed', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityEdited', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityElement', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityEnabled', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityExpanded', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityFocused', {'required': False, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityFrontmost', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityHidden', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityMain', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityMinimized', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityModal', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityOrderedByRow', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityProtectedContent', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilityRequired', {'retval': {'type': 'Z'}})
r(b'NSObject', b'isAccessibilitySelected', {'required': True, 'retval': {'type': b'Z'}})
r(b'NSObject', b'isAccessibilitySelectorAllowed:', {'required': True, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b':'}}})
r(b'NSObject', b'isContentDiscarded', {'retval': {'type': 'Z'}})
r(b'NSObject', b'isEditable', {'required': False, 'retval': {'type': 'Z'}})
r(b'NSObject', b'isExplicitlyIncluded', {'retval': {'type': 'Z'}})
r(b'NSObject', b'isFindBarVisible', {'required': True, 'retval': {'type': 'Z'}})
r(b'NSObject', b'isSelectable', {'required': False, 'retval': {'type': 'Z'}})
r(b'NSObject', b'key', {'retval': {'type': b'@'}})
r(b'NSObject', b'keyPathsForValuesAffectingPreview', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'layer:shouldInheritContentsScale:fromWindow:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'f', b'd')}, 4: {'type': b'@'}}})
r(b'NSObject', b'layoutManager:boundingBoxForControlGlyphAtIndex:forTextContainer:proposedLineFragment:glyphPosition:characterIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'I', b'Q')}, 5: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 6: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 7: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'layoutManager:didCompleteLayoutForTextContainer:atEnd:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': 'Z'}}})
r(b'NSObject', b'layoutManager:lineSpacingAfterGlyphAtIndex:withProposedLineFragmentRect:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'layoutManager:paragraphSpacingAfterGlyphAtIndex:withProposedLineFragmentRect:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'layoutManager:paragraphSpacingBeforeGlyphAtIndex:withProposedLineFragmentRect:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'layoutManager:shouldBreakLineByHyphenatingBeforeCharacterAtIndex:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'layoutManager:shouldBreakLineByWordBeforeCharacterAtIndex:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'layoutManager:shouldGenerateGlyphs:properties:characterIndexes:forGlyphRange:', {'arguments': {3: {'type': 'n^S', 'c_array_length_in_arg': 6}, 4: {'type': sel32or64(b'n^I', b'n^Q'), 'c_array_length_in_arg': 6}, 5: {'type': sel32or64(b'n^I', b'n^Q'), 'c_array_length_in_arg': 6}, 6: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'layoutManager:shouldSetLineFragmentRect:lineFragmentUsedRect:baselineOffset:inTextContainer:forGlyphRange:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'N^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'N^{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'N^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'N^{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'N^f', b'N^d')}, 7: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'layoutManager:shouldUseAction:forControlCharacterAtIndex:', {'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'layoutManager:shouldUseTemporaryAttributes:forDrawingToScreen:atCharacterIndex:effectiveRange:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': 'Z'}, 5: {'type': sel32or64(b'I', b'Q')}, 6: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}'), 'type_modifier': b'o'}}})
r(b'NSObject', b'layoutManager:textContainer:didChangeGeometryFromSize:', {'arguments': {4: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSObject', b'layoutManagerDidInvalidateLayout:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'layoutOptions', {'required': True, 'retval': {'type': sel32or64(b'I', b'Q')}})
r(b'NSObject', b'layoutOrientation', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'listener:shouldAcceptNewConnection:', {'retval': {'type': 'Z'}})
r(b'NSObject', b'localizedKey', {'retval': {'type': b'@'}})
r(b'NSObject', b'localizedSummaryItems', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'localizedTitlesForItem:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'markedRange', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSObject', b'markedTextAbandoned:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'markedTextSelectionChanged:client:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': b'@'}}})
r(b'NSObject', b'menu:updateItem:atIndex:shouldCancel:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': 'Z'}}})
r(b'NSObject', b'menu:willHighlightItem:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'menuDidClose:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'menuHasKeyEquivalent:forEvent:target:action:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': '^@', 'type_modifier': b'o'}, 5: {'type': '^:', 'type_modifier': b'o'}}})
r(b'NSObject', b'menuNeedsUpdate:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'menuWillOpen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'minContentSize', {'required': True, 'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSObject', b'mouseDownOnCharacterIndex:atCoordinate:withModifier:client:', {'required': True, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'I', b'Q')}, 5: {'type': b'@'}}})
r(b'NSObject', b'mouseDraggedOnCharacterIndex:atCoordinate:withModifier:client:', {'required': True, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'I', b'Q')}, 5: {'type': b'@'}}})
r(b'NSObject', b'mouseUpOnCharacterIndex:atCoordinate:withModifier:client:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'I', b'Q')}, 5: {'type': b'@'}}})
r(b'NSObject', b'namesOfPromisedFilesDroppedAtDestination:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'numberOfItemsForScrubber:', {'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'numberOfItemsInComboBox:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'numberOfItemsInComboBoxCell:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'numberOfItemsInMenu:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'numberOfRowsInTableView:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'numberOfSectionsInCollectionView:', {'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'numberOfValidItemsForDrop', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'objectDidBeginEditing:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'objectDidEndEditing:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'optionDescriptionsForBinding:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'outlineView:acceptDrop:item:childIndex:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'outlineView:child:ofItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:dataCellForTableColumn:item:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:didAddRowView:forRow:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'outlineView:didClickTableColumn:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:didDragTableColumn:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:didRemoveRowView:forRow:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'outlineView:draggingSession:endedAtPoint:', {'arguments': {4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'outlineView:draggingSession:endedAtPoint:operation:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'outlineView:draggingSession:willBeginAtPoint:', {'arguments': {4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'outlineView:draggingSession:willBeginAtPoint:forItems:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': b'@'}}})
r(b'NSObject', b'outlineView:heightOfRowByItem:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:isGroupItem:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:isItemExpandable:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:itemForPersistentObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:mouseDownInHeaderOfTableColumn:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:namesOfPromisedFilesDroppedAtDestination:forDraggedItems:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:nextTypeSelectMatchFromItem:toItem:forString:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}}})
r(b'NSObject', b'outlineView:numberOfChildrenOfItem:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:objectValueForTableColumn:byItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:pasteboardWriterForItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:persistentObjectForItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:rowViewForItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:selectionIndexesForProposedSelection:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:setObjectValue:forTableColumn:byItem:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldCollapseItem:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldEditTableColumn:item:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldExpandItem:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldReorderColumn:toColumn:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'outlineView:shouldSelectItem:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldSelectTableColumn:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldShowCellExpansionForTableColumn:item:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldShowOutlineCellForItem:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldTrackCell:forTableColumn:item:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}}})
r(b'NSObject', b'outlineView:shouldTypeSelectForEvent:withCurrentSearchString:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:sizeToFitWidthOfColumn:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'outlineView:sortDescriptorsDidChange:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:toolTipForCell:rect:tableColumn:item:mouseLocation:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 5: {'type': b'@'}, 6: {'type': b'@'}, 7: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'outlineView:typeSelectStringForTableColumn:item:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:updateDraggingItemsForDrag:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'outlineView:validateDrop:proposedItem:proposedChildIndex:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'outlineView:viewForTableColumn:item:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineView:willDisplayCell:forTableColumn:item:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}}})
r(b'NSObject', b'outlineView:willDisplayOutlineCell:forTableColumn:item:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}}})
r(b'NSObject', b'outlineView:writeItems:toPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'outlineViewColumnDidMove:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'outlineViewColumnDidResize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'outlineViewItemDidCollapse:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'outlineViewItemDidExpand:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'outlineViewItemWillCollapse:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'outlineViewItemWillExpand:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'outlineViewSelectionDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'outlineViewSelectionIsChanging:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'pageController:didTransitionToObject:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pageController:frameForObject:', {'required': False, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pageController:identifierForObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pageController:prepareViewController:withObject:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'pageController:viewControllerForIdentifier:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pageControllerDidEndLiveTransition:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'pageControllerWillStartLiveTransition:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'panel:compareFilename:with:caseSensitive:', {'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': 'Z'}}})
r(b'NSObject', b'panel:didChangeToDirectoryURL:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'panel:directoryDidChange:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'panel:isValidFilename:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'panel:shouldEnableURL:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'panel:shouldShowFilename:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'panel:userEnteredFilename:confirmed:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': 'Z'}}})
r(b'NSObject', b'panel:validateURL:error:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': '^@', 'type_modifier': b'o'}}})
r(b'NSObject', b'panel:willExpand:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': 'Z'}}})
r(b'NSObject', b'panelSelectionDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'pasteboard:item:provideDataForType:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'pasteboard:provideDataForType:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pasteboardChangedOwner:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'pasteboardFinishedWithDataProvider:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'pasteboardPropertyListForType:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'pathCell:willDisplayOpenPanel:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pathCell:willPopUpMenu:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pathControl:acceptDrop:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pathControl:shouldDragItem:withPasteboard:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'pathControl:shouldDragPathComponentCell:withPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'pathControl:validateDrop:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pathControl:willDisplayOpenPanel:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'pathControl:willPopUpMenu:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'performActionForItem:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'performDragOperation:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'performFeedbackPattern:performanceTime:', {'arguments': {3: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'performSegueWithIdentifier:sender:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'popoverDidClose:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'popoverDidShow:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'popoverShouldClose:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'popoverShouldDetach:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'popoverWillClose:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'popoverWillShow:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'prepareForDragOperation:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'prepareForInterfaceBuilder', {'retval': {'type': b'v'}})
r(b'NSObject', b'prepareForSegue:sender:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'provideNewButtonImage', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'provideNewView:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSObject', b'readSelectionFromPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'readableTypesForPasteboard:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'readingOptionsForType:pasteboard:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'rectsForCharacterInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'rectsForCharacterRange:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'remoteObjectProxyWithErrorHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}, 'type': '@?'}}})
r(b'NSObject', b'replaceCharactersInRange:withString:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': b'@'}}})
r(b'NSObject', b'restoreWindowWithIdentifier:state:completionHandler:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}, 'type': '@?'}}})
r(b'NSObject', b'rootItemForBrowser:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'ruleEditor:child:forCriterion:withRowType:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'ruleEditor:displayValueForCriterion:inRow:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'ruleEditor:numberOfChildrenForCriterion:withRowType:', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'ruleEditor:predicatePartsForCriterion:withDisplayValue:inRow:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'ruleEditorRowsDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'rulerView:didAddMarker:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'rulerView:didMoveMarker:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'rulerView:didRemoveMarker:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'rulerView:handleMouseDown:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'rulerView:locationForPoint:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'rulerView:pointForLocation:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'f', b'd')}}})
r(b'NSObject', b'rulerView:pointForlocation:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'f', b'd')}}})
r(b'NSObject', b'rulerView:shouldAddMarker:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'rulerView:shouldMoveMarker:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'rulerView:shouldRemoveMarker:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'rulerView:willAddMarker:atLocation:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'f', b'd')}}})
r(b'NSObject', b'rulerView:willMoveMarker:toLocation:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'f', b'd')}}})
r(b'NSObject', b'rulerView:willSetClientView:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'scrollRangeToVisible:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'scrubber:didChangeVisibleRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'scrubber:didHighlightItemAtIndex:', {'arguments': {3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'scrubber:didSelectItemAtIndex:', {'arguments': {3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'scrubber:layout:sizeForItemAtIndex:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'scrubber:viewForItemAtIndex:', {'arguments': {3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'searchForItemsWithSearchString:resultLimit:matchedItemHandler:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}, 'type': '@?'}}})
r(b'NSObject', b'selectable', {'retval': {'type': b'Z'}})
r(b'NSObject', b'selectedRange', {'required': True, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSObject', b'selectedRanges', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'selectionShouldChangeInOutlineView:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'selectionShouldChangeInTableView:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityActivationPoint:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'setAccessibilityAllowedValues:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityAlternateUIVisible:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityApplicationFocusedUIElement:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityCancelButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityChildren:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityClearButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityCloseButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityColumnCount:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityColumnHeaderUIElements:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityColumnIndexRange:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'setAccessibilityColumnTitles:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityColumns:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityContents:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityCriticalValue:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityDecrementButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityDefaultButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityDisclosed:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityDisclosedByRow:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityDisclosedRows:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityDisclosureLevel:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityDocument:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityEdited:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityElement:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityEnabled:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityExpanded:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityExtrasMenuBar:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityFilename:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityFocused:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityFocusedWindow:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityFrame:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'setAccessibilityFrontmost:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityFullScreenButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityGrowArea:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityHandles:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityHeader:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityHelp:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityHidden:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityHorizontalScrollBar:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityHorizontalUnitDescription:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityHorizontalUnits:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityIdentifier:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityIncrementButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityIndex:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityInsertionPointLineNumber:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityLabel:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityLabelUIElements:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityLabelValue:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'f'}}})
r(b'NSObject', b'setAccessibilityLinkedUIElements:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMain:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityMainWindow:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMarkerGroupUIElement:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMarkerTypeDescription:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMarkerUIElements:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMarkerValues:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMaxValue:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMenuBar:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMinValue:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMinimizeButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityMinimized:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityModal:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityNextContents:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityNumberOfCharacters:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityOrderedByRow:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityOrientation:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityOverflowButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityParent:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityPlaceholderValue:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityPreviousContents:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityProtectedContent:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilityProxy:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityRole:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityRoleDescription:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityRowCount:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityRowHeaderUIElements:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityRowIndexRange:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'setAccessibilityRows:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityRulerMarkerType:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilitySearchButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySearchMenu:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySelected:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAccessibilitySelectedCells:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySelectedChildren:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySelectedColumns:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySelectedRows:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySelectedText:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySelectedTextRange:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'setAccessibilitySelectedTextRanges:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityServesAsTitleForUIElements:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySharedCharacterRange:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'setAccessibilitySharedFocusElements:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySharedTextUIElements:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityShownMenu:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySortDirection:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilitySplitters:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilitySubrole:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityTabs:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityTitle:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityTitleUIElement:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityToolbarButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityTopLevelUIElement:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityURL:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityUnitDescription:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityUnits:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityValue:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityValueDescription:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityVerticalScrollBar:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityVerticalUnitDescription:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityVerticalUnits:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setAccessibilityVisibleCells:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityVisibleCharacterRange:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'setAccessibilityVisibleChildren:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityVisibleColumns:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityVisibleRows:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityWarningValue:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityWindow:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityWindows:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAccessibilityZoomButton:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAllowsMultipleSelection:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAnimatesToDestination:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setAnimations:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAppearance:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setAttachment:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setColor:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setDefaultPlaceholder:forMarker:withBinding:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'setDockTile:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setDraggingFormation:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setEditable:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setFindBarView:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setFindBarVisible:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSObject', b'setFirstSelectedRange:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'setIdentifier:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setIntAttribute:value:forGlyphAtIndex:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'setKey:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setLocalizedKey:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setMarkedText:selectedRange:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'setMarkedText:selectedRange:replacementRange:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'setMode:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': 'i'}}})
r(b'NSObject', b'setNumberOfValidItemsForDrop:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'setSelectable:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'Z'}}})
r(b'NSObject', b'setSelectedRanges:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setString:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setValue:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'setVisibleCharacterRanges:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'sharingService:didFailToShareItems:error:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'sharingService:didShareItems:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'sharingService:sourceFrameOnScreenForShareItem:', {'required': False, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'sharingService:sourceWindowForShareItems:sharingContentScope:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'^i', b'^q')}}})
r(b'NSObject', b'sharingService:transitionImageForShareItem:contentRect:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'sharingService:willShareItems:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'sharingServicePicker:delegateForSharingService:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'sharingServicePicker:didChooseSharingService:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'sharingServicePicker:sharingServicesForItems:proposedSharingServices:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'shouldPerformSegueWithIdentifier:sender:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'shouldReplaceCharactersInRanges:withStrings:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'showAllHelpTopicsForSearchString:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'showRelativeToRect:ofView:preferredEdge:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'slideDraggedImageTo:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'sound:didFinishPlaying:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': 'Z'}}})
r(b'NSObject', b'speechRecognizer:didRecognizeCommand:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'speechSynthesizer:didEncounterErrorAtIndex:ofString:message:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': b'@'}, 5: {'type': b'@'}}})
r(b'NSObject', b'speechSynthesizer:didEncounterSyncMessage:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'speechSynthesizer:didFinishSpeaking:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': 'Z'}}})
r(b'NSObject', b'speechSynthesizer:willSpeakPhoneme:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': 's'}}})
r(b'NSObject', b'speechSynthesizer:willSpeakWord:ofString:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': b'@'}}})
r(b'NSObject', b'splitView:additionalEffectiveRectOfDividerAtIndex:', {'required': False, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:canCollapseSubview:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'splitView:constrainMaxCoordinate:ofSubviewAt:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'f', b'd')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:constrainMinCoordinate:ofSubviewAt:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'f', b'd')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:constrainSplitPosition:ofSubviewAt:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'f', b'd')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:effectiveRect:forDrawnRect:ofDividerAtIndex:', {'required': False, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:onstrainMaxCoordinate:ofSubviewAt:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {3: {'type': sel32or64(b'f', b'd')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:onstrainMinCoordinate:ofSubviewAt:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {3: {'type': sel32or64(b'f', b'd')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:onstrainSplitPosition:ofSubviewAt:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {3: {'type': sel32or64(b'f', b'd')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:resizeSubviewsWithOldSize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSObject', b'splitView:shouldAdjustSizeOfSubview:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'splitView:shouldCollapseSubview:forDoubleClickOnDividerAtIndex:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitView:shouldHideDividerAtIndex:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'splitViewDidResizeSubviews:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'splitViewWillResizeSubviews:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'springLoadingActivated:draggingInfo:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSObject', b'springLoadingEntered:', {'retval': {'type': sel32or64(b'I', b'Q')}})
r(b'NSObject', b'springLoadingUpdated:', {'retval': {'type': sel32or64(b'I', b'Q')}})
r(b'NSObject', b'stackView:didReattachViews:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'stackView:willDetachViews:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'string', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'stringAtIndex:effectiveRange:endsWithSearchBoundary:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': sel32or64(b'^{_NSRange=II}', b'^{_NSRange=QQ}')}, 4: {'type': b'^Z'}}})
r(b'NSObject', b'stringAtIndex:effectiveRange:endswithSearchBoundary:', {'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 3: {'type': sel32or64(b'o^{_NSRange=II}', b'o^{_NSRange=QQ}')}, 4: {'type': 'o^Z'}}})
r(b'NSObject', b'stringLength', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}})
r(b'NSObject', b'supportsMode:', {'required': True, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': 'i'}}})
r(b'NSObject', b'tabView:didSelectTabViewItem:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tabView:shouldSelectTabViewItem:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tabView:willSelectTabViewItem:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tabViewDidChangeNumberOfTabViewItems:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'tableView:acceptDrop:row:dropOperation:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'tableView:dataCellForTableColumn:row:', {'required': False, 'retval': {'type': '@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:didAddRowView:forRow:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:didClickTableColumn:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tableView:didDragTableColumn:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tableView:didRemoveRowView:forRow:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:draggingSession:endedAtPoint:operation:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'tableView:draggingSession:willBeginAtPoint:forRowIndexes:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': b'@'}}})
r(b'NSObject', b'tableView:heightOfRow:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:isGroupRow:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:mouseDownInHeaderOfTableColumn:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tableView:namesOfPromisedFilesDroppedAtDestination:forDraggedRowsWithIndexes:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'tableView:nextTypeSelectMatchFromRow:toRow:forString:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': b'@'}}})
r(b'NSObject', b'tableView:objectValueForTableColumn:row:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:pasteboardWriterForRow:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:rowActionsForRow:edge:', {'arguments': {3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:rowViewForRow:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:selectionIndexesForProposedSelection:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tableView:setObjectValue:forTableColumn:row:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:shouldEditTableColumn:row:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:shouldReorderColumn:toColumn:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:shouldSelectRow:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:shouldSelectTableColumn:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tableView:shouldShowCellExpansionForTableColumn:row:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:shouldTrackCell:forTableColumn:row:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:shouldTypeSelectForEvent:withCurrentSearchString:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'tableView:sizeToFitWidthOfColumn:', {'required': False, 'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:sortDescriptorsDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tableView:toolTipForCell:rect:tableColumn:row:mouseLocation:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 5: {'type': b'@'}, 6: {'type': sel32or64(b'i', b'q')}, 7: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSObject', b'tableView:typeSelectStringForTableColumn:row:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:updateDraggingItemsForDrag:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tableView:validateDrop:proposedRow:proposedDropOperation:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'tableView:viewForTableColumn:row:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:willDisplayCell:forTableColumn:row:', {'required': False, 'retval': {'type': 'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'tableView:writeRows:toPasteboard:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'tableView:writeRowsWithIndexes:toPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'tableViewColumnDidMove:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'tableViewColumnDidResize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'tableViewSelectionDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'tableViewSelectionIsChanging:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'tag', {'required': True, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'terminate:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textDidBeginEditing:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textDidEndEditing:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textField:textView:candidates:forSelectedRange:', {'arguments': {5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'textField:textView:candidatesForSelectedRange:', {'arguments': {4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'textField:textView:shouldSelectCandidateAtIndex:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textShouldBeginEditing:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textShouldEndEditing:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textStorage:didProcessEditing:range:changeInLength:', {'arguments': {3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'textStorage:willProcessEditing:range:changeInLength:', {'arguments': {3: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'textStorageDidProcessEditing:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textStorageWillProcessEditing:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textView:URLForContentsOfTextAttachment:atIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:candidates:forSelectedRange:', {'arguments': {4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'textView:candidatesForSelectedRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'textView:clickedOnCell:inRect:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'textView:clickedOnCell:inRect:atIndex:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:clickedOnLink:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'textView:clickedOnLink:atIndex:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:completions:forPartialWordRange:indexOfSelectedItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'N'}}})
r(b'NSObject', b'textView:didCheckTextInRange:types:options:results:orthography:wordCount:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': b'@'}, 6: {'type': b'@'}, 7: {'type': b'@'}, 8: {'type': sel32or64(b'i', b'q')}}})
r(b'NSObject', b'textView:doCommandBySelector:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': ':', 'sel_of_type': b'v@:@'}}})
r(b'NSObject', b'textView:doubleClickedOnCell:inRect:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'textView:doubleClickedOnCell:inRect:atIndex:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:draggedCell:inRect:event:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': b'@'}}})
r(b'NSObject', b'textView:draggedCell:inRect:event:atIndex:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': b'@'}, 6: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:menu:forEvent:atIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:shouldChangeTextInRange:replacementString:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': b'@'}}})
r(b'NSObject', b'textView:shouldChangeTextInRanges:replacementStrings:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'textView:shouldChangeTypingAttributes:toAttributes:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'textView:shouldSelectCandidateAtIndex:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:shouldSetSpellingState:range:', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'i', b'q')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'textView:willChangeSelectionFromCharacterRange:toCharacterRange:', {'required': False, 'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSObject', b'textView:willChangeSelectionFromCharacterRanges:toCharacterRanges:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'textView:willCheckTextInRange:options:types:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'N'}}})
r(b'NSObject', b'textView:willDisplayToolTip:forCharacterAtIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:willShowSharingServicePicker:forItems:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'textView:writablePasteboardTypesForCell:atIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'textView:writeCell:atIndex:toPasteboard:type:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}, 5: {'type': b'@'}, 6: {'type': b'@'}}})
r(b'NSObject', b'textViewDidChangeSelection:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'textViewDidChangeTypingAttributes:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'o'}}})
r(b'NSObject', b'tokenField:displayStringForRepresentedObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenField:editingStringForRepresentedObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenField:hasMenuForRepresentedObject:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenField:menuForRepresentedObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenField:readFromPasteboard:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenField:representedObjectForEditingString:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenField:shouldAddObjects:atIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'tokenField:styleForRepresentedObject:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenField:writeRepresentedObjects:toPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'tokenFieldCell:completionsForSubstring:indexOfToken:indexOfSelectedItem:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}, 5: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'o'}}})
r(b'NSObject', b'tokenFieldCell:displayStringForRepresentedObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenFieldCell:editingStringForRepresentedObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenFieldCell:hasMenuForRepresentedObject:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenFieldCell:menuForRepresentedObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenFieldCell:readFromPasteboard:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenFieldCell:representedObjectForEditingString:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenFieldCell:shouldAddObjects:atIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'tokenFieldCell:styleForRepresentedObject:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'tokenFieldCell:writeRepresentedObjects:toPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}})
r(b'NSObject', b'toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': 'Z'}}})
r(b'NSObject', b'toolbarAllowedItemIdentifiers:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'toolbarDefaultItemIdentifiers:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'toolbarDidRemoveItem:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'toolbarSelectableItemIdentifiers:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'toolbarWillAddItem:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'trackMouse:inRect:ofView:atCharacterIndex:untilMouseUp:', {'required': True, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'I', b'Q')}, 6: {'type': 'Z'}}})
r(b'NSObject', b'trackMouse:inRect:ofView:untilMouseUp:', {'required': True, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': b'@'}, 5: {'type': 'Z'}}})
r(b'NSObject', b'unbind:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'undoManagerForTextView:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'unmarkText', {'required': True, 'retval': {'type': b'v'}})
r(b'NSObject', b'updateDraggingItemsForDrag:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'validAttributesForMarkedText', {'required': True, 'retval': {'type': b'@'}})
r(b'NSObject', b'validModesForFontPanel:', {'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'validateMenuItem:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'validateToolbarItem:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'validateUserInterfaceItem:', {'required': True, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'value', {'retval': {'type': b'@'}})
r(b'NSObject', b'valueClassForBinding:', {'retval': {'type': '#'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'view:stringForToolTip:point:userData:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': 'i'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': '^v'}}})
r(b'NSObject', b'viewSizeChanged:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'visibleCharacterRanges', {'required': False, 'retval': {'type': b'@'}})
r(b'NSObject', b'wantsPeriodicDraggingUpdates', {'required': False, 'retval': {'type': 'Z'}})
r(b'NSObject', b'wantsToDelayTextChangeNotifications', {'required': True, 'retval': {'type': 'Z'}})
r(b'NSObject', b'wantsToHandleMouseEvents', {'required': True, 'retval': {'type': 'Z'}})
r(b'NSObject', b'wantsToInterpretAllKeystrokes', {'required': True, 'retval': {'type': 'Z'}})
r(b'NSObject', b'wantsToTrackMouse', {'required': True, 'retval': {'type': 'Z'}})
r(b'NSObject', b'wantsToTrackMouseForEvent:inRect:ofView:atCharacterIndex:', {'required': True, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': b'@'}, 5: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'window:didDecodeRestorableState:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'window:shouldDragDocumentWithEvent:from:withPasteboard:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 5: {'type': b'@'}}})
r(b'NSObject', b'window:shouldPopUpDocumentPathMenu:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'window:startCustomAnimationToEnterFullScreenOnScreen:withDuration:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'd'}}})
r(b'NSObject', b'window:startCustomAnimationToEnterFullScreenWithDuration:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'd'}}})
r(b'NSObject', b'window:startCustomAnimationToExitFullScreenWithDuration:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'd'}}})
r(b'NSObject', b'window:willEncodeRestorableState:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'window:willPositionSheet:usingRect:', {'required': False, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'window:willResizeForVersionBrowserWithMaxPreferredSize:maxAllowedSize:', {'required': False, 'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 4: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSObject', b'window:willUseFullScreenContentSize:', {'required': False, 'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSObject', b'window:willUseFullScreenPresentationOptions:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSObject', b'windowDidBecomeKey:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidBecomeMain:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidChangeBackingProperties:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidChangeOcclusionState:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidChangeScreen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidChangeScreenProfile:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidDeminiaturize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidEndLiveResize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidEndSheet:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidEnterFullScreen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidEnterVersionBrowser:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidExitFullScreen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidExitVersionBrowser:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidExpose:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidFailToEnterFullScreen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidFailToExitFullScreen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidMiniaturize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidMove:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidResignKey:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidResignMain:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidResize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowDidUpdate:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowLevel', {'required': False, 'retval': {'type': sel32or64(b'i', b'q')}})
r(b'NSObject', b'windowShouldClose:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowShouldZoom:toFrame:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'windowWillBeginSheet:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillClose:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillEnterFullScreen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillEnterVersionBrowser:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillExitFullScreen:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillExitVersionBrowser:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillMiniaturize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillMove:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillResize:toSize:', {'required': False, 'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSObject', b'windowWillReturnFieldEditor:toObject:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'windowWillReturnUndoManager:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillStartLiveResize:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'windowWillUseStandardFrame:defaultFrame:', {'required': False, 'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSObject', b'writableTypesForPasteboard:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}}})
r(b'NSObject', b'writeSelectionToPasteboard:types:', {'required': False, 'retval': {'type': 'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObject', b'writingOptionsForType:pasteboard:', {'required': False, 'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}})
r(b'NSObjectController', b'automaticallyPreparesContent', {'retval': {'type': 'Z'}})
r(b'NSObjectController', b'canAdd', {'retval': {'type': 'Z'}})
r(b'NSObjectController', b'canRemove', {'retval': {'type': 'Z'}})
r(b'NSObjectController', b'fetchWithRequest:merge:error:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': 'Z'}, 4: {'type_modifier': b'o'}}})
r(b'NSObjectController', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSObjectController', b'setAutomaticallyPreparesContent:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSObjectController', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSObjectController', b'setUsesLazyFetching:', {'retval': {'type': 'v'}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSObjectController', b'usesLazyFetching', {'retval': {'type': 'Z'}})
r(b'NSObjectController', b'validateUserInterfaceItem:', {'retval': {'type': 'Z'}})
r(b'NSOpenGLContext', b'CGLContextObj', {'retval': {'type': '^{_CGLContextObj}'}})
r(b'NSOpenGLContext', b'getValues:forParameter:', {'arguments': {2: {'type': '^i'}}})
r(b'NSOpenGLContext', b'setOffScreen:width:height:rowbytes:', {'arguments': {2: {'type_modifier': b'n', 'c_array_of_variable_length': True}}})
r(b'NSOpenGLContext', b'setValues:forParameter:', {'arguments': {2: {'type_modifier': b'n', 'c_array_of_variable_length': True}}})
r(b'NSOpenGLLayer', b'canDrawInOpenGLContext:pixelFormat:forLayerTime:displayTime:', {'retval': {'type': 'Z'}, 'arguments': {5: {'type': sel32or64(b'^{_CVTimeStamp=IiqQdq{CVSMPTETime=ssLLLssss}QQ}', b'^{_CVTimeStamp=IiqQdq{CVSMPTETime=ssIIIssss}QQ}'), 'type_modifier': b'n'}}})
r(b'NSOpenGLLayer', b'drawInOpenGLContext:pixelFormat:forLayerTime:displayTime:', {'arguments': {5: {'type': sel32or64(b'^{_CVTimeStamp=IiqQdq{CVSMPTETime=ssLLLssss}QQ}', b'^{_CVTimeStamp=IiqQdq{CVSMPTETime=ssIIIssss}QQ}'), 'type_modifier': b'n'}}})
r(b'NSOpenGLPixelFormat', b'CGLPixelFormatObj', {'retval': {'type': '^{_CGLPixelFormatObject}'}})
r(b'NSOpenGLPixelFormat', b'getValues:forAttribute:forVirtualScreen:', {'arguments': {2: {'type': '^i', 'type_modifier': b'o'}}})
r(b'NSOpenGLPixelFormat', b'initWithAttributes:', {'arguments': {2: {'c_array_delimited_by_null': True, 'type': 'r^I', 'type_modifier': b'n'}}})
r(b'NSOpenGLView', b'initWithFrame:pixelFormat:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSOpenPanel', b'allowsMultipleSelection', {'retval': {'type': 'Z'}})
r(b'NSOpenPanel', b'beginForDirectory:file:types:modelessDelegate:didEndSelector:contextInfo:', {'arguments': {6: {'type': ':', 'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 7: {'type': '^v'}}})
r(b'NSOpenPanel', b'beginSheetForDirectory:file:types:modalForWindow:modalDelegate:didEndSelector:contextInfo:', {'arguments': {7: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 8: {'type': '^v'}}})
r(b'NSOpenPanel', b'canChooseDirectories', {'retval': {'type': 'Z'}})
r(b'NSOpenPanel', b'canChooseFiles', {'retval': {'type': 'Z'}})
r(b'NSOpenPanel', b'canDownloadUbiquitousContents', {'retval': {'type': b'Z'}})
r(b'NSOpenPanel', b'canResolveUbiquitousConflicts', {'retval': {'type': b'Z'}})
r(b'NSOpenPanel', b'isAccessoryViewDisclosed', {'retval': {'type': 'Z'}})
r(b'NSOpenPanel', b'resolvesAliases', {'retval': {'type': 'Z'}})
r(b'NSOpenPanel', b'setAccessoryViewDisclosed:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOpenPanel', b'setAllowsMultipleSelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOpenPanel', b'setCanChooseDirectories:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOpenPanel', b'setCanChooseFiles:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOpenPanel', b'setCanDownloadUbiquitousContents:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSOpenPanel', b'setCanResolveUbiquitousConflicts:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSOpenPanel', b'setResolvesAliases:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOutlineView', b'autoresizesOutlineColumn', {'retval': {'type': 'Z'}})
r(b'NSOutlineView', b'autosaveExpandedItems', {'retval': {'type': 'Z'}})
r(b'NSOutlineView', b'collapseItem:collapseChildren:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSOutlineView', b'expandItem:expandChildren:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSOutlineView', b'frameOfOutlineCellAtRow:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSOutlineView', b'indentationMarkerFollowsCell', {'retval': {'type': 'Z'}})
r(b'NSOutlineView', b'isExpandable:', {'retval': {'type': 'Z'}})
r(b'NSOutlineView', b'isItemExpanded:', {'retval': {'type': 'Z'}})
r(b'NSOutlineView', b'reloadItem:reloadChildren:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSOutlineView', b'setAutoresizesOutlineColumn:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOutlineView', b'setAutosaveExpandedItems:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOutlineView', b'setIndentationMarkerFollowsCell:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOutlineView', b'setStronglyReferencesItems:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSOutlineView', b'shouldCollapseAutoExpandedItemsForDeposited:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSOutlineView', b'stronglyReferencesItems', {'retval': {'type': 'Z'}})
r(b'NSPDFImageRep', b'bounds', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSPDFInfo', b'isFileExtensionHidden', {'retval': {'type': b'Z'}})
r(b'NSPDFInfo', b'setFileExtensionHidden:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSPDFPanel', b'beginSheetWithPDFInfo:modalForWindow:completionHandler:', {'arguments': {4: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSPICTImageRep', b'boundingBox', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSPageLayout', b'beginSheetWithPrintInfo:modalForWindow:delegate:didEndSelector:contextInfo:', {'arguments': {5: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 6: {'type': '^v'}}})
r(b'NSPanel', b'becomesKeyOnlyIfNeeded', {'retval': {'type': 'Z'}})
r(b'NSPanel', b'isFloatingPanel', {'retval': {'type': 'Z'}})
r(b'NSPanel', b'setBecomesKeyOnlyIfNeeded:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPanel', b'setFloatingPanel:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPanel', b'setWorksWhenModal:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPanel', b'worksWhenModal', {'retval': {'type': 'Z'}})
r(b'NSParagraphStyle', b'allowsDefaultTighteningForTruncation', {'retval': {'type': 'Z'}})
r(b'NSPasteboard', b'canReadItemWithDataConformingToTypes:', {'retval': {'type': 'Z'}})
r(b'NSPasteboard', b'canReadObjectForClasses:options:', {'retval': {'type': 'Z'}})
r(b'NSPasteboard', b'setData:forType:', {'retval': {'type': 'Z'}})
r(b'NSPasteboard', b'setPropertyList:forType:', {'retval': {'type': 'Z'}})
r(b'NSPasteboard', b'setString:forType:', {'retval': {'type': 'Z'}})
r(b'NSPasteboard', b'writeFileContents:', {'retval': {'type': 'Z'}})
r(b'NSPasteboard', b'writeFileWrapper:', {'retval': {'type': 'Z'}})
r(b'NSPasteboard', b'writeObjects:', {'retval': {'type': 'Z'}})
r(b'NSPasteboardItem', b'setData:forType:', {'retval': {'type': 'Z'}})
r(b'NSPasteboardItem', b'setDataProvider:forTypes:', {'retval': {'type': 'Z'}})
r(b'NSPasteboardItem', b'setPropertyList:forType:', {'retval': {'type': 'Z'}})
r(b'NSPasteboardItem', b'setString:forType:', {'retval': {'type': 'Z'}})
r(b'NSPathCell', b'mouseEntered:withFrame:inView:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPathCell', b'mouseExited:withFrame:inView:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPathCell', b'pathComponentCellAtPoint:withFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPathCell', b'rectOfPathComponentCell:withFrame:inView:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPathCell', b'setDoubleAction:', {'retval': {'type': 'v'}, 'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSPathControl', b'isEditable', {'retval': {'type': b'Z'}})
r(b'NSPathControl', b'setDoubleAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSPathControl', b'setDraggingSourceOperationMask:forLocal:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSPathControl', b'setEditable:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSPersistentDocument', b'configurePersistentStoreCoordinatorForURL:ofType:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSPersistentDocument', b'configurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error:', {'retval': {'type': 'Z'}, 'arguments': {6: {'type_modifier': b'o'}}})
r(b'NSPersistentDocument', b'readFromURL:ofType:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSPersistentDocument', b'revertToContentsOfURL:ofType:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSPersistentDocument', b'writeToURL:ofType:forSaveOperation:originalContentsURL:error:', {'retval': {'type': 'Z'}, 'arguments': {6: {'type_modifier': b'o'}}})
r(b'NSPopUpButton', b'autoenablesItems', {'retval': {'type': 'Z'}})
r(b'NSPopUpButton', b'indexOfItemWithTarget:andAction:', {'arguments': {3: {'sel_of_type': b'v@:@'}}})
r(b'NSPopUpButton', b'initWithFrame:pullsDown:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': 'Z'}}})
r(b'NSPopUpButton', b'pullsDown', {'retval': {'type': 'Z'}})
r(b'NSPopUpButton', b'selectItemWithTag:', {'retval': {'type': 'Z'}})
r(b'NSPopUpButton', b'setAutoenablesItems:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopUpButton', b'setPullsDown:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopUpButtonCell', b'altersStateOfSelectedItem', {'retval': {'type': 'Z'}})
r(b'NSPopUpButtonCell', b'attachPopUpWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPopUpButtonCell', b'autoenablesItems', {'retval': {'type': 'Z'}})
r(b'NSPopUpButtonCell', b'indexOfItemWithTarget:andAction:', {'arguments': {3: {'sel_of_type': b'v@:@'}}})
r(b'NSPopUpButtonCell', b'initTextCell:pullsDown:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSPopUpButtonCell', b'performClickWithFrame:inView:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPopUpButtonCell', b'pullsDown', {'retval': {'type': 'Z'}})
r(b'NSPopUpButtonCell', b'selectItemWithTag:', {'retval': {'type': 'Z'}})
r(b'NSPopUpButtonCell', b'setAltersStateOfSelectedItem:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopUpButtonCell', b'setAutoenablesItems:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopUpButtonCell', b'setPullsDown:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopUpButtonCell', b'setUsesItemFromMenu:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopUpButtonCell', b'usesItemFromMenu', {'retval': {'type': 'Z'}})
r(b'NSPopover', b'animates', {'retval': {'type': b'Z'}})
r(b'NSPopover', b'isDetached', {'retval': {'type': 'Z'}})
r(b'NSPopover', b'isShown', {'retval': {'type': b'Z'}})
r(b'NSPopover', b'setAnimates:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSPopover', b'setDetached:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopover', b'setShown:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopoverTouchBarItem', b'setShowsCloseButton:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPopoverTouchBarItem', b'showsCloseButton', {'retval': {'type': 'Z'}})
r(b'NSPrintInfo', b'PMPageFormat', {'retval': {'type': '^{OpaquePMPageFormat=}'}})
r(b'NSPrintInfo', b'PMPrintSession', {'retval': {'type': '^{OpaquePMPrintSession=}'}})
r(b'NSPrintInfo', b'PMPrintSettings', {'retval': {'type': '^{OpaquePMPrintSettings=}'}})
r(b'NSPrintInfo', b'imageablePageBounds', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSPrintInfo', b'isHorizontallyCentered', {'retval': {'type': 'Z'}})
r(b'NSPrintInfo', b'isSelectionOnly', {'retval': {'type': 'Z'}})
r(b'NSPrintInfo', b'isVerticallyCentered', {'retval': {'type': 'Z'}})
r(b'NSPrintInfo', b'paperSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSPrintInfo', b'setHorizontallyCentered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPrintInfo', b'setPaperSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSPrintInfo', b'setSelectionOnly:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPrintInfo', b'setVerticallyCentered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPrintInfo', b'sizeForPaperName:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSPrintOperation', b'EPSOperationWithView:insideRect:toData:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPrintOperation', b'EPSOperationWithView:insideRect:toData:printInfo:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPrintOperation', b'EPSOperationWithView:insideRect:toPath:printInfo:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPrintOperation', b'PDFOperationWithView:insideRect:toData:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPrintOperation', b'PDFOperationWithView:insideRect:toData:printInfo:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPrintOperation', b'PDFOperationWithView:insideRect:toPath:printInfo:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSPrintOperation', b'canSpawnSeparateThread', {'retval': {'type': 'Z'}})
r(b'NSPrintOperation', b'deliverResult', {'retval': {'type': 'Z'}})
r(b'NSPrintOperation', b'isCopyingOperation', {'retval': {'type': 'Z'}})
r(b'NSPrintOperation', b'pageRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSPrintOperation', b'runOperation', {'retval': {'type': 'Z'}})
r(b'NSPrintOperation', b'runOperationModalForWindow:delegate:didRunSelector:contextInfo:', {'arguments': {4: {'sel_of_type': b'v@:@Z^v'}, 5: {'type': '^v'}}})
r(b'NSPrintOperation', b'setCanSpawnSeparateThread:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPrintOperation', b'setShowPanels:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPrintOperation', b'setShowsPrintPanel:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPrintOperation', b'setShowsProgressPanel:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSPrintOperation', b'showPanels', {'retval': {'type': 'Z'}})
r(b'NSPrintOperation', b'showsPrintPanel', {'retval': {'type': 'Z'}})
r(b'NSPrintOperation', b'showsProgressPanel', {'retval': {'type': 'Z'}})
r(b'NSPrintPanel', b'beginSheetWithPrintInfo:modalForWindow:delegate:didEndSelector:contextInfo:', {'arguments': {5: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 6: {'type': '^v'}}})
r(b'NSPrinter', b'acceptsBinary', {'retval': {'type': 'Z'}})
r(b'NSPrinter', b'booleanForKey:inTable:', {'retval': {'type': 'Z'}})
r(b'NSPrinter', b'imageRectForPaper:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSPrinter', b'isColor', {'retval': {'type': 'Z'}})
r(b'NSPrinter', b'isFontAvailable:', {'retval': {'type': 'Z'}})
r(b'NSPrinter', b'isKey:inTable:', {'retval': {'type': 'Z'}})
r(b'NSPrinter', b'isOutputStackInReverseOrder', {'retval': {'type': 'Z'}})
r(b'NSPrinter', b'pageSizeForPaper:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSPrinter', b'printerWithName:domain:includeUnavailable:', {'arguments': {4: {'type': 'Z'}}})
r(b'NSPrinter', b'rectForKey:inTable:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSPrinter', b'sizeForKey:inTable:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSProgressIndicator', b'isBezeled', {'retval': {'type': 'Z'}})
r(b'NSProgressIndicator', b'isDisplayedWhenStopped', {'retval': {'type': 'Z'}})
r(b'NSProgressIndicator', b'isIndeterminate', {'retval': {'type': 'Z'}})
r(b'NSProgressIndicator', b'setBezeled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSProgressIndicator', b'setDisplayedWhenStopped:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSProgressIndicator', b'setIndeterminate:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSProgressIndicator', b'setUsesThreadedAnimation:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSProgressIndicator', b'usesThreadedAnimation', {'retval': {'type': 'Z'}})
r(b'NSQuickDrawView', b'qdPort', {'retval': {'type': '^v'}})
r(b'NSResponder', b'acceptsFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSResponder', b'becomeFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSResponder', b'doCommandBySelector:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSResponder', b'noResponderFor:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSResponder', b'performKeyEquivalent:', {'retval': {'type': 'Z'}})
r(b'NSResponder', b'performMnemonic:', {'retval': {'type': 'Z'}})
r(b'NSResponder', b'presentError:', {'retval': {'type': 'Z'}})
r(b'NSResponder', b'presentError:modalForWindow:delegate:didPresentSelector:contextInfo:', {'arguments': {5: {'sel_of_type': b'v@:Z^v'}, 6: {'type': '^v'}}})
r(b'NSResponder', b'resignFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSResponder', b'shouldBeTreatedAsInkEvent:', {'retval': {'type': 'Z'}})
r(b'NSResponder', b'supplementalTargetForAction:sender:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSResponder', b'tryToPerform:with:', {'retval': {'type': 'Z'}, 'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSResponder', b'validateProposedFirstResponder:forEvent:', {'retval': {'type': b'Z'}})
r(b'NSResponder', b'wantsForwardedScrollEventsForAxis:', {'retval': {'type': b'Z'}})
r(b'NSResponder', b'wantsScrollEventsForSwipeTrackingOnAxis:', {'retval': {'type': b'Z'}})
r(b'NSRuleEditor', b'canRemoveAllRows', {'retval': {'type': 'Z'}})
r(b'NSRuleEditor', b'insertRowAtIndex:withType:asSubrowOfRow:animate:', {'arguments': {5: {'type': 'Z'}}})
r(b'NSRuleEditor', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSRuleEditor', b'removeRowsAtIndexes:includeSubrows:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSRuleEditor', b'selectRowIndexes:byExtendingSelection:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSRuleEditor', b'setCanRemoveAllRows:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSRuleEditor', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSRulerMarker', b'drawRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSRulerMarker', b'imageOrigin', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSRulerMarker', b'imageRectInRuler', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSRulerMarker', b'initWithRulerView:markerLocation:image:imageOrigin:', {'arguments': {5: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSRulerMarker', b'isDragging', {'retval': {'type': 'Z'}})
r(b'NSRulerMarker', b'isMovable', {'retval': {'type': 'Z'}})
r(b'NSRulerMarker', b'isRemovable', {'retval': {'type': 'Z'}})
r(b'NSRulerMarker', b'setImageOrigin:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSRulerMarker', b'setMovable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSRulerMarker', b'setRemovable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSRulerMarker', b'trackMouse:adding:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': 'Z'}}})
r(b'NSRulerView', b'drawHashMarksAndLabelsInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSRulerView', b'drawMarkersInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSRulerView', b'isFlipped', {'retval': {'type': 'Z'}})
r(b'NSRulerView', b'trackMarker:withMouseEvent:', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'activateWithOptions:', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'forceTerminate', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'hide', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'isActive', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'isFinishedLaunching', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'isTerminated', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'ownsMenuBar', {'retval': {'type': b'Z'}})
r(b'NSRunningApplication', b'terminate', {'retval': {'type': 'Z'}})
r(b'NSRunningApplication', b'unhide', {'retval': {'type': 'Z'}})
r(b'NSSavePanel', b'allowsOtherFileTypes', {'retval': {'type': 'Z'}})
r(b'NSSavePanel', b'beginForDirectory:file:types:modelessDelegate:didEndSelector:contextInfo:', {'arguments': {6: {'type': ':', 'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 7: {'type': '^v'}}})
r(b'NSSavePanel', b'beginSheetForDirectory:file:modalForWindow:modalDelegate:didEndSelector:contextInfo:', {'arguments': {6: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 7: {'type': '^v'}}})
r(b'NSSavePanel', b'beginSheetForDirectory:file:types:modalForWindow:modalDelegate:didEndSelector:contextInfo:', {'arguments': {7: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}, 8: {'type': '^v'}}})
r(b'NSSavePanel', b'beginSheetModalForWindow:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSSavePanel', b'beginWithCompletionHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSSavePanel', b'canCreateDirectories', {'retval': {'type': 'Z'}})
r(b'NSSavePanel', b'canSelectHiddenExtension', {'retval': {'type': 'Z'}})
r(b'NSSavePanel', b'isExpanded', {'retval': {'type': 'Z'}})
r(b'NSSavePanel', b'isExtensionHidden', {'retval': {'type': 'Z'}})
r(b'NSSavePanel', b'setAllowsOtherFileTypes:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSavePanel', b'setCanCreateDirectories:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSavePanel', b'setCanSelectHiddenExtension:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSavePanel', b'setExtensionHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSavePanel', b'setShowsHiddenFiles:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSavePanel', b'setShowsTagField:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSSavePanel', b'setTreatsFilePackagesAsDirectories:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSavePanel', b'showsHiddenFiles', {'retval': {'type': 'Z'}})
r(b'NSSavePanel', b'showsTagField', {'retval': {'type': b'Z'}})
r(b'NSSavePanel', b'treatsFilePackagesAsDirectories', {'retval': {'type': 'Z'}})
r(b'NSScreen', b'canRepresentDisplayGamut:', {'retval': {'type': 'Z'}})
r(b'NSScreen', b'frame', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSScreen', b'screensHaveSeparateSpaces', {'retval': {'type': b'Z'}})
r(b'NSScreen', b'supportedWindowDepths', {'retval': {'c_array_delimited_by_null': True}})
r(b'NSScreen', b'visibleFrame', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSScrollView', b'allowsMagnification', {'retval': {'type': b'Z'}})
r(b'NSScrollView', b'autohidesScrollers', {'retval': {'type': 'Z'}})
r(b'NSScrollView', b'automaticallyAdjustsContentInsets', {'retval': {'type': b'Z'}})
r(b'NSScrollView', b'contentSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSScrollView', b'contentSizeForFrameSize:hasHorizontalScroller:hasVerticalScroller:borderType:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 3: {'type': 'Z'}, 4: {'type': 'Z'}}})
r(b'NSScrollView', b'documentVisibleRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSScrollView', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSScrollView', b'frameSizeForContentSize:hasHorizontalScroller:hasVerticalScroller:borderType:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 3: {'type': 'Z'}, 4: {'type': 'Z'}}})
r(b'NSScrollView', b'hasHorizontalRuler', {'retval': {'type': 'Z'}})
r(b'NSScrollView', b'hasHorizontalScroller', {'retval': {'type': 'Z'}})
r(b'NSScrollView', b'hasVerticalRuler', {'retval': {'type': 'Z'}})
r(b'NSScrollView', b'hasVerticalScroller', {'retval': {'type': 'Z'}})
r(b'NSScrollView', b'rulersVisible', {'retval': {'type': 'Z'}})
r(b'NSScrollView', b'scrollsDynamically', {'retval': {'type': 'Z'}})
r(b'NSScrollView', b'setAllowsMagnification:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSScrollView', b'setAutohidesScrollers:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrollView', b'setAutomaticallyAdjustsContentInsets:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSScrollView', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrollView', b'setHasHorizontalRuler:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrollView', b'setHasHorizontalScroller:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrollView', b'setHasVerticalRuler:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrollView', b'setHasVerticalScroller:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrollView', b'setRulersVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrollView', b'setScrollsDynamically:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrollView', b'setUsesPredominantAxisScrolling:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSScrollView', b'usesPredominantAxisScrolling', {'retval': {'type': b'Z'}})
r(b'NSScroller', b'drawArrow:highlight:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSScroller', b'drawKnobSlotInRect:highlight:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': 'Z'}}})
r(b'NSScroller', b'highlight:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScroller', b'isCompatibleWithOverlayScrollers', {'retval': {'type': b'Z'}})
r(b'NSScroller', b'rectForPart:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSScroller', b'testPart:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSScrubber', b'floatsSelectionViews', {'retval': {'type': 'Z'}})
r(b'NSScrubber', b'isContinuous', {'retval': {'type': 'Z'}})
r(b'NSScrubber', b'performSequentialBatchUpdates:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSScrubber', b'setContinuous:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrubber', b'setFloatsSelectionViews:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrubber', b'setShowsAdditionalContentIndicators:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrubber', b'setShowsArrowButtons:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrubber', b'showsAdditionalContentIndicators', {'retval': {'type': 'Z'}})
r(b'NSScrubber', b'showsArrowButtons', {'retval': {'type': 'Z'}})
r(b'NSScrubberArrangedView', b'isHighlighted', {'retval': {'type': 'Z'}})
r(b'NSScrubberArrangedView', b'isSelected', {'retval': {'type': 'Z'}})
r(b'NSScrubberArrangedView', b'setHighlighted:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrubberArrangedView', b'setSelected:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSScrubberLayout', b'automaticallyMirrorsInRightToLeftLayout', {'retval': {'type': 'Z'}})
r(b'NSScrubberLayout', b'shouldInvalidateLayoutForChangeFromVisibleRect:toVisibleRect:', {'retval': {'type': 'Z'}})
r(b'NSScrubberLayout', b'shouldInvalidateLayoutForHighlightChange', {'retval': {'type': 'Z'}})
r(b'NSScrubberLayout', b'shouldInvalidateLayoutForSelectionChange', {'retval': {'type': 'Z'}})
r(b'NSSearchField', b'centersPlaceholder', {'retval': {'type': 'Z'}})
r(b'NSSearchField', b'rectForCancelButtonWhenCentered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSearchField', b'rectForSearchButtonWhenCentered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSearchField', b'rectForSearchTextWhenCentered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSearchField', b'sendsSearchStringImmediately', {'retval': {'type': b'Z'}})
r(b'NSSearchField', b'sendsWholeSearchString', {'retval': {'type': b'Z'}})
r(b'NSSearchField', b'setCentersPlaceholder:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSearchField', b'setSendsSearchStringImmediately:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSSearchField', b'setSendsWholeSearchString:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSSearchFieldCell', b'cancelButtonRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSSearchFieldCell', b'searchButtonRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSSearchFieldCell', b'searchTextRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSSearchFieldCell', b'sendsSearchStringImmediately', {'retval': {'type': 'Z'}})
r(b'NSSearchFieldCell', b'sendsWholeSearchString', {'retval': {'type': 'Z'}})
r(b'NSSearchFieldCell', b'setSendsSearchStringImmediately:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSearchFieldCell', b'setSendsWholeSearchString:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSecureTextFieldCell', b'echosBullets', {'retval': {'type': 'Z'}})
r(b'NSSecureTextFieldCell', b'setEchosBullets:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSegmentedCell', b'drawSegment:inFrame:withView:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSSegmentedCell', b'isEnabledForSegment:', {'retval': {'type': 'Z'}})
r(b'NSSegmentedCell', b'isSelectedForSegment:', {'retval': {'type': 'Z'}})
r(b'NSSegmentedCell', b'selectSegmentWithTag:', {'retval': {'type': 'Z'}})
r(b'NSSegmentedCell', b'setEnabled:forSegment:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSegmentedCell', b'setSelected:forSegment:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSegmentedControl', b'isEnabledForSegment:', {'retval': {'type': 'Z'}})
r(b'NSSegmentedControl', b'isSelectedForSegment:', {'retval': {'type': 'Z'}})
r(b'NSSegmentedControl', b'isSpringLoaded', {'retval': {'type': b'Z'}})
r(b'NSSegmentedControl', b'segmentedControlWithImages:trackingMode:target:action:', {'arguments': {5: {'sel_of_type': b'v@:@'}}})
r(b'NSSegmentedControl', b'segmentedControlWithLabels:trackingMode:target:action:', {'arguments': {5: {'sel_of_type': b'v@:@'}}})
r(b'NSSegmentedControl', b'selectSegmentWithTag:', {'retval': {'type': 'Z'}})
r(b'NSSegmentedControl', b'setEnabled:forSegment:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSegmentedControl', b'setSelected:forSegment:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSegmentedControl', b'setShowsMenuIndicator:forSegment:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSegmentedControl', b'setSpringLoaded:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSSegmentedControl', b'showsMenuIndicatorForSegment:', {'retval': {'type': 'Z'}})
r(b'NSSet', b'enumerateIndexPathsWithOptions:usingBlock:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'o^Z'}}}}}})
r(b'NSShadow', b'setShadowOffset:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSShadow', b'shadowOffset', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSSharingService', b'canPerformWithItems:', {'retval': {'type': b'Z'}})
r(b'NSSharingService', b'initWithTitle:image:alternateImage:handler:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSSharingServicePickerTouchBarItem', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSSharingServicePickerTouchBarItem', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSimpleHorizontalTypesetter', b'baseOfTypesetterGlyphInfo', {'retval': {'type': b'^{_NSTypesetterGlyphInfo={_NSPoint=ff}fffI@{_NSSize=ff}{_struct _NSTypesetterGlyphInfo::(anonymous at /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/AppKit.framework/Headers/NSSimpleHorizontalTypesetter.h:58:5)=b1b1b1}{=b1b1b1}}'}})
r(b'NSSimpleHorizontalTypesetter', b'growGlyphCaches:fillGlyphInfo:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSSimpleHorizontalTypesetter', b'layoutControlGlyphForLineFragment:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSSimpleHorizontalTypesetter', b'layoutGlyphsInHorizontalLineFragment:baseline:', {'arguments': {2: {'type_modifier': b'N'}, 3: {'type_modifier': b'N'}}})
r(b'NSSimpleHorizontalTypesetter', b'layoutGlyphsInLayoutManager:startingAtGlyphIndex:maxNumberOfLineFragments:nextGlyphIndex:', {'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSSimpleHorizontalTypesetter', b'typesetterLaidOneGlyph:', {'arguments': {2: {'type': b'^{_NSTypesetterGlyphInfo={_NSPoint=ff}fffI@{_NSSize=ff}{_struct _NSTypesetterGlyphInfo::(anonymous at /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/AppKit.framework/Headers/NSSimpleHorizontalTypesetter.h:58:5)=b1b1b1}{=b1b1b1}}', 'type_modifier': b'N'}}})
r(b'NSSimpleHorizontalTypesetter', b'willSetLineFragmentRect:forGlyphRange:usedRect:', {'arguments': {2: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}}})
r(b'NSSlider', b'acceptsFirstMouse:', {'retval': {'type': 'Z'}})
r(b'NSSlider', b'allowsTickMarkValuesOnly', {'retval': {'type': 'Z'}})
r(b'NSSlider', b'indexOfTickMarkAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSSlider', b'isVertical', {'retval': {'type': 'Z'}})
r(b'NSSlider', b'rectOfTickMarkAtIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSSlider', b'setAllowsTickMarkValuesOnly:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSlider', b'setVertical:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSlider', b'sliderWithValue:minValue:maxValue:target:action:', {'arguments': {6: {'sel_of_type': b'v@:@'}}})
r(b'NSSliderAccessory', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSSliderAccessory', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSliderAccessoryBehavior', b'behaviorWithHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSSliderCell', b'allowsTickMarkValuesOnly', {'retval': {'type': 'Z'}})
r(b'NSSliderCell', b'barRectFlipped:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSSliderCell', b'drawBarInside:flipped:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': 'Z'}}})
r(b'NSSliderCell', b'drawKnob:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSSliderCell', b'indexOfTickMarkAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSSliderCell', b'isVertical', {'retval': {'type': 'Z'}})
r(b'NSSliderCell', b'knobRectFlipped:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSSliderCell', b'prefersTrackingUntilMouseUp', {'retval': {'type': 'Z'}})
r(b'NSSliderCell', b'rectOfTickMarkAtIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'i', b'q')}}})
r(b'NSSliderCell', b'setAllowsTickMarkValuesOnly:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSliderCell', b'setVertical:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSliderCell', b'trackRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSSound', b'canInitWithPasteboard:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': '@'}}})
r(b'NSSound', b'initWithContentsOfFile:byReference:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSSound', b'initWithContentsOfURL:byReference:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSSound', b'isPlaying', {'retval': {'type': 'Z'}})
r(b'NSSound', b'loops', {'retval': {'type': 'Z'}})
r(b'NSSound', b'name', {'retval': {'type': '@'}})
r(b'NSSound', b'pause', {'retval': {'type': 'Z'}})
r(b'NSSound', b'play', {'retval': {'type': 'Z'}})
r(b'NSSound', b'resume', {'retval': {'type': 'Z'}})
r(b'NSSound', b'setLoops:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSound', b'setName:', {'retval': {'type': 'Z'}})
r(b'NSSound', b'stop', {'retval': {'type': 'Z'}})
r(b'NSSpeechRecognizer', b'blocksOtherRecognizers', {'retval': {'type': 'Z'}})
r(b'NSSpeechRecognizer', b'listensInForegroundOnly', {'retval': {'type': 'Z'}})
r(b'NSSpeechRecognizer', b'setBlocksOtherRecognizers:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSpeechRecognizer', b'setListensInForegroundOnly:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSpeechSynthesizer', b'isAnyApplicationSpeaking', {'retval': {'type': 'Z'}})
r(b'NSSpeechSynthesizer', b'isSpeaking', {'retval': {'type': 'Z'}})
r(b'NSSpeechSynthesizer', b'objectForProperty:error:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSSpeechSynthesizer', b'setObject:forProperty:error:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type_modifier': b'o'}}})
r(b'NSSpeechSynthesizer', b'setUsesFeedbackWindow:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSpeechSynthesizer', b'setVoice:', {'retval': {'type': 'Z'}})
r(b'NSSpeechSynthesizer', b'startSpeakingString:', {'retval': {'type': 'Z'}})
r(b'NSSpeechSynthesizer', b'startSpeakingString:toURL:', {'retval': {'type': 'Z'}})
r(b'NSSpeechSynthesizer', b'usesFeedbackWindow', {'retval': {'type': 'Z'}})
r(b'NSSpeechSynthesizer', b'voice', {'retval': {'type': '@'}})
r(b'NSSpellChecker', b'automaticallyIdentifiesLanguages', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'checkGrammarOfString:startingAt:language:wrap:inSpellDocumentWithTag:details:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {5: {'type': 'Z'}, 7: {'type_modifier': b'o'}}})
r(b'NSSpellChecker', b'checkSpellingOfString:startingAt:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSSpellChecker', b'checkSpellingOfString:startingAt:language:wrap:inSpellDocumentWithTag:wordCount:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {5: {'type': 'Z'}, 7: {'type_modifier': b'o'}}})
r(b'NSSpellChecker', b'checkString:range:types:options:inSpellDocumentWithTag:orthography:wordCount:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 7: {'type_modifier': b'o'}, 8: {'type_modifier': b'o'}}})
r(b'NSSpellChecker', b'completionsForPartialWordRange:inString:language:inSpellDocumentWithTag:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSSpellChecker', b'deletesAutospaceBetweenString:andString:language:', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'hasLearnedWord:', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'isAutomaticCapitalizationEnabled', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'isAutomaticDashSubstitutionEnabled', {'retval': {'type': b'Z'}})
r(b'NSSpellChecker', b'isAutomaticPeriodSubstitutionEnabled', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'isAutomaticQuoteSubstitutionEnabled', {'retval': {'type': b'Z'}})
r(b'NSSpellChecker', b'isAutomaticSpellingCorrectionEnabled', {'retval': {'type': b'Z'}})
r(b'NSSpellChecker', b'isAutomaticTextCompletionEnabled', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'isAutomaticTextReplacementEnabled', {'retval': {'type': b'Z'}})
r(b'NSSpellChecker', b'preventsAutocorrectionBeforeString:language:', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'requestCandidatesForSelectedRange:inString:types:options:inSpellDocumentWithTag:completionHandler:', {'arguments': {7: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}, 2: {'type': b'@'}}}}}})
r(b'NSSpellChecker', b'requestCheckingOfString:range:types:options:inSpellDocumentWithTag:completionHandler:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 7: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}, 2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSSpellChecker', b'setAutomaticallyIdentifiesLanguages:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSpellChecker', b'setLanguage:', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'sharedSpellCheckerExists', {'retval': {'type': 'Z'}})
r(b'NSSpellChecker', b'showCorrectionIndicatorOfType:primaryString:alternativeStrings:forStringInRect:view:completionHandler:', {'arguments': {7: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}}}}}})
r(b'NSSpellChecker', b'unlearnWord:', {'arguments': {2: {'type': '@'}}})
r(b'NSSplitView', b'arrangesAllSubviews', {'retval': {'type': 'Z'}})
r(b'NSSplitView', b'drawDividerInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSSplitView', b'isPaneSplitter', {'retval': {'type': 'Z'}})
r(b'NSSplitView', b'isSpringLoaded', {'retval': {'type': 'Z'}})
r(b'NSSplitView', b'isSubviewCollapsed:', {'retval': {'type': 'Z'}})
r(b'NSSplitView', b'isVertical', {'retval': {'type': 'Z'}})
r(b'NSSplitView', b'setArrangesAllSubviews:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSplitView', b'setIsPaneSplitter:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSplitView', b'setVertical:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSSplitViewController', b'splitView:canCollapseSubview:', {'retval': {'type': b'Z'}})
r(b'NSSplitViewController', b'splitView:shouldCollapseSubview:forDoubleClickOnDividerAtIndex:', {'retval': {'type': b'Z'}})
r(b'NSSplitViewController', b'splitView:shouldHideDividerAtIndex:', {'retval': {'type': b'Z'}})
r(b'NSSplitViewController', b'validateUserInterfaceItem:', {'retval': {'type': 'Z'}})
r(b'NSSplitViewItem', b'canCollapse', {'retval': {'type': b'Z'}})
r(b'NSSplitViewItem', b'isCollapsed', {'retval': {'type': b'Z'}})
r(b'NSSplitViewItem', b'isSpringLoaded', {'retval': {'type': 'Z'}})
r(b'NSSplitViewItem', b'setCanCollapse:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSSplitViewItem', b'setCollapsed:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSSplitViewItem', b'setSpringLoaded:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStackView', b'detachesHiddenViews', {'retval': {'type': 'Z'}})
r(b'NSStackView', b'hasEqualSpacing', {'retval': {'type': b'Z'}})
r(b'NSStackView', b'setDetachesHiddenViews:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStackView', b'setHasEqualSpacing:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSStatusBar', b'isVertical', {'retval': {'type': 'Z'}})
r(b'NSStatusBarButton', b'appearsDisabled', {'retval': {'type': b'Z'}})
r(b'NSStatusBarButton', b'setAppearsDisabled:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSStatusItem', b'drawStatusBarBackgroundInRect:withHighlight:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': 'Z'}}})
r(b'NSStatusItem', b'highlightMode', {'retval': {'type': 'Z'}})
r(b'NSStatusItem', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSStatusItem', b'isVisible', {'retval': {'type': 'Z'}})
r(b'NSStatusItem', b'setAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSStatusItem', b'setDoubleAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSStatusItem', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStatusItem', b'setHighlightMode:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStatusItem', b'setVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStepper', b'autorepeat', {'retval': {'type': 'Z'}})
r(b'NSStepper', b'setAutorepeat:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStepper', b'setValueWraps:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStepper', b'valueWraps', {'retval': {'type': 'Z'}})
r(b'NSStepperCell', b'autorepeat', {'retval': {'type': 'Z'}})
r(b'NSStepperCell', b'setAutorepeat:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStepperCell', b'setValueWraps:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSStepperCell', b'valueWraps', {'retval': {'type': 'Z'}})
r(b'NSStoryboardSegue', b'initWithIdentifier:source:destination:performHandler:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSStoryboardSegue', b'performHandler', {'retval': {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}})
r(b'NSStoryboardSegue', b'segueWithIdentifier:source:destination:performHandler:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSStoryboardSegue', b'setPerformHandler:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSString', b'boundingRectWithSize:options:attributes:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSString', b'drawAtPoint:withAttributes:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSString', b'drawInRect:withAttributes:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSString', b'drawWithRect:options:attributes:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSString', b'sizeWithAttributes:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSTabView', b'allowsTruncatedLabels', {'retval': {'type': 'Z'}})
r(b'NSTabView', b'contentRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSTabView', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSTabView', b'minimumSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSTabView', b'setAllowsTruncatedLabels:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTabView', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTabView', b'tabViewItemAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSTabViewController', b'canPropagateSelectedChildViewControllerTitle', {'retval': {'type': b'Z'}})
r(b'NSTabViewController', b'setCanPropagateSelectedChildViewControllerTitle:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTabViewController', b'tabView:shouldSelectTabViewItem:', {'retval': {'type': b'Z'}})
r(b'NSTabViewController', b'toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:', {'arguments': {4: {'type': b'Z'}}})
r(b'NSTabViewItem', b'drawLabel:inRect:', {'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTabViewItem', b'sizeOfLabel:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': 'Z'}}})
r(b'NSTableColumn', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSTableColumn', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSTableColumn', b'isResizable', {'retval': {'type': 'Z'}})
r(b'NSTableColumn', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableColumn', b'setHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableColumn', b'setResizable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableHeaderCell', b'drawSortIndicatorWithFrame:inView:ascending:priority:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': 'Z'}}})
r(b'NSTableHeaderCell', b'sortIndicatorRectForBounds:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTableHeaderView', b'columnAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSTableHeaderView', b'headerRectOfColumn:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSTableRowView', b'isEmphasized', {'retval': {'type': b'Z'}})
r(b'NSTableRowView', b'isFloating', {'retval': {'type': b'Z'}})
r(b'NSTableRowView', b'isGroupRowStyle', {'retval': {'type': b'Z'}})
r(b'NSTableRowView', b'isNextRowSelected', {'retval': {'type': b'Z'}})
r(b'NSTableRowView', b'isPreviousRowSelected', {'retval': {'type': b'Z'}})
r(b'NSTableRowView', b'isSelected', {'retval': {'type': b'Z'}})
r(b'NSTableRowView', b'isTargetForDropOperation', {'retval': {'type': b'Z'}})
r(b'NSTableRowView', b'setEmphasized:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableRowView', b'setFloating:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableRowView', b'setGroupRowStyle:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableRowView', b'setNextRowSelected:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableRowView', b'setPreviousRowSelected:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableRowView', b'setSelected:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableRowView', b'setTargetForDropOperation:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableView', b'allowsColumnReordering', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'allowsColumnResizing', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'allowsColumnSelection', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'allowsEmptySelection', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'allowsMultipleSelection', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'allowsTypeSelect', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'autoresizesAllColumnsToFit', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'autosaveTableColumns', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'canDragRowsWithIndexes:atPoint:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSTableView', b'columnAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSTableView', b'columnIndexesInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTableView', b'columnsInRect:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTableView', b'dragImageForRows:event:dragImageOffset:', {'arguments': {4: {'type_modifier': b'N'}}})
r(b'NSTableView', b'dragImageForRowsWithIndexes:tableColumns:event:offset:', {'arguments': {5: {'type_modifier': b'N'}}})
r(b'NSTableView', b'drawBackgroundInClipRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTableView', b'drawGridInClipRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTableView', b'drawRow:clipRect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTableView', b'drawsGrid', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'editColumn:row:withEvent:select:', {'arguments': {5: {'type': 'Z'}}})
r(b'NSTableView', b'enumerateAvailableRowViewsUsingBlock:', {'arguments': {2: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSTableView', b'floatsGroupRows', {'retval': {'type': b'Z'}})
r(b'NSTableView', b'frameOfCellAtColumn:row:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSTableView', b'highlightSelectionInClipRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTableView', b'intercellSpacing', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSTableView', b'isColumnSelected:', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'isRowSelected:', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'rectOfColumn:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSTableView', b'rectOfRow:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSTableView', b'rowActionsVisible', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'rowAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSTableView', b'rowViewAtRow:makeIfNecessary:', {'arguments': {3: {'type': b'Z'}}})
r(b'NSTableView', b'rowsInRect:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTableView', b'selectColumn:byExtendingSelection:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSTableView', b'selectColumnIndexes:byExtendingSelection:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSTableView', b'selectRow:byExtendingSelection:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSTableView', b'selectRowIndexes:byExtendingSelection:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSTableView', b'setAllowsColumnReordering:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setAllowsColumnResizing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setAllowsColumnSelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setAllowsEmptySelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setAllowsMultipleSelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setAllowsTypeSelect:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setAutoresizesAllColumnsToFit:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setAutosaveTableColumns:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setDoubleAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSTableView', b'setDraggingSourceOperationMask:forLocal:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSTableView', b'setDrawsGrid:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setFloatsGroupRows:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableView', b'setIntercellSpacing:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSTableView', b'setRowActionsVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setUsesAlternatingRowBackgroundColors:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setUsesAutomaticRowHeights:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'setUsesStaticContents:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTableView', b'setVerticalMotionCanBeginDrag:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTableView', b'shouldFocusCell:atColumn:row:', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'textShouldBeginEditing:', {'retval': {'type': b'Z'}})
r(b'NSTableView', b'textShouldEndEditing:', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'usesAlternatingRowBackgroundColors', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'usesAutomaticRowHeights', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'usesStaticContents', {'retval': {'type': b'Z'}})
r(b'NSTableView', b'verticalMotionCanBeginDrag', {'retval': {'type': 'Z'}})
r(b'NSTableView', b'viewAtColumn:row:makeIfNecessary:', {'arguments': {4: {'type': b'Z'}}})
r(b'NSText', b'RTFDFromRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'RTFFromRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSText', b'importsGraphics', {'retval': {'type': 'Z'}})
r(b'NSText', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSText', b'isFieldEditor', {'retval': {'type': 'Z'}})
r(b'NSText', b'isHorizontallyResizable', {'retval': {'type': 'Z'}})
r(b'NSText', b'isRichText', {'retval': {'type': 'Z'}})
r(b'NSText', b'isRulerVisible', {'retval': {'type': 'Z'}})
r(b'NSText', b'isSelectable', {'retval': {'type': 'Z'}})
r(b'NSText', b'isVerticallyResizable', {'retval': {'type': 'Z'}})
r(b'NSText', b'maxSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSText', b'minSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSText', b'readRTFDFromFile:', {'retval': {'type': 'Z'}})
r(b'NSText', b'replaceCharactersInRange:withRTF:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'replaceCharactersInRange:withRTFD:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'replaceCharactersInRange:withString:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'scrollRangeToVisible:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'selectedRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSText', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'setFieldEditor:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'setFont:range:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'setHorizontallyResizable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'setImportsGraphics:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'setMaxSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSText', b'setMinSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSText', b'setRichText:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'setSelectable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'setSelectedRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'setTextColor:range:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSText', b'setUsesFontPanel:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'setVerticallyResizable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSText', b'usesFontPanel', {'retval': {'type': 'Z'}})
r(b'NSText', b'writeRTFDToFile:atomically:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': 'Z'}}})
r(b'NSTextBlock', b'boundsRectForContentRect:inRect:textContainer:characterRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextBlock', b'drawBackgroundWithFrame:inView:characterRange:layoutManager:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextBlock', b'rectForLayoutAtPoint:inRect:textContainer:characterRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextContainer', b'containerSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSTextContainer', b'containsPoint:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSTextContainer', b'heightTracksTextView', {'retval': {'type': 'Z'}})
r(b'NSTextContainer', b'initWithContainerSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSTextContainer', b'isSimpleRectangularTextContainer', {'retval': {'type': 'Z'}})
r(b'NSTextContainer', b'lineFragmentRectForProposedRect:atIndex:writingDirection:remainingRect', {'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSTextContainer', b'lineFragmentRectForProposedRect:atIndex:writingDirection:remainingRect:', {'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSTextContainer', b'lineFragmentRectForProposedRect:sweepDirection:movementDirection:remainingRect:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type_modifier': b'o'}}})
r(b'NSTextContainer', b'setContainerSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSTextContainer', b'setHeightTracksTextView:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextContainer', b'setWidthTracksTextView:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextContainer', b'widthTracksTextView', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'acceptsFirstResponder', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'allowsCharacterPickerTouchBarItem', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'allowsDefaultTighteningForTruncation', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'allowsEditingTextAttributes', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'importsGraphics', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'isAutomaticTextCompletionEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'isBezeled', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'isBordered', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'isSelectable', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'setAllowsCharacterPickerTouchBarItem:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setAllowsDefaultTighteningForTruncation:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setAllowsEditingTextAttributes:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setAutomaticTextCompletionEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setBezeled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setBordered:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setImportsGraphics:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setSelectable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextField', b'setTextColor:', {'arguments': {2: {'type': '@'}}})
r(b'NSTextField', b'textShouldBeginEditing:', {'retval': {'type': 'Z'}})
r(b'NSTextField', b'textShouldEndEditing:', {'retval': {'type': 'Z'}})
r(b'NSTextFieldCell', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSTextFieldCell', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextFieldCell', b'setWantsNotificationForMarkedText:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextFinder', b'findIndicatorNeedsUpdate', {'retval': {'type': b'Z'}})
r(b'NSTextFinder', b'incrementalSearchingShouldDimContentView', {'retval': {'type': b'Z'}})
r(b'NSTextFinder', b'isIncrementalSearchingEnabled', {'retval': {'type': b'Z'}})
r(b'NSTextFinder', b'setFindIndicatorNeedsUpdate:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTextFinder', b'setIncrementalSearchingEnabled:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTextFinder', b'setIncrementalSearchingShouldDimContentView:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTextFinder', b'validateAction:', {'retval': {'type': b'Z'}})
r(b'NSTextInputContext', b'acceptsGlyphInfo', {'retval': {'type': 'Z'}})
r(b'NSTextInputContext', b'handleEvent:', {'retval': {'type': 'Z'}})
r(b'NSTextInputContext', b'setAcceptsGlyphInfo:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextStorage', b'edited:range:changeInLength:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextStorage', b'editedRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTextStorage', b'ensureAttributesAreFixedInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextStorage', b'fixesAttributesLazily', {'retval': {'type': 'Z'}})
r(b'NSTextStorage', b'invalidateAttributesInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextTable', b'boundsRectForBlock:contentRect:inRect:textContainer:characterRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 6: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextTable', b'collapsesBorders', {'retval': {'type': 'Z'}})
r(b'NSTextTable', b'drawBackgroundForBlock:withFrame:inView:characterRange:layoutManager:', {'retval': {'type': 'v'}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextTable', b'hidesEmptyCells', {'retval': {'type': 'Z'}})
r(b'NSTextTable', b'rectForBlock:layoutAtPoint:inRect:textContainer:characterRange:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 6: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextTable', b'setCollapsesBorders:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextTable', b'setHidesEmptyCells:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'acceptsGlyphInfo', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'allowsCharacterPickerTouchBarItem', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'allowsDocumentBackgroundColorChange', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'allowsImageEditing', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'allowsUndo', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'characterIndexForInsertionAtPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSTextView', b'completionsForPartialWordRange:indexOfSelectedItem:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o'}}})
r(b'NSTextView', b'displaysLinkToolTips', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'dragImageForSelectionWithEvent:origin:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSTextView', b'dragSelectionWithEvent:offset:slideBack:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 4: {'type': 'Z'}}})
r(b'NSTextView', b'drawInsertionPointInRect:color:turnedOn:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': 'Z'}}})
r(b'NSTextView', b'drawViewBackgroundInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTextView', b'drawsBackground', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'importsGraphics', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'initWithFrame:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTextView', b'initWithFrame:textContainer:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTextView', b'insertCompletion:forPartialWordRange:movement:isFinal:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': 'Z'}}})
r(b'NSTextView', b'isAutomaticDashSubstitutionEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isAutomaticDataDetectionEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isAutomaticLinkDetectionEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isAutomaticQuoteSubstitutionEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isAutomaticSpellingCorrectionEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isAutomaticTextReplacementEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isCoalescingUndo', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isContinuousSpellCheckingEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isEditable', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isFieldEditor', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isGrammarCheckingEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isIncrementalSearchingEnabled', {'retval': {'type': b'Z'}})
r(b'NSTextView', b'isRichText', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isRulerVisible', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'isSelectable', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'rangeForUserCharacterAttributeChange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTextView', b'rangeForUserCompletion', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTextView', b'rangeForUserParagraphAttributeChange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTextView', b'rangeForUserTextChange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTextView', b'readSelectionFromPasteboard:', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'readSelectionFromPasteboard:type:', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'rulerView:shouldAddMarker:', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'rulerView:shouldMoveMarker:', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'rulerView:shouldRemoveMarker:', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'rulerView:willMoveMarker:toLocation:', {'retval': {'type': sel32or64(b'f', b'd')}, 'arguments': {4: {'type': sel32or64(b'f', b'd')}}})
r(b'NSTextView', b'selectionRangeForProposedRange:granularity:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'setAcceptsGlyphInfo:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAlignment:range:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'setAllowsCharacterPickerTouchBarItem:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAllowsDocumentBackgroundColorChange:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAllowsImageEditing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAllowsUndo:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAutomaticDashSubstitutionEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAutomaticDataDetectionEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAutomaticLinkDetectionEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAutomaticQuoteSubstitutionEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAutomaticSpellingCorrectionEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setAutomaticTextReplacementEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setBaseWritingDirection:range:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'setConstrainedFrameSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSTextView', b'setContinuousSpellCheckingEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setDisplaysLinkToolTips:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setDrawsBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setEditable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setFieldEditor:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setGrammarCheckingEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setImportsGraphics:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setIncrementalSearchingEnabled:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTextView', b'setNeedsDisplayInRect:avoidAdditionalLayout:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': 'Z'}}})
r(b'NSTextView', b'setRichText:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setRulerVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setSelectable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setSelectedRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'setSelectedRange:affinity:stillSelecting:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': 'Z'}}})
r(b'NSTextView', b'setSelectedRanges:affinity:stillSelecting:', {'arguments': {4: {'type': 'Z'}}})
r(b'NSTextView', b'setSmartInsertDeleteEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setSpellingState:range:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'setTextContainerInset:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSTextView', b'setUsesFindBar:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTextView', b'setUsesFindPanel:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setUsesFontPanel:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'setUsesInspectorBar:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTextView', b'setUsesRolloverButtonForSelection:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSTextView', b'setUsesRuler:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'shouldChangeTextInRange:replacementString:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'shouldChangeTextInRanges:replacementStrings:', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'shouldDrawInsertionPoint', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'showFindIndicatorForRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'smartDeleteRangeForProposedRange:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'smartInsertAfterStringForString:replacingRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'smartInsertBeforeStringForString:replacingRange:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTextView', b'smartInsertDeleteEnabled', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'smartInsertForString:replacingRange:beforeString:afterString:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type_modifier': b'o'}, 5: {'type_modifier': b'o'}}})
r(b'NSTextView', b'stronglyReferencesTextStorage', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'textContainerInset', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSTextView', b'textContainerOrigin', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSTextView', b'updateInsertionPointStateAndRestartTimer:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTextView', b'usesFindBar', {'retval': {'type': b'Z'}})
r(b'NSTextView', b'usesFindPanel', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'usesFontPanel', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'usesInspectorBar', {'retval': {'type': b'Z'}})
r(b'NSTextView', b'usesRolloverButtonForSelection', {'retval': {'type': b'Z'}})
r(b'NSTextView', b'usesRuler', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'writeSelectionToPasteboard:type:', {'retval': {'type': 'Z'}})
r(b'NSTextView', b'writeSelectionToPasteboard:types:', {'retval': {'type': 'Z'}})
r(b'NSTitlebarAccessoryViewController', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSTitlebarAccessoryViewController', b'setHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSToolbar', b'allowsExtensionItems', {'retval': {'type': b'Z'}})
r(b'NSToolbar', b'allowsUserCustomization', {'retval': {'type': 'Z'}})
r(b'NSToolbar', b'autosavesConfiguration', {'retval': {'type': 'Z'}})
r(b'NSToolbar', b'customizationPaletteIsRunning', {'retval': {'type': 'Z'}})
r(b'NSToolbar', b'isVisible', {'retval': {'type': 'Z'}})
r(b'NSToolbar', b'setAllowsExtensionItems:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSToolbar', b'setAllowsUserCustomization:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSToolbar', b'setAutosavesConfiguration:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSToolbar', b'setShowsBaselineSeparator:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSToolbar', b'setVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSToolbar', b'showsBaselineSeparator', {'retval': {'type': 'Z'}})
r(b'NSToolbarItem', b'allowsDuplicatesInToolbar', {'retval': {'type': 'Z'}})
r(b'NSToolbarItem', b'autovalidates', {'retval': {'type': 'Z'}})
r(b'NSToolbarItem', b'isEnabled', {'retval': {'type': 'Z'}})
r(b'NSToolbarItem', b'maxSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSToolbarItem', b'minSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSToolbarItem', b'setAction:', {'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSToolbarItem', b'setAutovalidates:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSToolbarItem', b'setEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSToolbarItem', b'setMaxSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSToolbarItem', b'setMinSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSTouch', b'deviceSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSTouch', b'isResting', {'retval': {'type': 'Z'}})
r(b'NSTouchBar', b'isVisible', {'retval': {'type': 'Z'}})
r(b'NSTouchBar', b'setVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTouchBarItem', b'isVisible', {'retval': {'type': 'Z'}})
r(b'NSTouchBarItem', b'setVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTrackingArea', b'initWithRect:options:owner:userInfo:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTrackingArea', b'rect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSTreeController', b'addSelectionIndexPaths:', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'alwaysUsesMultipleValuesMarker', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'avoidsEmptySelection', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'canAddChild', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'canInsert', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'canInsertChild', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'preservesSelection', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'removeSelectionIndexPaths:', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'selectsInsertedObjects', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'setAlwaysUsesMultipleValuesMarker:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTreeController', b'setAvoidsEmptySelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTreeController', b'setPreservesSelection:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTreeController', b'setSelectionIndexPath:', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'setSelectionIndexPaths:', {'retval': {'type': 'Z'}})
r(b'NSTreeController', b'setSelectsInsertedObjects:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTreeNode', b'isLeaf', {'retval': {'type': 'Z'}})
r(b'NSTreeNode', b'sortWithSortDescriptors:recursively:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSTypesetter', b'bidiProcessingEnabled', {'retval': {'type': 'Z'}})
r(b'NSTypesetter', b'boundingBoxForControlGlyphAtIndex:forTextContainer:proposedLineFragment:glyphPosition:characterIndex:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 6: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSTypesetter', b'characterRangeForGlyphRange:actualGlyphRange:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o'}}})
r(b'NSTypesetter', b'deleteGlyphsInRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'endLineWithGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'getGlyphsInRange:glyphs:characterIndexes:glyphInscriptions:elasticBits:bidiLevels:', {'retval': {'type': sel32or64(b'I', b'Q')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 4: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 5: {'type_modifier': b'o', 'c_array_length_in_arg': 2}, 6: {'type': '^Z', 'type_modifier': b'o', 'c_array_length_in_arg': 2}, 7: {'type': '^C', 'type_modifier': b'o', 'c_array_length_in_arg': 2}}})
r(b'NSTypesetter', b'getLineFragmentRect:usedRect:forParagraphSeparatorGlyphRange:atProposedOrigin:', {'arguments': {2: {'type_modifier': b'o'}, 3: {'type_modifier': b'o'}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSTypesetter', b'getLineFragmentRect:usedRect:remainingRect:forStartingGlyphAtIndex:proposedRect:lineSpacing:paragraphSpacingBefore:paragraphSpacingAfter:', {'arguments': {2: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 3: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 4: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 6: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTypesetter', b'glyphRangeForCharacterRange:actualCharacterRange:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'o'}}})
r(b'NSTypesetter', b'layoutCharactersInRange:forLayoutManager:maximumNumberOfLineFragments:', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'layoutGlyphsInLayoutManager:startingAtGlyphIndex:maxNumberOfLineFragments:nextGlyphIndex:', {'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSTypesetter', b'layoutParagraphAtPoint:', {'arguments': {2: {'type_modifier': b'N'}}})
r(b'NSTypesetter', b'lineSpacingAfterGlyphAtIndex:withProposedLineFragmentRect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTypesetter', b'paragraphCharacterRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTypesetter', b'paragraphGlyphRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTypesetter', b'paragraphSeparatorCharacterRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTypesetter', b'paragraphSeparatorGlyphRange', {'retval': {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}})
r(b'NSTypesetter', b'paragraphSpacingAfterGlyphAtIndex:withProposedLineFragmentRect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTypesetter', b'paragraphSpacingBeforeGlyphAtIndex:withProposedLineFragmentRect:', {'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTypesetter', b'printingAdjustmentInLayoutManager:forNominallySpacedGlyphRange:packedGlyphs:count:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'c_array_delimited_by_null': True, 'type': '^v', 'type_modifier': b'n', 'c_array_length_in_arg': 5}}})
r(b'NSTypesetter', b'setAttachmentSize:forGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'setBidiLevels:forGlyphRange:', {'arguments': {2: {'type': '^z', 'type_modifier': b'n', 'c_array_length_in_arg': 3}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'setBidiProcessingEnabled:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTypesetter', b'setDrawsOutsideLineFragment:forGlyphRange:', {'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'setHardInvalidation:forGlyphRange:', {'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'setLineFragmentRect:forGlyphRange:usedRect:baselineOffset:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSTypesetter', b'setLocation:withAdvancements:forStartOfGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 4}, 4: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'setNotShownAttribute:forGlyphRange:', {'arguments': {2: {'type': 'Z'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'setParagraphGlyphRange:separatorGlyphRange:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}})
r(b'NSTypesetter', b'setUsesFontLeading:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSTypesetter', b'shouldBreakLineByHyphenatingBeforeCharacterAtIndex:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSTypesetter', b'shouldBreakLineByWordBeforeCharacterAtIndex:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSTypesetter', b'substituteGlyphsInRange:withGlyphs:', {'arguments': {2: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 3: {'type_modifier': b'n', 'c_array_length_in_arg': 2}}})
r(b'NSTypesetter', b'usesFontLeading', {'retval': {'type': 'Z'}})
r(b'NSTypesetter', b'willSetLineFragmentRect:forGlyphRange:usedRect:baselineOffset:', {'arguments': {2: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 4: {'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'N'}, 5: {'type': sel32or64(b'^f', b'^d'), 'type_modifier': b'N'}}})
r(b'NSUndoManager', b'groupsByEvent', {'retval': {'type': 'Z'}})
r(b'NSUndoManager', b'setGroupsByEvent:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSUserDefaultsController', b'appliesImmediately', {'retval': {'type': 'Z'}})
r(b'NSUserDefaultsController', b'hasUnappliedChanges', {'retval': {'type': 'Z'}})
r(b'NSUserDefaultsController', b'setAppliesImmediately:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSUserInterfaceCompressionOptions', b'containsOptions:', {'retval': {'type': 'Z'}})
r(b'NSUserInterfaceCompressionOptions', b'intersectsOptions:', {'retval': {'type': 'Z'}})
r(b'NSUserInterfaceCompressionOptions', b'isEmpty', {'retval': {'type': 'Z'}})
r(b'NSUserInterfaceCompressionOptions', b'setEmpty:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'acceptsFirstMouse:', {'retval': {'type': 'Z'}})
r(b'NSView', b'acceptsTouchEvents', {'retval': {'type': 'Z'}})
r(b'NSView', b'addCursorRect:cursor:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'addToolTipRect:owner:userData:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': '^v'}}})
r(b'NSView', b'addTrackingRect:owner:userData:assumeInside:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': '^v'}, 5: {'type': 'Z'}}})
r(b'NSView', b'adjustPageHeightNew:top:bottom:limit:', {'arguments': {2: {'type_modifier': b'o'}}})
r(b'NSView', b'adjustPageWidthNew:left:right:limit:', {'arguments': {2: {'type_modifier': b'o'}}})
r(b'NSView', b'adjustScroll:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'alignmentRectInsets', {'retval': {'type': sel32or64(b'{NSEdgeInsets=ffff}', b'{NSEdgeInsets=dddd}')}})
r(b'NSView', b'allowsVibrancy', {'retval': {'type': b'Z'}})
r(b'NSView', b'autoresizesSubviews', {'retval': {'type': 'Z'}})
r(b'NSView', b'autoscroll:', {'retval': {'type': 'Z'}})
r(b'NSView', b'beginPageInRect:atPlacement:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'bitmapImageRepForCachingDisplayInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'bounds', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSView', b'cacheDisplayInRect:toBitmapImageRep:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'canBecomeKeyView', {'retval': {'type': 'Z'}})
r(b'NSView', b'canDraw', {'retval': {'type': 'Z'}})
r(b'NSView', b'canDrawConcurrently', {'retval': {'type': 'Z'}})
r(b'NSView', b'canDrawSubviewsIntoLayer', {'retval': {'type': b'Z'}})
r(b'NSView', b'centerScanRect:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'context:', {'arguments': {2: {'type': '^v'}}})
r(b'NSView', b'convertPoint:fromView:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'convertPoint:toView:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'convertPointFromBase:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'convertPointToBase:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'convertRect:fromView:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'convertRect:toView:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'convertRectFromBase:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'convertRectToBase:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'convertSize:fromView:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'convertSize:toView:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'convertSizeFromBase:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'convertSizeToBase:', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'dataWithEPSInsideRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'dataWithPDFInsideRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'displayIfNeededInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'displayIfNeededInRectIgnoringOpacity:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'displayRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'displayRectIgnoringOpacity:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'displayRectIgnoringOpacity:inContext:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'dragFile:fromRect:slideBack:event:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 4: {'type': 'Z'}}})
r(b'NSView', b'dragImage:at:offset:event:pasteboard:source:slideBack:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 8: {'type': 'Z'}}})
r(b'NSView', b'dragPromisedFilesOfTypes:fromRect:source:slideBack:event:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': 'Z'}}})
r(b'NSView', b'drawPageBorderWithSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'drawRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'drawSheetBorderWithSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'enterFullScreenMode:withOptions:', {'retval': {'type': 'Z'}})
r(b'NSView', b'frame', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSView', b'getRectsBeingDrawn:count:', {'arguments': {2: {'type': sel32or64(b'^^{_NSRect}', b'^^{CGRect}')}, 3: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'o'}}})
r(b'NSView', b'getRectsExposedDuringLiveResize:count:', {'arguments': {2: {'c_array_of_fixed_length': 4, 'type': sel32or64(b'^{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'^{CGRect={CGPoint=dd}{CGSize=dd}}'), 'type_modifier': b'o'}, 3: {'type': sel32or64(b'^i', b'^q'), 'type_modifier': b'o'}}})
r(b'NSView', b'hasAmbiguousLayout', {'retval': {'type': b'Z'}})
r(b'NSView', b'hitTest:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'inLiveResize', {'retval': {'type': 'Z'}})
r(b'NSView', b'isCompatibleWithResponsiveScrolling', {'retval': {'type': b'Z'}})
r(b'NSView', b'isDescendantOf:', {'retval': {'type': 'Z'}})
r(b'NSView', b'isDrawingFindIndicator', {'retval': {'type': b'Z'}})
r(b'NSView', b'isFlipped', {'retval': {'type': 'Z'}})
r(b'NSView', b'isHidden', {'retval': {'type': 'Z'}})
r(b'NSView', b'isHiddenOrHasHiddenAncestor', {'retval': {'type': 'Z'}})
r(b'NSView', b'isInFullScreenMode', {'retval': {'type': 'Z'}})
r(b'NSView', b'isOpaque', {'retval': {'type': 'Z'}})
r(b'NSView', b'isRotatedFromBase', {'retval': {'type': 'Z'}})
r(b'NSView', b'isRotatedOrScaledFromBase', {'retval': {'type': 'Z'}})
r(b'NSView', b'knowsPageRange:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type_modifier': b'o'}}})
r(b'NSView', b'layerUsesCoreImageFilters', {'retval': {'type': b'Z'}})
r(b'NSView', b'locationOfPrintRect:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'lockFocusIfCanDraw', {'retval': {'type': 'Z'}})
r(b'NSView', b'lockFocusIfCanDrawInContext:', {'retval': {'type': 'Z'}})
r(b'NSView', b'mouse:inRect:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 3: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'mouseDownCanMoveWindow', {'retval': {'type': 'Z'}})
r(b'NSView', b'needsDisplay', {'retval': {'type': 'Z'}})
r(b'NSView', b'needsLayout', {'retval': {'type': b'Z'}})
r(b'NSView', b'needsPanelToBecomeKey', {'retval': {'type': 'Z'}})
r(b'NSView', b'needsToDrawRect:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'needsUpdateConstraints', {'retval': {'type': b'Z'}})
r(b'NSView', b'performKeyEquivalent:', {'retval': {'type': 'Z'}})
r(b'NSView', b'performMnemonic:', {'retval': {'type': 'Z'}})
r(b'NSView', b'postsBoundsChangedNotifications', {'retval': {'type': 'Z'}})
r(b'NSView', b'postsFrameChangedNotifications', {'retval': {'type': 'Z'}})
r(b'NSView', b'preservesContentDuringLiveResize', {'retval': {'type': 'Z'}})
r(b'NSView', b'rectForPage:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSView', b'rectPreservedDuringLiveResize', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSView', b'removeCursorRect:cursor:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'requiresConstraintBasedLayout', {'retval': {'type': b'Z'}})
r(b'NSView', b'resizeSubviewsWithOldSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'resizeWithOldSuperviewSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'rulerView:shouldAddMarker:', {'retval': {'type': 'Z'}})
r(b'NSView', b'rulerView:shouldMoveMarker:', {'retval': {'type': 'Z'}})
r(b'NSView', b'rulerView:shouldRemoveMarker:', {'retval': {'type': 'Z'}})
r(b'NSView', b'scaleUnitSquareToSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'scrollClipView:toPoint:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'scrollPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'scrollRect:by:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'scrollRectToVisible:', {'retval': {'type': 'Z'}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'setAcceptsTouchEvents:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setAutoresizesSubviews:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setBounds:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'setBoundsOrigin:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'setBoundsSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'setCanDrawConcurrently:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setCanDrawSubviewsIntoLayer:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSView', b'setFrame:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'setFrameOrigin:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'setFrameSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'setHidden:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setKeyboardFocusRingNeedsDisplayInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'setLayerUsesCoreImageFilters:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSView', b'setNeedsDisplay:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setNeedsDisplayInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'setNeedsLayout:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSView', b'setNeedsUpdateConstraints:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSView', b'setPostsBoundsChangedNotifications:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setPostsFrameChangedNotifications:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setTranslatesAutoresizingMaskIntoConstraints:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSView', b'setWantsBestResolutionOpenGLSurface:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSView', b'setWantsExtendedDynamicRangeOpenGLSurface:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setWantsLayer:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'setWantsRestingTouches:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSView', b'shouldDelayWindowOrderingForEvent:', {'retval': {'type': 'Z'}})
r(b'NSView', b'shouldDrawColor', {'retval': {'type': 'Z'}})
r(b'NSView', b'showDefinitionForAttributedString:atPoint:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'showDefinitionForAttributedString:range:options:baselineOriginProvider:', {'arguments': {3: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}, 5: {'callable': {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'{_NSRange=II}', b'{_NSRange=QQ}')}}}}}})
r(b'NSView', b'sortSubviewsUsingFunction:context:', {'arguments': {2: {'callable': {'retval': {'type': b'i'}, 'arguments': {0: {'type': b'@'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}, 'type': '^?', 'callable_retained': False}, 3: {'type': '@'}}})
r(b'NSView', b'translateOriginToPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSView', b'translateRectsNeedingDisplayInRect:by:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSView', b'translatesAutoresizingMaskIntoConstraints', {'retval': {'type': b'Z'}})
r(b'NSView', b'visibleRect', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSView', b'wantsBestResolutionOpenGLSurface', {'retval': {'type': b'Z'}})
r(b'NSView', b'wantsDefaultClipping', {'retval': {'type': 'Z'}})
r(b'NSView', b'wantsExtendedDynamicRangeOpenGLSurface', {'retval': {'type': 'Z'}})
r(b'NSView', b'wantsLayer', {'retval': {'type': 'Z'}})
r(b'NSView', b'wantsRestingTouches', {'retval': {'type': 'Z'}})
r(b'NSView', b'wantsUpdateLayer', {'retval': {'type': b'Z'}})
r(b'NSView', b'writeEPSInsideRect:toPasteboard:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSView', b'writePDFInsideRect:toPasteboard:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSViewController', b'commitEditing', {'retval': {'type': 'Z'}})
r(b'NSViewController', b'commitEditingWithDelegate:didCommitSelector:contextInfo:', {'arguments': {3: {'type': ':', 'sel_of_type': b'v@:@Z^v'}, 4: {'type': '^v'}}})
r(b'NSViewController', b'isViewLoaded', {'retval': {'type': b'Z'}})
r(b'NSViewController', b'transitionFromViewController:toViewController:options:completionHandler:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}}}}}})
r(b'NSVisualEffectView', b'isEmphasized', {'retval': {'type': 'Z'}})
r(b'NSVisualEffectView', b'setEmphasized:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'acceptsMouseMovedEvents', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'allowsAutomaticWindowTabbing', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'allowsConcurrentViewDrawing', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'allowsToolTipsWhenApplicationIsInactive', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'animationResizeTime:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSWindow', b'areCursorRectsEnabled', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'aspectRatio', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSWindow', b'autorecalculatesContentBorderThicknessForEdge:', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'autorecalculatesKeyViewLoop', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'beginCriticalSheet:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSWindow', b'beginSheet:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': sel32or64(b'i', b'q')}}}}}})
r(b'NSWindow', b'cacheImageInRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSWindow', b'canBeVisibleOnAllSpaces', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'canBecomeKeyWindow', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'canBecomeMainWindow', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'canBecomeVisibleWithoutLogin', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'canHide', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'canRepresentDisplayGamut:', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'canStoreColor', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'cascadeTopLeftFromPoint:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSWindow', b'contentAspectRatio', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSWindow', b'contentMaxSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSWindow', b'contentMinSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSWindow', b'contentRectForFrameRect:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSWindow', b'contentRectForFrameRect:styleMask:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSWindow', b'contentResizeIncrements', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSWindow', b'convertBaseToScreen:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSWindow', b'convertScreenToBase:', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSWindow', b'dataWithEPSInsideRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSWindow', b'dataWithPDFInsideRect:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSWindow', b'displaysWhenScreenProfileChanges', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'dragImage:at:offset:event:pasteboard:source:slideBack:', {'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}, 8: {'type': 'Z'}}})
r(b'NSWindow', b'fieldEditor:forObject:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'frame', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}})
r(b'NSWindow', b'frameRectForContentRect:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSWindow', b'frameRectForContentRect:styleMask:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': sel32or64(b'I', b'Q')}}})
r(b'NSWindow', b'hasCloseBox', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'hasDynamicDepthLimit', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'hasShadow', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'hasTitleBar', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'hidesOnDeactivate', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'ignoresMouseEvents', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'inLiveResize', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'initWithContentRect:styleMask:backing:defer:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': 'Z'}}})
r(b'NSWindow', b'initWithContentRect:styleMask:backing:defer:screen:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 5: {'type': 'Z'}}})
r(b'NSWindow', b'initWithWindowRef:', {'arguments': {2: {'type': '^{OpaqueWindowPtr=}'}}})
r(b'NSWindow', b'isAutodisplay', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isDocumentEdited', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isExcludedFromWindowsMenu', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isFloatingPanel', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isFlushWindowDisabled', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isKeyWindow', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isMainWindow', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isMiniaturizable', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isMiniaturized', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isModalPanel', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isMovable', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isMovableByWindowBackground', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isOnActiveSpace', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isOneShot', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isOpaque', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isReleasedWhenClosed', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isResizable', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isRestorable', {'retval': {'type': b'Z'}})
r(b'NSWindow', b'isSheet', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isVisible', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isZoomable', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'isZoomed', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'makeFirstResponder:', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'maxSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSWindow', b'minSize', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSWindow', b'mouseLocationOutsideOfEventStream', {'retval': {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}})
r(b'NSWindow', b'nextEventMatchingMask:untilDate:inMode:dequeue:', {'arguments': {5: {'type': 'Z'}}})
r(b'NSWindow', b'onstrainFrameRect:toScreen:', {'retval': {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}}})
r(b'NSWindow', b'postEvent:atStart:', {'arguments': {3: {'type': 'Z'}}})
r(b'NSWindow', b'preservesContentDuringLiveResize', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'preventsApplicationTerminationWhenModal', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'resizeIncrements', {'retval': {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}})
r(b'NSWindow', b'setAcceptsMouseMovedEvents:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setAllowsAutomaticWindowTabbing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setAllowsConcurrentViewDrawing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setAllowsToolTipsWhenApplicationIsInactive:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setAspectRatio:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setAutodisplay:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setAutorecalculatesContentBorderThickness:forEdge:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setAutorecalculatesKeyViewLoop:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setCanBeVisibleOnAllSpaces:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setCanBecomeVisibleWithoutLogin:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setCanHide:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setContentAspectRatio:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setContentMaxSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setContentMinSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setContentResizeIncrements:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setContentSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setDisplaysWhenScreenProfileChanges:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setDocumentEdited:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setDynamicDepthLimit:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setExcludedFromWindowsMenu:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setFrame:display:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': 'Z'}}})
r(b'NSWindow', b'setFrame:display:animate:', {'arguments': {2: {'type': sel32or64(b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}', b'{CGRect={CGPoint=dd}{CGSize=dd}}')}, 3: {'type': 'Z'}, 4: {'type': 'Z'}}})
r(b'NSWindow', b'setFrameAutosaveName:', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'setFrameOrigin:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSWindow', b'setFrameTopLeftPoint:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSWindow', b'setFrameUsingName:', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'setFrameUsingName:force:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': 'Z'}}})
r(b'NSWindow', b'setHasShadow:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setHidesOnDeactivate:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setIgnoresMouseEvents:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setIsMiniaturized:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setIsVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setIsZoomed:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setMaxSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setMinSize:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setMovable:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setMovableByWindowBackground:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setOneShot:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setOpaque:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setPreservesContentDuringLiveResize:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setPreventsApplicationTerminationWhenModal:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setReleasedWhenClosed:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setResizeIncrements:', {'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}})
r(b'NSWindow', b'setRestorable:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSWindow', b'setShowsResizeIndicator:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setShowsToolbarButton:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'setTitlebarAppearsTransparent:', {'arguments': {2: {'type': b'Z'}}})
r(b'NSWindow', b'setViewsNeedDisplay:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'showsResizeIndicator', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'showsToolbarButton', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'titlebarAppearsTransparent', {'retval': {'type': b'Z'}})
r(b'NSWindow', b'trackEventsMatchingMask:timeout:mode:handler:', {'arguments': {5: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'o^Z'}}}}}})
r(b'NSWindow', b'tryToPerform:with:', {'retval': {'type': 'Z'}, 'arguments': {2: {'sel_of_type': b'v@:@'}}})
r(b'NSWindow', b'useOptimizedDrawing:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindow', b'viewsNeedDisplay', {'retval': {'type': 'Z'}})
r(b'NSWindow', b'windowNumberAtPoint:belowWindowWithNumber:', {'arguments': {2: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSWindow', b'windowRef', {'retval': {'type': '^{OpaqueWindowPtr=}'}})
r(b'NSWindow', b'worksWhenModal', {'retval': {'type': 'Z'}})
r(b'NSWindowController', b'isWindowLoaded', {'retval': {'type': 'Z'}})
r(b'NSWindowController', b'setDocumentEdited:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindowController', b'setShouldCascadeWindows:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindowController', b'setShouldCloseDocument:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindowController', b'shouldCascadeWindows', {'retval': {'type': 'Z'}})
r(b'NSWindowController', b'shouldCloseDocument', {'retval': {'type': 'Z'}})
r(b'NSWindowTabGroup', b'isOverviewVisible', {'retval': {'type': 'Z'}})
r(b'NSWindowTabGroup', b'isTabBarVisible', {'retval': {'type': 'Z'}})
r(b'NSWindowTabGroup', b'setOverviewVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWindowTabGroup', b'setTabBarVisible:', {'arguments': {2: {'type': 'Z'}}})
r(b'NSWorkspace', b'accessibilityDisplayShouldDifferentiateWithoutColor', {'retval': {'type': b'Z'}})
r(b'NSWorkspace', b'accessibilityDisplayShouldIncreaseContrast', {'retval': {'type': b'Z'}})
r(b'NSWorkspace', b'accessibilityDisplayShouldInvertColors', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'accessibilityDisplayShouldReduceMotion', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'accessibilityDisplayShouldReduceTransparency', {'retval': {'type': b'Z'}})
r(b'NSWorkspace', b'duplicateURLs:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}}}})
r(b'NSWorkspace', b'fileSystemChanged', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'filenameExtension:isValidForType:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'getFileSystemInfoForPath:isRemovable:isWritable:isUnmountable:description:type:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': '^Z', 'type_modifier': b'o'}, 4: {'type': '^Z', 'type_modifier': b'o'}, 5: {'type': '^Z', 'type_modifier': b'o'}, 6: {'type_modifier': b'o'}, 7: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'getInfoForFile:application:type:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type_modifier': b'o'}, 4: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'isFilePackageAtPath:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'isSwitchControlEnabled', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'isVoiceOverEnabled', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'launchAppWithBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifier:', {'retval': {'type': 'Z'}, 'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'launchApplication:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'launchApplication:showIcon:autolaunch:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type': 'Z'}, 4: {'type': 'Z'}}})
r(b'NSWorkspace', b'launchApplicationAtURL:options:configuration:error:', {'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'openFile:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'openFile:fromImage:at:inView:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSWorkspace', b'openFile:withApplication:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'openFile:withApplication:andDeactivate:', {'retval': {'type': 'Z'}, 'arguments': {4: {'type': 'Z'}}})
r(b'NSWorkspace', b'openTempFile:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'openURL:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'openURL:options:configuration:error:', {'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'openURLs:withAppBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifiers:', {'retval': {'type': 'Z'}, 'arguments': {6: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'openURLs:withApplicationAtURL:options:configuration:error:', {'arguments': {6: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'performFileOperation:source:destination:files:tag:', {'retval': {'type': 'Z'}, 'arguments': {6: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'recycleURLs:completionHandler:', {'arguments': {3: {'callable': {'retval': {'type': b'v'}, 'arguments': {0: {'type': b'^v'}, 1: {'type': b'@'}, 2: {'type': b'@'}}}}}})
r(b'NSWorkspace', b'selectFile:inFileViewerRootedAtPath:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'setDesktopImageURL:forScreen:options:error:', {'retval': {'type': 'Z'}, 'arguments': {5: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'setIcon:forFile:options:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'showSearchResultsForQueryString:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'slideImage:from:to:', {'retval': {'type': 'v'}, 'arguments': {3: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}, 4: {'type': sel32or64(b'{_NSPoint=ff}', b'{CGPoint=dd}')}}})
r(b'NSWorkspace', b'type:conformsToType:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'typeOfFile:error:', {'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'unmountAndEjectDeviceAtPath:', {'retval': {'type': 'Z'}})
r(b'NSWorkspace', b'unmountAndEjectDeviceAtURL:error:', {'retval': {'type': 'Z'}, 'arguments': {3: {'type_modifier': b'o'}}})
r(b'NSWorkspace', b'userDefaultsChanged', {'retval': {'type': 'Z'}})
finally:
objc._updatingMetadata(False)
protocols={'NSSavePanelDelegateDeprecated': objc.informal_protocol('NSSavePanelDelegateDeprecated', [objc.selector(None, b'panel:compareFilename:with:caseSensitive:', sel32or64(b'i@:@@@Z', b'q@:@@@Z'), isRequired=False), objc.selector(None, b'panel:directoryDidChange:', b'v@:@@', isRequired=False), objc.selector(None, b'panel:shouldShowFilename:', b'Z@:@@', isRequired=False), objc.selector(None, b'panel:isValidFilename:', b'Z@:@@', isRequired=False)]), 'NSAccessibilityAdditions': objc.informal_protocol('NSAccessibilityAdditions', [objc.selector(None, b'accessibilitySetOverrideValue:forAttribute:', b'Z@:@@', isRequired=False)]), 'NSApplicationScriptingDelegation': objc.informal_protocol('NSApplicationScriptingDelegation', [objc.selector(None, b'application:delegateHandlesKey:', b'Z@:@@', isRequired=False)]), 'NSNibAwaking': objc.informal_protocol('NSNibAwaking', [objc.selector(None, b'awakeFromNib', b'v@:', isRequired=False), objc.selector(None, b'prepareForInterfaceBuilder', b'v@:', isRequired=False)]), 'NSToolTipOwner': objc.informal_protocol('NSToolTipOwner', [objc.selector(None, b'view:stringForToolTip:point:userData:', sel32or64(b'@@:@i{_NSPoint=ff}^v', b'@@:@q{CGPoint=dd}^v'), isRequired=False)]), 'NSDraggingDestination': objc.informal_protocol('NSDraggingDestination', [objc.selector(None, b'wantsPeriodicDraggingUpdates', b'Z@:', isRequired=False), objc.selector(None, b'draggingExited:', b'v@:@', isRequired=False), objc.selector(None, b'draggingEnded:', b'v@:@', isRequired=False), objc.selector(None, b'concludeDragOperation:', b'v@:@', isRequired=False), objc.selector(None, b'performDragOperation:', b'Z@:@', isRequired=False), objc.selector(None, b'draggingEntered:', sel32or64(b'I@:@', b'Q@:@'), isRequired=False), objc.selector(None, b'prepareForDragOperation:', b'Z@:@', isRequired=False), objc.selector(None, b'draggingUpdated:', sel32or64(b'I@:@', b'Q@:@'), isRequired=False)]), 'NSOutlineViewNotifications': objc.informal_protocol('NSOutlineViewNotifications', [objc.selector(None, b'outlineViewItemWillExpand:', b'v@:@', isRequired=False), objc.selector(None, b'outlineViewSelectionDidChange:', b'v@:@', isRequired=False), objc.selector(None, b'outlineViewSelectionIsChanging:', b'v@:@', isRequired=False), objc.selector(None, b'outlineViewColumnDidResize:', b'v@:@', isRequired=False), objc.selector(None, b'outlineViewItemWillCollapse:', b'v@:@', isRequired=False), objc.selector(None, b'outlineViewItemDidExpand:', b'v@:@', isRequired=False), objc.selector(None, b'outlineViewColumnDidMove:', b'v@:@', isRequired=False), objc.selector(None, b'outlineViewItemDidCollapse:', b'v@:@', isRequired=False)]), 'NSDraggingSource': objc.informal_protocol('NSDraggingSource', [objc.selector(None, b'namesOfPromisedFilesDroppedAtDestination:', b'@@:@', isRequired=False), objc.selector(None, b'draggedImage:endedAt:operation:', sel32or64(b'v@:@{_NSPoint=ff}I', b'v@:@{CGPoint=dd}Q'), isRequired=False), objc.selector(None, b'draggedImage:beganAt:', sel32or64(b'v@:@{_NSPoint=ff}', b'v@:@{CGPoint=dd}'), isRequired=False), objc.selector(None, b'draggingSourceOperationMaskForLocal:', sel32or64(b'I@:Z', b'Q@:Z'), isRequired=False), objc.selector(None, b'draggedImage:movedTo:', sel32or64(b'v@:@{_NSPoint=ff}', b'v@:@{CGPoint=dd}'), isRequired=False), objc.selector(None, b'ignoreModifierKeysWhileDragging', b'Z@:', isRequired=False)]), 'NSPasteboardOwner': objc.informal_protocol('NSPasteboardOwner', [objc.selector(None, b'pasteboard:provideDataForType:', b'v@:@@', isRequired=False), objc.selector(None, b'pasteboardChangedOwner:', b'v@:@', isRequired=False)]), 'NSAccessibility': objc.informal_protocol('NSAccessibility', [objc.selector(None, b'accessibilityAttributeValue:', b'@@:@', isRequired=False), objc.selector(None, b'accessibilityParameterizedAttributeNames', b'@@:', isRequired=False), objc.selector(None, b'accessibilityArrayAttributeCount:', sel32or64(b'I@:@', b'Q@:@'), isRequired=False), objc.selector(None, b'accessibilityIsAttributeSettable:', b'Z@:@', isRequired=False), objc.selector(None, b'accessibilityAttributeValue:forParameter:', b'@@:@@', isRequired=False), objc.selector(None, b'accessibilityArrayAttributeValues:index:maxCount:', sel32or64(b'@@:@II', b'@@:@QQ'), isRequired=False), objc.selector(None, b'accessibilityActionNames', b'@@:', isRequired=False), objc.selector(None, b'accessibilityAttributeNames', b'@@:', isRequired=False), objc.selector(None, b'accessibilityNotifiesWhenDestroyed', b'Z@:', isRequired=False), objc.selector(None, b'accessibilityIndexOfChild:', sel32or64(b'I@:@', b'Q@:@'), isRequired=False), objc.selector(None, b'accessibilityPerformAction:', b'v@:@', isRequired=False), objc.selector(None, b'accessibilityIsIgnored', b'Z@:', isRequired=False), objc.selector(None, b'accessibilityActionDescription:', b'@@:@', isRequired=False), objc.selector(None, b'accessibilityHitTest:', sel32or64(b'@@:{_NSPoint=ff}', b'@@:{CGPoint=dd}'), isRequired=False), objc.selector(None, b'accessibilitySetValue:forAttribute:', b'v@:@@', isRequired=False), objc.selector(None, b'accessibilityFocusedUIElement', b'@@:', isRequired=False)]), 'NSRulerMarkerClientViewDelegation': objc.informal_protocol('NSRulerMarkerClientViewDelegation', [objc.selector(None, b'rulerView:didRemoveMarker:', b'v@:@@', isRequired=False), objc.selector(None, b'rulerView:shouldRemoveMarker:', b'Z@:@@', isRequired=False), objc.selector(None, b'rulerView:shouldMoveMarker:', b'Z@:@@', isRequired=False), objc.selector(None, b'rulerView:locationForPoint:', sel32or64(b'f@:@{_NSPoint=ff}', b'd@:@{CGPoint=dd}'), isRequired=False), objc.selector(None, b'rulerView:willAddMarker:atLocation:', sel32or64(b'f@:@@f', b'd@:@@d'), isRequired=False), objc.selector(None, b'rulerView:didMoveMarker:', b'v@:@@', isRequired=False), objc.selector(None, b'rulerView:pointForLocation:', sel32or64(b'{_NSPoint=ff}@:@f', b'{CGPoint=dd}@:@d'), isRequired=False), objc.selector(None, b'rulerView:handleMouseDown:', b'v@:@@', isRequired=False), objc.selector(None, b'rulerView:willMoveMarker:toLocation:', sel32or64(b'f@:@@f', b'd@:@@d'), isRequired=False), objc.selector(None, b'rulerView:didAddMarker:', b'v@:@@', isRequired=False), objc.selector(None, b'rulerView:shouldAddMarker:', b'Z@:@@', isRequired=False), objc.selector(None, b'rulerView:willSetClientView:', b'v@:@@', isRequired=False)]), 'NSFontPanelValidationAdditions': objc.informal_protocol('NSFontPanelValidationAdditions', [objc.selector(None, b'validModesForFontPanel:', sel32or64(b'I@:@', b'Q@:@'), isRequired=False)]), 'NSToolbarItemValidation': objc.informal_protocol('NSToolbarItemValidation', [objc.selector(None, b'validateToolbarItem:', b'Z@:@', isRequired=False)]), 'NSKeyValueBindingCreation': objc.informal_protocol('NSKeyValueBindingCreation', [objc.selector(None, b'bind:toObject:withKeyPath:options:', b'v@:@@@@', isRequired=False), objc.selector(None, b'exposeBinding:', b'v@:@', isRequired=False), objc.selector(None, b'valueClassForBinding:', b'#@:@', isRequired=False), objc.selector(None, b'unbind:', b'v@:@', isRequired=False), objc.selector(None, b'infoForBinding:', b'@@:@', isRequired=False), objc.selector(None, b'exposedBindings', b'@@:', isRequired=False), objc.selector(None, b'optionDescriptionsForBinding:', b'@@:@', isRequired=False)]), 'NSDictionaryControllerKeyValuePair': objc.informal_protocol('NSDictionaryControllerKeyValuePair', [objc.selector(None, b'setKey:', b'v@:@', isRequired=False), objc.selector(None, b'setLocalizedKey:', b'v@:@', isRequired=False), objc.selector(None, b'value', b'@@:', isRequired=False), objc.selector(None, b'isExplicitlyIncluded', b'Z@:', isRequired=False), objc.selector(None, b'setValue:', b'v@:@', isRequired=False), objc.selector(None, b'key', b'@@:', isRequired=False), objc.selector(None, b'localizedKey', b'@@:', isRequired=False)]), 'NSEditor': objc.informal_protocol('NSEditor', [objc.selector(None, b'discardEditing', b'v@:', isRequired=False), objc.selector(None, b'commitEditing', b'Z@:', isRequired=False), objc.selector(None, b'commitEditingWithDelegate:didCommitSelector:contextInfo:', b'v@:@:^v', isRequired=False), objc.selector(None, b'commitEditingAndReturnError:', b'Z@:^@', isRequired=False)]), 'NSFontManagerDelegate': objc.informal_protocol('NSFontManagerDelegate', [objc.selector(None, b'fontManager:willIncludeFont:', b'Z@:@@', isRequired=False)]), 'NSControlSubclassNotifications': objc.informal_protocol('NSControlSubclassNotifications', [objc.selector(None, b'controlTextDidChange:', b'v@:@', isRequired=False), objc.selector(None, b'controlTextDidBeginEditing:', b'v@:@', isRequired=False), objc.selector(None, b'controlTextDidEndEditing:', b'v@:@', isRequired=False)]), 'NSServicesRequests': objc.informal_protocol('NSServicesRequests', [objc.selector(None, b'readSelectionFromPasteboard:', b'Z@:@', isRequired=False), objc.selector(None, b'writeSelectionToPasteboard:types:', b'Z@:@@', isRequired=False)]), 'NSTableViewDataSourceDeprecated': objc.informal_protocol('NSTableViewDataSourceDeprecated', [objc.selector(None, b'tableView:writeRows:toPasteboard:', b'Z@:@@@', isRequired=False)]), 'NSPlaceholders': objc.informal_protocol('NSPlaceholders', [objc.selector(None, b'setDefaultPlaceholder:forMarker:withBinding:', b'v@:@@@', isRequired=False), objc.selector(None, b'defaultPlaceholderForMarker:withBinding:', b'@@:@@', isRequired=False)]), 'NSDraggingSourceDeprecated': objc.informal_protocol('NSDraggingSourceDeprecated', [objc.selector(None, b'namesOfPromisedFilesDroppedAtDestination:', b'@@:@', isRequired=False), objc.selector(None, b'draggedImage:endedAt:operation:', sel32or64(b'v@:@{_NSPoint=ff}I', b'v@:@{CGPoint=dd}Q'), isRequired=False), objc.selector(None, b'draggedImage:beganAt:', sel32or64(b'v@:@{_NSPoint=ff}', b'v@:@{CGPoint=dd}'), isRequired=False), objc.selector(None, b'draggedImage:endedAt:deposited:', sel32or64(b'v@:@{_NSPoint=ff}Z', b'v@:@{CGPoint=dd}Z'), isRequired=False), objc.selector(None, b'draggingSourceOperationMaskForLocal:', sel32or64(b'I@:Z', b'Q@:Z'), isRequired=False), objc.selector(None, b'draggedImage:movedTo:', sel32or64(b'v@:@{_NSPoint=ff}', b'v@:@{CGPoint=dd}'), isRequired=False), objc.selector(None, b'ignoreModifierKeysWhileDragging', b'Z@:', isRequired=False)]), 'NSColorPanelResponderMethod': objc.informal_protocol('NSColorPanelResponderMethod', [objc.selector(None, b'changeColor:', b'v@:@', isRequired=False)]), 'NSMenuValidation': objc.informal_protocol('NSMenuValidation', [objc.selector(None, b'validateMenuItem:', b'Z@:@', isRequired=False)]), 'NSEditorRegistration': objc.informal_protocol('NSEditorRegistration', [objc.selector(None, b'objectDidEndEditing:', b'v@:@', isRequired=False), objc.selector(None, b'objectDidBeginEditing:', b'v@:@', isRequired=False)]), 'NSFontManagerResponderMethod': objc.informal_protocol('NSFontManagerResponderMethod', [objc.selector(None, b'changeFont:', b'v@:@', isRequired=False)]), 'NSLayerDelegateContentsScaleUpdating': objc.informal_protocol('NSLayerDelegateContentsScaleUpdating', [objc.selector(None, b'layer:shouldInheritContentsScale:fromWindow:', sel32or64(b'Z@:@f@', b'Z@:@d@'), isRequired=False)])}
expressions = {}
# END OF FILE
| 162.236347
| 52,520
| 0.67534
|
be6c2ea60ae296724425cc76b9dd32e523369860
| 5,257
|
py
|
Python
|
pynautobot/core/api.py
|
Thetacz/pynautobot
|
4e1033eb952d7eb3fbc699be8e103f594a174cd7
|
[
"Apache-2.0"
] | 10
|
2021-02-24T23:52:09.000Z
|
2022-03-03T18:28:39.000Z
|
pynautobot/core/api.py
|
Thetacz/pynautobot
|
4e1033eb952d7eb3fbc699be8e103f594a174cd7
|
[
"Apache-2.0"
] | 23
|
2021-03-01T17:33:23.000Z
|
2022-03-22T14:02:39.000Z
|
pynautobot/core/api.py
|
Thetacz/pynautobot
|
4e1033eb952d7eb3fbc699be8e103f594a174cd7
|
[
"Apache-2.0"
] | 9
|
2021-02-25T04:36:44.000Z
|
2021-11-30T01:29:02.000Z
|
"""
(c) 2017 DigitalOcean
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This file has been modified by NetworktoCode, LLC.
"""
import sys
import requests
from pynautobot.core.query import Request
from pynautobot.core.app import App, PluginsApp
from pynautobot.core.graphql import GraphQLQuery
class Api(object):
"""The API object is the point of entry to pynautobot.
After instantiating the Api() with the appropriate named arguments
you can specify which app and endpoint you wish to interact with.
Valid attributes currently are:
* dcim
* ipam
* circuits
* tenancy
* extras
* virtualization
* users
Calling any of these attributes will return
:py:class:`.App` which exposes endpoints as attributes.
**Additional Attributes**:
* **http_session(requests.Session)**:
Override the default session with your own. This is used to control
a number of HTTP behaviors such as SSL verification, custom headers,
retires, and timeouts.
See `custom sessions <advanced.html#custom-sessions>`__ for more info.
:param str url: The base URL to the instance of Nautobot you
wish to connect to.
:param str token: Your Nautobot token.
:param bool,optional threading: Set to True to use threading in ``.all()``
and ``.filter()`` requests.
:raises AttributeError: If app doesn't exist.
:Examples:
>>> import pynautobot
>>> nb = pynautobot.api(
... 'http://localhost:8000',
... token='d6f4e314a5b5fefd164995169f28ae32d987704f'
... )
>>> nb.dcim.devices.all()
"""
def __init__(
self, url, token=None, threading=False,
):
base_url = "{}/api".format(url if url[-1] != "/" else url[:-1])
self.token = token
self.headers = {"Authorization": f"Token {self.token}"}
self.base_url = base_url
self.http_session = requests.Session()
self.threading = threading
self.dcim = App(self, "dcim")
self.ipam = App(self, "ipam")
self.circuits = App(self, "circuits")
self.tenancy = App(self, "tenancy")
self.extras = App(self, "extras")
self.virtualization = App(self, "virtualization")
self.users = App(self, "users")
self.plugins = PluginsApp(self)
self.graphql = GraphQLQuery(self)
@property
def version(self):
"""Gets the API version of Nautobot.
Can be used to check the Nautobot API version if there are
version-dependent features or syntaxes in the API.
:Returns: Version number as a string.
:Example:
>>> import pynautobot
>>> nb = pynautobot.api(
... 'http://localhost:8000',
... token='d6f4e314a5b5fefd164995169f28ae32d987704f'
... )
>>> nb.version
'1.0'
>>>
"""
version = Request(base=self.base_url, http_session=self.http_session,).get_version()
return version
def openapi(self):
"""Returns the OpenAPI spec.
Quick helper function to pull down the entire OpenAPI spec.
:Returns: dict
:Example:
>>> import pynautobot
>>> nb = pynautobot.api(
... 'http://localhost:8000',
... token='d6f4e314a5b5fefd164995169f28ae32d987704f'
... )
>>> nb.openapi()
{...}
>>>
"""
return Request(base=self.base_url, http_session=self.http_session,).get_openapi()
def status(self):
"""Gets the status information from Nautobot.
Available in Nautobot 2.10.0 or newer.
:Returns: Dictionary as returned by Nautobot.
:Raises: :py:class:`.RequestError` if the request is not successful.
:Example:
>>> pprint.pprint(nb.status())
{'django-version': '3.1.3',
'installed-apps': {'cacheops': '5.0.1',
'debug_toolbar': '3.1.1',
'django_filters': '2.4.0',
'django_prometheus': '2.1.0',
'django_rq': '2.4.0',
'django_tables2': '2.3.3',
'drf_yasg': '1.20.0',
'mptt': '0.11.0',
'rest_framework': '3.12.2',
'taggit': '1.3.0',
'timezone_field': '4.0'},
'nautobot-version': '1.0.0',
'plugins': {},
'python-version': '3.7.3',
'rq-workers-running': 1}
>>>
"""
status = Request(base=self.base_url, token=self.token, http_session=self.http_session,).get_status()
return status
| 33.062893
| 108
| 0.584364
|
27a154c840a3b2a7d4b50b3cff11e2433d4637f4
| 2,832
|
py
|
Python
|
handler.py
|
stijm/j2lsnek
|
b7a2779bd812ef9c7477e44058b2d033e04d7b1b
|
[
"MIT"
] | null | null | null |
handler.py
|
stijm/j2lsnek
|
b7a2779bd812ef9c7477e44058b2d033e04d7b1b
|
[
"MIT"
] | null | null | null |
handler.py
|
stijm/j2lsnek
|
b7a2779bd812ef9c7477e44058b2d033e04d7b1b
|
[
"MIT"
] | null | null | null |
import abc
import enum
import time
from jj2.protocol import TCP
from jj2.snek import config
from jj2.snek.utils import query
class Port(enum.IntEnum):
BINARY_LIST = 10053
SERVER_NET = 10056
REMOTE_ADMIN = SSL = 10059
class PortHandler(metaclass=abc.ABCMeta):
"""
Generic data handler: receives data from a socket and processes it
handle_data() method is to be defined by descendant classes, which will be called from the listener loop
"""
buffer = bytearray()
locked = False
def __init__(self, client, address, server_list):
"""
Check if all data is available and assign object vars
:param client: Socket through which the client is connected
:param address: Address (tuple with IP and connection port)
:param ls: List server object, for logging etc
"""
self.client = client
self.connection = self.client.create_connection(address)
self.key = str(self.connection)
self.ip, self.port = self.connection.address
self.server_list = server_list
self.waiter = self.client.loop.create_future()
@abc.abstractmethod
async def handle_data(self):
pass
def halt(self):
"""
Halt handler
Most handlers don't need to do anything for halting, but some may be looping or maintaining connections, in
which case this method can be used to properly end that.
:return:
"""
self.waiter.set_result(True)
async def send(self, string):
"""
Send text message to connection
For ascii server list etc, and error messages
:param string: Text message, will be encoded as ascii
:return: Return result of socket.sendall()
"""
await self.connection.send_raw(string.encode("ascii"), TCP)
async def error_msg(self, string):
"""
Just msg() with a warning before the message
:param string: Error message to send
:return: Return result of self.msg()
"""
await self.send("/!\ GURU MEDITATION /!\ " + string)
async def acknowledge(self):
"""
Just msg() but with a standardised ACK-message
:return: Return result of self.msg()
"""
await self.send("ACK")
def close(self):
"""
End the connection: close the socket
:return: Return result of socket.close()
"""
self.client.close()
@staticmethod
def cleanup():
"""
Housekeeping
Not critical, but should be called before some user-facing actions (e.g. retrieving server lists)
:return:
"""
query(
"DELETE FROM servers "
"WHERE remote = 1 AND lifesign < ?",
(int(time.time()) - config.TIMEOUT,)
)
| 27.764706
| 115
| 0.61476
|
7fb849ca980c614ef0d0f6cd6cd0562dbb79ae66
| 12,350
|
py
|
Python
|
defender/lib/cli.py
|
dfrtz/project-defender
|
18635da511af03b5adb7f2cf6332be6127ed10f9
|
[
"Apache-2.0"
] | null | null | null |
defender/lib/cli.py
|
dfrtz/project-defender
|
18635da511af03b5adb7f2cf6332be6127ed10f9
|
[
"Apache-2.0"
] | null | null | null |
defender/lib/cli.py
|
dfrtz/project-defender
|
18635da511af03b5adb7f2cf6332be6127ed10f9
|
[
"Apache-2.0"
] | null | null | null |
"""Shell access for primary application."""
import argparse
import getpass
from defender.lib import shells
from defender.lib.secure import AuthTable
class HostShell(shells.BaseShell):
"""An interactive shell class to control frontend and backend services for primary application.
All parser commands are defined in this class and automatically called depending on user input.
For example, if 'http logging' is entered by user, then http_logging(args) is called.
Attributes:
apid: An ApiServer which provides access to HTTP frontend and user authentication backend.
mediad: A MediaServer which provides access to video and audio on the local device.
"""
def __init__(self) -> None:
"""Initializes the base shell with prefix and null daemons."""
super(HostShell, self).__init__('Defender> ')
self.apid = None
self.mediad = None
def _get_cmd_list(self) -> list:
"""Creates a list of all commands that should autocomplete."""
commands = [
*['http logging info', 'http logging debug'],
*['service http start', 'service http stop'],
*['user add', 'user remove', 'user edit', 'user list']
]
return commands
def _setup_parser(self) -> argparse.ArgumentParser:
"""Setup all subcommand parsers accessible to the end user."""
parser = argparse.ArgumentParser(prog='', description='Defense Monitoring System')
# First level parsers
parsers = parser.add_subparsers(title='Commands', dest='root')
parsers.required = True
parser_help = parsers.add_parser('help', help='List commands and functions')
parser_http = parsers.add_parser('http', help='Modify HTTP subsystems')
parser_service = parsers.add_parser('service', help='Control services')
parser_user = parsers.add_parser('user', help='Modify user accounts')
parser_exit = parsers.add_parser('exit', help='Exit program')
# HTTP subparsers
subparsers_http = parser_http.add_subparsers(title='Subsystems', dest='branch')
subparsers_http.required = True
subparser_http_debug = subparsers_http.add_parser('logging', help='HTTP/API logging configuration')
subparser_http_debug.add_argument('level', help='Logging level', action='store', choices=['info', 'debug'])
# Service subparsers
subparsers_service = parser_service.add_subparsers(title='Services', dest='branch')
subparsers_service.required = True
subparser_service_video = subparsers_service.add_parser('audio', help='Audio service')
subparser_service_video.add_argument('action', help='Audio Action', action='store', choices=['start', 'stop'])
subparser_service_http = subparsers_service.add_parser('http', help='HTTP/API service')
subparser_service_http.add_argument('action', help='HTTP Action', action='store', choices=['start', 'stop'])
subparser_service_video = subparsers_service.add_parser('video', help='Video service')
subparser_service_video.add_argument('action', help='Video Action', action='store', choices=['start', 'stop'])
# User subparsers
subparsers_user = parser_user.add_subparsers(title='Actions', dest='branch')
subparsers_user.required = True
subparser_user_list = subparsers_user.add_parser('list', help='List users in database')
subparser_user_add = subparsers_user.add_parser('add', help='Add new user account')
subparser_user_add.add_argument('username', help='User name', action='store')
subparser_user_remove = subparsers_user.add_parser('remove', help='Remove existing user account')
subparser_user_remove.add_argument('username', help='User name', action='store')
subparser_user_edit = subparsers_user.add_parser('edit', help='Edit existing user account')
subparser_user_edit.add_argument('username', help='User name', action='store')
subparser_user_edit.add_argument('-p', '--password', help='Prompts for new user credentials.',
action='store_true')
# Exit subparsers
parser_exit.add_argument('-f', '--force', help='Force shutdown', action='store_true', default=False)
return parser
def _show_banner(self) -> None:
"""Do not show any banner to the user."""
def exit_root(self, args: argparse.Namespace) -> bool:
"""Prevents premature exits from program.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True if the command was handled and should continue looping. False if exit is requested.
"""
cmd_handled = True
try:
if not args.force:
response = input('Exit shell and shutdown all services? Y/n: ')
if response.lower() == 'y':
cmd_handled = False
else:
cmd_handled = False
except EOFError:
# CTRL+D intercept.
print('')
cmd_handled = False
except KeyboardInterrupt:
# CTRL+C intercept.
print('')
return cmd_handled
def http_logging(self, args: argparse.Namespace) -> bool:
"""Changes the logging level of the HTTP/API service.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True to indicate the command was handled.
"""
cmd_handled = True
level = args.level
if level == 'debug':
print('Warning: Enabling debugging will send additional output to console and logs, and restart the HTTP server.')
if input('Do you wish to continue? Y/n: ').lower() == 'y':
self.apid.set_debug(True)
elif level == 'info':
print('Warning: disabling debugging will restart the HTTP server.')
if input('Do you wish to continue? Y/n: ').lower() == 'y':
self.apid.set_debug(False)
return cmd_handled
def service_audio(self, args: argparse.Namespace) -> bool:
"""Changes the status of the Audio service.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True to indicate the command was handled.
"""
cmd_handled = True
action = args.action
if action == 'start':
self.mediad.start_audio()
elif action == 'stop':
self.mediad.stop_audio()
return cmd_handled
def service_http(self, args: argparse.Namespace) -> bool:
"""Changes the status of the HTTP/API service.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True to indicate the command was handled.
"""
cmd_handled = True
action = args.action
if action == 'start':
self.apid.start()
elif action == 'stop':
print('Warning: Stopping the HTTP service will prevent external access to commands, user shell will be required to restart.')
if input('Do you wish to continue? Y/n: ').lower() == 'y':
self.apid.shutdown()
return cmd_handled
def service_video(self, args: argparse.Namespace) -> bool:
"""Changes the status of the Video service.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True to indicate the command was handled.
"""
cmd_handled = True
action = args.action
if action == 'start':
self.mediad.start_video()
elif action == 'stop':
self.mediad.stop_video()
return cmd_handled
def user_add(self, args: argparse.Namespace) -> bool:
"""Adds a new user configuration.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True to indicate the command was handled.
"""
cmd_handled = True
user = args.username
if self.apid.server.authenticator.get_user(user):
print(f'{user} already exists. To modify user, use: user edit {user}')
else:
password1 = getpass.getpass(f'Enter password for {user}:')
# TODO add check against simple Passwords
password2 = getpass.getpass(f'Re-enter password for {user}:')
if password1 != password2:
print('Passwords do not match')
else:
self.apid.server.authenticator.add_user(user, password1)
return cmd_handled
def user_edit(self, args: argparse.Namespace) -> bool:
"""Edits a user's configuration.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True to indicate the command was handled.
"""
cmd_handled = True
user = args.username
# TODO Allow username change
entry = self.apid.server.authenticator.get_user(user)
if not entry:
print(f'User {user} does not exist')
else:
password1 = getpass.getpass(f'Enter password for {user}:')
# TODO add check against simple Passwords
password2 = getpass.getpass(f'Re-enter password for {user}:')
if password1 != password2:
print('Passwords do not match')
else:
entry[AuthTable.column_salt] = self.apid.server.authenticator.generate_salt()
entry[AuthTable.column_pass] = self.apid.server.authenticator.encrypt(
password1, entry[AuthTable.column_salt])
self.apid.server.authenticator.edit_user(user, entry)
return cmd_handled
def user_list(self, args: argparse.Namespace) -> bool:
"""Lists all users in the database.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True to indicate the command was handled.
"""
cmd_handled = True
entries = self.apid.server.authenticator.get_users()
if entries:
users = '\n'.join([user['username'] for user in entries])
print(f'User list:\n{users}')
return cmd_handled
def user_remove(self, args: argparse.Namespace) -> bool:
"""Removes a user's configuration.
This function is automatically called by self._execute_cmd() and should not be called manually.
Args:
args: User arguments from CLI.
Returns:
True to indicate the command was handled.
"""
cmd_handled = True
user = args.username
entry = self.apid.server.authenticator.get_user(user)
if not entry:
print(f'User {user} does not exist')
else:
print(f'Do you wish to revoke user {user}\'s access?')
if input('Re-enter user\'s name to continue: ') == user:
if self.apid.server.authenticator.remove_user(user):
print(f'User {user} access revoked.')
else:
print(f'Could not revoke user {user} access. Please try again.')
else:
print('User confirmation did not match. Please try again.')
return cmd_handled
| 41.722973
| 138
| 0.608016
|
32c46635de967ea39a6fba3227e432b344d6b152
| 917
|
py
|
Python
|
tests/protein/test_protein_sequence.py
|
bfabiandev/atom3d
|
b2499ff743be2e851c286cabf64696682abffa44
|
[
"MIT"
] | null | null | null |
tests/protein/test_protein_sequence.py
|
bfabiandev/atom3d
|
b2499ff743be2e851c286cabf64696682abffa44
|
[
"MIT"
] | null | null | null |
tests/protein/test_protein_sequence.py
|
bfabiandev/atom3d
|
b2499ff743be2e851c286cabf64696682abffa44
|
[
"MIT"
] | null | null | null |
import pytest
import numpy as np
import pandas as pd
import atom3d.datasets as da
import atom3d.protein.sequence as seq
def test_find_similar():
# TODO: write test for seq.find_similar()
pass
@pytest.mark.network
def test_get_pdb_clusters_and_find_cluster_members():
id_level = 0.3
clusterings = seq.get_pdb_clusters(id_level, pdb_ids=None)
pdb2cluster, cluster2pdb = clusterings
for cluster in cluster2pdb.keys():
for pdb in cluster2pdb[cluster]:
assert cluster in pdb2cluster[pdb]
for pdb in pdb2cluster.keys():
seq.find_cluster_members(pdb, clusterings)
@pytest.mark.network
def test_get_chain_sequences():
dataset = da.load_dataset('tests/test_data/lmdb', 'lmdb')
cseq = seq.get_chain_sequences(dataset[2]['atoms'])
assert cseq[0][1] == 'NNQQ'
def test_write_to_blast_db():
# TODO: write test for seq.write_to_blast_db()
pass
| 26.970588
| 62
| 0.720829
|
7106bc05fa353999350ac1bb50f295fae3965fb9
| 7,699
|
py
|
Python
|
pyfiscal/generate.py
|
erickcasita/pyfiscal
|
a1c1a95027fe28401006f13643e49a7a9ee6087f
|
[
"MIT"
] | 3
|
2020-03-23T18:45:42.000Z
|
2020-03-23T22:19:39.000Z
|
pyfiscal/generate.py
|
erickcasita/pyfiscal
|
a1c1a95027fe28401006f13643e49a7a9ee6087f
|
[
"MIT"
] | null | null | null |
pyfiscal/generate.py
|
erickcasita/pyfiscal
|
a1c1a95027fe28401006f13643e49a7a9ee6087f
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
import unicodedata
from .base import BaseGenerator
class GenerateRFC(BaseGenerator):
key_value = 'rfc'
DATA_REQUIRED = ('complete_name', 'last_name', 'mother_last_name', 'birth_date')
partial_data = None
def __init__(self, **kwargs):
self.complete_name = kwargs.get('complete_name')
self.last_name = kwargs.get('last_name')
self.mother_last_name = kwargs.get('mother_last_name')
self.birth_date = kwargs.get('birth_date')
self.parse(complete_name=self.complete_name, last_name=self.last_name,
mother_last_name=self.mother_last_name)
self.partial_data = self.data_fiscal(
complete_name=self.complete_name, last_name=self.last_name,
mother_last_name=self.mother_last_name, birth_date=self.birth_date)
def calculate(self):
if self.mother_last_name is not None:
complete_name = u"%s %s %s" % (self.last_name, self.mother_last_name, self.complete_name)
else:
complete_name = u"%s %s" % (self.last_name, self.complete_name)
rfc = self.partial_data
hc = self.homoclave(self.partial_data, complete_name)
rfc += '%s' % hc
rfc += self.verification_number(rfc)
return rfc
def remove_accents(self, s):
if type(s) is str:
s = u"%s" % s
return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))
def homoclave(self, rfc, complete_name):
nombre_numero = '0'
summary = 0
div = 0
mod = 0
rfc1 = {
' ':00, '&':10, 'Ñ':10, 'A':11, 'B':12, 'C':13, 'D':14, 'E':15, 'F':16,
'G':17, 'H':18, 'I':19, 'J':21, 'K':22, 'L':23, 'M':24, 'N':25, 'O':26,
'P':27, 'Q':28, 'R':29, 'S':32, 'T':33, 'U':34, 'V':35, 'W':36, 'X':37,
'Y':38, 'Z':39, '0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7,
'8':8,'9':9,
}
rfc2 = {
0:'1', 1:'2', 2:'3', 3:'4', 4:'5', 5:'6', 6:'7', 7:'8', 8:'9', 9:'A', 10:'B',
11:'C', 12:'D', 13:'E', 14:'F', 15:'G', 16:'H', 17:'I', 18:'J', 19:'K',
20:'L', 21:'M', 22:'N', 23:'P', 24:'Q', 25:'R', 26:'S', 27:'T', 28:'U',
29:'V', 30:'W', 31:'X', 32:'Y',
}
# Recorrer el nombre y convertir las letras en su valor numérico.
for count in range(0, len(complete_name)):
letra = self.remove_accents(complete_name[count])
nombre_numero += self.rfc_set(str(rfc1[letra]),'00')
# La formula es:
# El caracter actual multiplicado por diez mas el valor del caracter
# siguiente y lo anterior multiplicado por el valor del caracter siguiente.
for count in range(0,len(nombre_numero)-1):
count2 = count+1
summary += ((int(nombre_numero[count])*10) + int(nombre_numero[count2])) * int(nombre_numero[count2])
div = summary % 1000
mod = div % 34
div = (div-mod)/34
homoclave = ''
homoclave += self.rfc_set(rfc2[int(div)], 'Z')
homoclave += self.rfc_set(rfc2[int(mod)], 'Z')
return homoclave
def verification_number(self, rfc):
suma_numero = 0
suma_parcial = 0
digito = None
rfc3 = {
'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15, 'G':16, 'H':17, 'I':18,
'J':19, 'K':20, 'L':21, 'M':22, 'N':23, 'O':25, 'P':26, 'Q':27, 'R':28,
'S':29, 'T':30, 'U':31, 'V':32, 'W':33, 'X':34, 'Y':35, 'Z':36, '0':0,
'1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '':24,
' ':37,
}
for count in range(0,len(rfc)):
letra = rfc[count]
if rfc3[letra]:
suma_numero = rfc3[letra]
suma_parcial += (suma_numero*(14-(count+1)))
modulo = suma_parcial % 11
digito_parcial = (11-modulo)
if modulo == 0:
digito = '0'
if digito_parcial == 10:
digito = 'A'
else:
digito = str(digito_parcial)
return digito
def rfc_set(self, a, b):
if a == b:
return b
else:
return a
@property
def data(self):
return self.calculate()
class GenerateCURP(BaseGenerator):
""" Generate CURP"""
key_value = 'curp'
partial_data = None
DATA_REQUIRED = (
'complete_name',
'last_name',
'mother_last_name',
'birth_date',
'gender',
'city',
'state_code'
)
def __init__(self, **kwargs):
self.complete_name = kwargs.get('complete_name')
self.last_name = kwargs.get('last_name')
self.mother_last_name = kwargs.get('mother_last_name', None)
self.birth_date = kwargs.get('birth_date')
self.gender = kwargs.get('gender')
self.city = kwargs.get('city', None)
self.state_code = kwargs.get('state_code')
self.parse(complete_name=self.complete_name, last_name=self.last_name,
mother_last_name=self.mother_last_name, city=self.city, state_code=self.state_code)
self.partial_data = self.data_fiscal(
complete_name=self.complete_name, last_name=self.last_name,
mother_last_name=self.mother_last_name, birth_date=self.birth_date)
def calculate(self):
curp = self.partial_data
statecode = self.state_code
if self.city is not None:
statecode = self.city_search(self.city)
elif self.state_code is not None:
statecode = self.state_code
else:
raise AttributeError("No such attribute: state_code")
lastname = self.get_consonante(self.last_name)
mslastname = self.get_consonante(self.mother_last_name)
name = self.get_consonante(self.complete_name)
year = self.get_year(self.birth_date)
hc = self.homoclave(year)
curp += '%s%s%s%s%s%s' % (self.gender, statecode, lastname,
mslastname, name, hc)
curp += self.check_digit(curp)
return curp
def homoclave(self, year):
hc = ''
if year < 2000:
hc = '0'
elif year >= 2000:
hc = 'A'
return hc
def check_digit(self, curp):
value = 0
summary = 0
checkers = {
'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9,
'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15, 'G':16, 'H':17, 'I':18,
'J':19, 'K':20, 'L':21, 'M':22, 'N':23, 'Ñ':24, 'O':25, 'P':26, 'Q':27,
'R':28, 'S':29, 'T':30, 'U':31, 'V':32, 'W':33, 'X':34, 'Y':35, 'Z':36
}
count = 0
count2 = 18
for count in range(0,len(curp)):
posicion = curp[count]
for k, v in checkers.items():
if posicion == k:
value = (v * count2)
count2 = count2 - 1
summary = summary + value
num_ver = summary % 10 # Residue
num_ver = abs(10 - num_ver) #Returns the absolute value in case it is negative.
if num_ver == 10:
num_ver = 0
return str(num_ver)
@property
def data(self):
return self.calculate()
class GenerateNSS(BaseGenerator):
"""
class for CalculeNSS
"""
def __init__(self, nss):
self.nss = nss
def is_valid(self):
validated = len(self.nss)
if not validated is 11: # 11 dígitos y subdelegación válida
return False
sub_deleg = int(self.nss[0:2])
year = self.current_year() % 100
high_date = int(self.nss[2:4])
birth_date = int(self.nss[4:6])
if sub_deleg is not 97:
if high_date <= year:
high_date += 100
if birth_date <= year:
birth_date += 100
if birth_date > high_date:
print('Error: Se dio de alta antes de nacer.')
return False
return self._is_luhn_valid()
def _is_luhn_valid(self): #example 4896889802135
""" Validate an entry with a check digit. """
num = list(map(int, str(self.nss)))
return sum(num[::-2] + [sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0
def _calculate_luhn(self):
""" Calculation of said digit. """
num = list(map(int, str(self.nss)))
check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
return 0 if check_digit == 10 else check_digit
@property
def data(self):
return self._calculate_luhn()
class GenericGeneration(object):
_data = {}
def __init__(self, **kwargs):
self._datos = kwargs
@property
def data(self):
for cls in self.generadores:
data = cls.DATA_REQUIRED
kargs = {key: self._datos[key] for key in data}
gen = cls(**kargs)
gen.calculate()
self._data[gen.key_value] = gen.data
return self._data
| 28.409594
| 104
| 0.627484
|
5a07165701a0df64f817dd17e723898a14a560cf
| 930
|
py
|
Python
|
days/01-03-datetimes/code/pomidor_timer.py
|
VladimirLind/100daysofcode-with-python-course
|
fb33fe552a38ea7f23cffe82a4d7184786661ee5
|
[
"MIT"
] | null | null | null |
days/01-03-datetimes/code/pomidor_timer.py
|
VladimirLind/100daysofcode-with-python-course
|
fb33fe552a38ea7f23cffe82a4d7184786661ee5
|
[
"MIT"
] | null | null | null |
days/01-03-datetimes/code/pomidor_timer.py
|
VladimirLind/100daysofcode-with-python-course
|
fb33fe552a38ea7f23cffe82a4d7184786661ee5
|
[
"MIT"
] | null | null | null |
import click
import datetime
@click.command()
@click.option('--work', prompt="Time to work", type=float, help='Time to work in minutes')
@click.option('--relax', prompt="Time to relax", type=float, help='Time to relax in minutes')
@click.option('--cycle', prompt="Number of cycles", type=int, help='Number of iterations to work/relax')
def pomidor_timer(work, relax, cycle):
for i in range(0, cycle):
print("-"*40)
timedelta(work, "work")
print("-"*40)
if i != (cycle - 1):
timedelta(relax, "have a break")
else:
print("you are done!")
def timedelta(time, action):
delta = datetime.timedelta(seconds=time*60)
now = datetime.datetime.today()
future = now + delta
print("time to {} for {} min".format(action, time))
while True:
if datetime.datetime.today() > future:
break
if __name__ == '__main__':
pomidor_timer()
| 31
| 104
| 0.617204
|
5532c6eedbf459f78c3b068113d8522f1fb43074
| 3,491
|
py
|
Python
|
huaweicloud-sdk-iam/huaweicloudsdkiam/v3/model/keystone_update_identity_provider_request.py
|
wuchen-huawei/huaweicloud-sdk-python-v3
|
3683d703f4320edb2b8516f36f16d485cff08fc2
|
[
"Apache-2.0"
] | 1
|
2021-11-03T07:54:50.000Z
|
2021-11-03T07:54:50.000Z
|
huaweicloud-sdk-iam/huaweicloudsdkiam/v3/model/keystone_update_identity_provider_request.py
|
wuchen-huawei/huaweicloud-sdk-python-v3
|
3683d703f4320edb2b8516f36f16d485cff08fc2
|
[
"Apache-2.0"
] | null | null | null |
huaweicloud-sdk-iam/huaweicloudsdkiam/v3/model/keystone_update_identity_provider_request.py
|
wuchen-huawei/huaweicloud-sdk-python-v3
|
3683d703f4320edb2b8516f36f16d485cff08fc2
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
import pprint
import re
import six
class KeystoneUpdateIdentityProviderRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'id': 'str',
'body': 'KeystoneUpdateIdentityProviderRequestBody'
}
attribute_map = {
'id': 'id',
'body': 'body'
}
def __init__(self, id=None, body=None):
"""KeystoneUpdateIdentityProviderRequest - a model defined in huaweicloud sdk"""
self._id = None
self._body = None
self.discriminator = None
self.id = id
if body is not None:
self.body = body
@property
def id(self):
"""Gets the id of this KeystoneUpdateIdentityProviderRequest.
待更新的身份提供商ID。
:return: The id of this KeystoneUpdateIdentityProviderRequest.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this KeystoneUpdateIdentityProviderRequest.
待更新的身份提供商ID。
:param id: The id of this KeystoneUpdateIdentityProviderRequest.
:type: str
"""
self._id = id
@property
def body(self):
"""Gets the body of this KeystoneUpdateIdentityProviderRequest.
:return: The body of this KeystoneUpdateIdentityProviderRequest.
:rtype: KeystoneUpdateIdentityProviderRequestBody
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this KeystoneUpdateIdentityProviderRequest.
:param body: The body of this KeystoneUpdateIdentityProviderRequest.
:type: KeystoneUpdateIdentityProviderRequestBody
"""
self._body = body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, KeystoneUpdateIdentityProviderRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 25.859259
| 88
| 0.561444
|
c8160f2e3786e7111c1b41931d9b1ca6ec566c3d
| 705
|
py
|
Python
|
aim/ext/exception_resistant.py
|
rubenaprikyan/aim
|
039ccb29ec7d14ebc384d671d8a96c54fb4d15e4
|
[
"Apache-2.0"
] | null | null | null |
aim/ext/exception_resistant.py
|
rubenaprikyan/aim
|
039ccb29ec7d14ebc384d671d8a96c54fb4d15e4
|
[
"Apache-2.0"
] | null | null | null |
aim/ext/exception_resistant.py
|
rubenaprikyan/aim
|
039ccb29ec7d14ebc384d671d8a96c54fb4d15e4
|
[
"Apache-2.0"
] | null | null | null |
from functools import wraps
def exception_resistant(func):
num_fails = 0
max_fails = 6
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal num_fails
func_name = func.__name__
try:
return func(*args, **kwargs)
except Exception as e:
num_fails += 1
if num_fails == 1:
print('Something went wrong in `{}`. The process will continue to execute.'.format(func_name))
if num_fails <= max_fails:
print('`{}`: {}'.format(func_name, e))
elif num_fails == max_fails + 1:
print('The rest of the `{}` errors are hidden.'.format(func_name))
return wrapper
| 30.652174
| 110
| 0.560284
|
f423102f402dab38586c476ce77af24a0c85ea71
| 527
|
py
|
Python
|
env/Lib/site-packages/pangocffi/convert.py
|
kodelaben/manimce
|
fef4f1bd748d1cc8c1ade73e7561d4235dc253ca
|
[
"MIT"
] | 1
|
2021-06-01T19:10:23.000Z
|
2021-06-01T19:10:23.000Z
|
env/Lib/site-packages/pangocffi/convert.py
|
kodelaben/manimce
|
fef4f1bd748d1cc8c1ade73e7561d4235dc253ca
|
[
"MIT"
] | null | null | null |
env/Lib/site-packages/pangocffi/convert.py
|
kodelaben/manimce
|
fef4f1bd748d1cc8c1ade73e7561d4235dc253ca
|
[
"MIT"
] | null | null | null |
from . import pango
def units_to_double(i: int) -> float:
"""
Converts a number in Pango units to floating-point: divides it by
``PANGO_SCALE``.
:param i:
value in Pango units
"""
return pango.pango_units_to_double(i)
def units_from_double(d: float) -> int:
"""
Converts a floating-point number to Pango units: multiplies it by
``PANGO_SCALE`` and rounds to nearest integer.
:param d:
double floating-point value
"""
return pango.pango_units_from_double(d)
| 21.958333
| 69
| 0.656546
|
064b43b70108974cbbed095677493e3f107933f1
| 6,063
|
py
|
Python
|
Lib/test/test_unicode_file.py
|
Krrishdhaneja/cpython
|
9ae9ad8ba35cdcece7ded73cd2207e4f8cb85578
|
[
"0BSD"
] | 1
|
2020-10-25T16:33:22.000Z
|
2020-10-25T16:33:22.000Z
|
Lib/test/test_unicode_file.py
|
Krrishdhaneja/cpython
|
9ae9ad8ba35cdcece7ded73cd2207e4f8cb85578
|
[
"0BSD"
] | null | null | null |
Lib/test/test_unicode_file.py
|
Krrishdhaneja/cpython
|
9ae9ad8ba35cdcece7ded73cd2207e4f8cb85578
|
[
"0BSD"
] | null | null | null |
# Test some Unicode file name semantics
# We don't test many operations on files other than
# that their names can be used with Unicode characters.
import os, glob, time, shutil
import sys
import unicodedata
import unittest
from test.support import run_unittest
from test.support.os_helper import (rmtree, change_cwd, TESTFN_UNICODE,
TESTFN_UNENCODABLE, create_empty_file)
if not os.path.supports_unicode_filenames:
try:
TESTFN_UNICODE.encode(sys.getfilesystemencoding())
except (UnicodeError, TypeError):
# Either the file system encoding is None, or the file name
# cannot be encoded in the file system encoding.
raise unittest.SkipTest("No Unicode filesystem semantics on this platform.")
def remove_if_exists(filename):
if os.path.exists(filename):
os.unlink(filename)
class TestUnicodeFiles(unittest.TestCase):
# The 'do_' functions are the actual tests. They generally assume the
# file already exists etc.
# Do all the tests we can given only a single filename. The file should
# exist.
def _do_single(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isfile(filename))
self.assertTrue(os.access(filename, os.R_OK))
self.assertTrue(os.path.exists(os.path.abspath(filename)))
self.assertTrue(os.path.isfile(os.path.abspath(filename)))
self.assertTrue(os.access(os.path.abspath(filename), os.R_OK))
os.chmod(filename, 0o777)
os.utime(filename, None)
os.utime(filename, (time.time(), time.time()))
# Copy/rename etc tests using the same filename
self._do_copyish(filename, filename)
# Filename should appear in glob output
self.assertTrue(
os.path.abspath(filename)==os.path.abspath(glob.glob(glob.escape(filename))[0]))
# basename should appear in listdir.
path, base = os.path.split(os.path.abspath(filename))
file_list = os.listdir(path)
# Normalize the unicode strings, as round-tripping the name via the OS
# may return a different (but equivalent) value.
base = unicodedata.normalize("NFD", base)
file_list = [unicodedata.normalize("NFD", f) for f in file_list]
self.assertIn(base, file_list)
# Tests that copy, move, etc one file to another.
def _do_copyish(self, filename1, filename2):
# Should be able to rename the file using either name.
self.assertTrue(os.path.isfile(filename1)) # must exist.
os.rename(filename1, filename2 + ".new")
self.assertFalse(os.path.isfile(filename2))
self.assertTrue(os.path.isfile(filename1 + '.new'))
os.rename(filename1 + ".new", filename2)
self.assertFalse(os.path.isfile(filename1 + '.new'))
self.assertTrue(os.path.isfile(filename2))
shutil.copy(filename1, filename2 + ".new")
os.unlink(filename1 + ".new") # remove using equiv name.
# And a couple of moves, one using each name.
shutil.move(filename1, filename2 + ".new")
self.assertFalse(os.path.exists(filename2))
self.assertTrue(os.path.exists(filename1 + '.new'))
shutil.move(filename1 + ".new", filename2)
self.assertFalse(os.path.exists(filename2 + '.new'))
self.assertTrue(os.path.exists(filename1))
# Note - due to the implementation of shutil.move,
# it tries a rename first. This only fails on Windows when on
# different file systems - and this test can't ensure that.
# So we test the shutil.copy2 function, which is the thing most
# likely to fail.
shutil.copy2(filename1, filename2 + ".new")
self.assertTrue(os.path.isfile(filename1 + '.new'))
os.unlink(filename1 + ".new")
self.assertFalse(os.path.exists(filename2 + '.new'))
def _do_directory(self, make_name, chdir_name):
if os.path.isdir(make_name):
rmtree(make_name)
os.mkdir(make_name)
try:
with change_cwd(chdir_name):
cwd_result = os.getcwd()
name_result = make_name
cwd_result = unicodedata.normalize("NFD", cwd_result)
name_result = unicodedata.normalize("NFD", name_result)
self.assertEqual(os.path.basename(cwd_result),name_result)
finally:
os.rmdir(make_name)
# The '_test' functions 'entry points with params' - ie, what the
# top-level 'test' functions would be if they could take params
def _test_single(self, filename):
remove_if_exists(filename)
create_empty_file(filename)
try:
self._do_single(filename)
finally:
os.unlink(filename)
self.assertTrue(not os.path.exists(filename))
# and again with os.open.
f = os.open(filename, os.O_CREAT)
os.close(f)
try:
self._do_single(filename)
finally:
os.unlink(filename)
# The 'test' functions are unittest entry points, and simply call our
# _test functions with each of the filename combinations we wish to test
def test_single_files(self):
self._test_single(TESTFN_UNICODE)
if TESTFN_UNENCODABLE is not None:
self._test_single(TESTFN_UNENCODABLE)
def test_directories(self):
# For all 'equivalent' combinations:
# Make dir with encoded, chdir with unicode, checkdir with encoded
# (or unicode/encoded/unicode, etc
ext = ".dir"
self._do_directory(TESTFN_UNICODE+ext, TESTFN_UNICODE+ext)
# Our directory name that can't use a non-unicode name.
if TESTFN_UNENCODABLE is not None:
self._do_directory(TESTFN_UNENCODABLE+ext,
TESTFN_UNENCODABLE+ext)
def test_main():
run_unittest(__name__)
if __name__ == "__main__":
test_main()
| 42.104167
| 93
| 0.640442
|
9567bde113f0edc93bc9de92ce172ce0c8c261a3
| 379
|
py
|
Python
|
Tweet_Media.py
|
wolfdale/T-Bot
|
ceb4e6becf276592bf36f068dba59134e14bb4f0
|
[
"MIT"
] | null | null | null |
Tweet_Media.py
|
wolfdale/T-Bot
|
ceb4e6becf276592bf36f068dba59134e14bb4f0
|
[
"MIT"
] | null | null | null |
Tweet_Media.py
|
wolfdale/T-Bot
|
ceb4e6becf276592bf36f068dba59134e14bb4f0
|
[
"MIT"
] | null | null | null |
import tweepy
import os
import sys
ckey= ' '
csecret= ' '
atoken=' '
asecret= ' '
auth = tweepy.OAuthHandler(ckey,csecret) #Authenticating with twitter
auth.set_access_token(atoken,asecret) #Access tokens
api = tweepy.API(auth) #Performing Auth
filename = os.path.abspath(sys.argv[1])
status = sys.argv[2]
print "Posting Now"
api.update_with_media(filename,status=status)
| 21.055556
| 69
| 0.74934
|
22344229a0d369d629b26db64d1ead7698d6e87f
| 123
|
py
|
Python
|
kiqpo/core/jsLib/alert.py
|
bionic-py/Bionic
|
a54c85107a6a2aa9a9563b6b3e1f9bb64d63faa4
|
[
"MIT"
] | 9
|
2021-10-31T03:38:16.000Z
|
2021-12-17T00:03:36.000Z
|
kiqpo/core/jsLib/alert.py
|
bionic-py/Bionic
|
a54c85107a6a2aa9a9563b6b3e1f9bb64d63faa4
|
[
"MIT"
] | 12
|
2021-11-11T14:18:09.000Z
|
2021-12-03T14:00:25.000Z
|
kiqpo/core/jsLib/alert.py
|
kiqpo/kiqpo
|
a54c85107a6a2aa9a9563b6b3e1f9bb64d63faa4
|
[
"MIT"
] | 3
|
2022-03-03T18:30:53.000Z
|
2022-03-09T13:29:39.000Z
|
def alert(data, js=False):
if js == False:
return f'alert("{data}")'
else:
return f'alert({data})'
| 20.5
| 33
| 0.520325
|
e7e9c2003137a4a187efa31452aafa0566a7a9f3
| 6,109
|
py
|
Python
|
opennem/workers/aggregates.py
|
willhac/opennem
|
c8fbcd60e06898e1eeb2dad89548c4ece1b9a319
|
[
"MIT"
] | null | null | null |
opennem/workers/aggregates.py
|
willhac/opennem
|
c8fbcd60e06898e1eeb2dad89548c4ece1b9a319
|
[
"MIT"
] | null | null | null |
opennem/workers/aggregates.py
|
willhac/opennem
|
c8fbcd60e06898e1eeb2dad89548c4ece1b9a319
|
[
"MIT"
] | null | null | null |
import logging
import os
from datetime import datetime, timedelta
from textwrap import dedent
from typing import Tuple
from opennem.api.stats.controllers import get_scada_range
from opennem.api.stats.schema import ScadaDateRange
from opennem.db import get_database_engine
from opennem.schema.network import NetworkNEM, NetworkSchema, NetworkWEM
from opennem.utils.dates import DATE_CURRENT_YEAR
logger = logging.getLogger("opennem.workers.aggregates")
DRY_RUN = os.environ.get("DRY_RUN", False)
def aggregates_facility_daily_query(date_min: datetime, date_max: datetime = None) -> str:
"""This is the query to update the at_facility_daily aggregate"""
__query = """
insert into at_facility_daily
select
date_trunc('day', fs.trading_interval at time zone n.timezone_database) as trading_day,
f.network_id,
f.code as facility_code,
f.fueltech_id,
sum(fs.energy) as energy,
sum(fs.market_value) as market_value,
sum(fs.emissions) as emissions
from (
select
time_bucket_gapfill('30 minutes', fs.trading_interval) as trading_interval,
fs.facility_code as code,
coalesce(sum(fs.eoi_quantity), 0) as energy,
coalesce(sum(fs.eoi_quantity), 0) * coalesce(max(bsn.price), max(bs.price), 0) as market_value,
coalesce(sum(fs.eoi_quantity), 0) * coalesce(max(f.emissions_factor_co2), 0) as emissions
from facility_scada fs
left join facility f on fs.facility_code = f.code
left join network n on f.network_id = n.code
left join balancing_summary bsn on
bsn.trading_interval - INTERVAL '5 minutes' = fs.trading_interval
and bsn.network_id = n.network_price
and bsn.network_region = f.network_region
and f.network_id = 'NEM'
left join balancing_summary bs on
bs.trading_interval = fs.trading_interval
and bs.network_id = n.network_price
and bs.network_region = f.network_region
and f.network_id != 'NEM'
where
fs.is_forecast is False
and fs.trading_interval >= '{date_min}'
and fs.trading_interval <= '{date_max}'
group by
1, 2
) as fs
left join facility f on fs.code = f.code
left join network n on f.network_id = n.code
where
f.fueltech_id is not null
and fs.trading_interval >= '{date_min}'
and fs.trading_interval <= '{date_max}'
group by
1,
f.network_id,
f.code,
f.fueltech_id
on conflict (trading_day, network_id, facility_code) DO UPDATE set
energy = EXCLUDED.energy,
market_value = EXCLUDED.market_value,
emissions = EXCLUDED.emissions;
"""
query = __query.format(
date_min=date_min,
date_max=date_max,
)
return dedent(query)
def exec_aggregates_facility_daily_query(date_min: datetime, date_max: datetime = None) -> bool:
resp_code: bool = False
engine = get_database_engine()
result = None
query = aggregates_facility_daily_query(date_min, date_max)
with engine.connect() as c:
logger.debug(query)
if not DRY_RUN:
result = c.execute(query)
logger.debug(result)
# @NOTE rooftop fix for double counts
run_rooftop_fix()
return resp_code
def _get_year_range(year: int, network: NetworkSchema = NetworkNEM) -> Tuple[datetime, datetime]:
"""Get a date range for a year with end exclusive"""
tz = network.get_fixed_offset()
date_min = datetime(year, 1, 1, 0, 0, 0, 0, tzinfo=tz)
date_max = datetime(year + 1, 1, 1, 0, 0, 0, 0, tzinfo=tz)
if year == DATE_CURRENT_YEAR:
date_max = datetime.now().replace(hour=0, minute=0, second=0, tzinfo=tz) + timedelta(
days=1
)
return date_min, date_max
def run_aggregates_facility_year(
year: int = DATE_CURRENT_YEAR, network: NetworkSchema = NetworkNEM
) -> None:
"""Run aggregates for a single year
Args:
year (int, optional): [description]. Defaults to DATE_CURRENT_YEAR.
network (NetworkSchema, optional): [description]. Defaults to NetworkNEM.
"""
date_min, date_max = _get_year_range(year)
logger.info("Running for year {} - range : {} {}".format(year, date_min, date_max))
exec_aggregates_facility_daily_query(date_min, date_max)
def run_aggregates_facility_all_by_year() -> None:
YEAR_MIN = 1998
YEAR_MAX = DATE_CURRENT_YEAR
for year in range(YEAR_MAX, YEAR_MIN - 1, -1):
run_aggregates_facility_year(year)
def run_aggregates_facility_all(network: NetworkSchema) -> None:
scada_range: ScadaDateRange = get_scada_range(network=network)
exec_aggregates_facility_daily_query(date_min=scada_range.start, date_max=scada_range.end)
def run_aggregate_days(days: int = 1, network: NetworkSchema = NetworkNEM) -> None:
"""Run energy sum update for yesterday. This task is scheduled
in scheduler/db"""
tz = network.get_fixed_offset()
# This is Sydney time as the data is published in local time
# today_midnight in NEM time
today = datetime.now().replace(
hour=0, minute=0, second=0, microsecond=0, tzinfo=tz
) + timedelta(days=1)
date_max = today
date_min = today - timedelta(days=days)
exec_aggregates_facility_daily_query(date_min, date_max)
def run_rooftop_fix() -> None:
query = "delete from at_facility_daily where trading_day < '2018-03-01 00:00:00+00' and network_id='AEMO_ROOFTOP';"
engine = get_database_engine()
with engine.connect() as c:
logger.debug(query)
if not DRY_RUN:
c.execute(query)
def run_aggregates_all() -> None:
for network in [NetworkWEM, NetworkNEM]:
run_aggregates_facility_all(network)
# Debug entry point
if __name__ == "__main__":
run_aggregates_all()
| 32.668449
| 119
| 0.656081
|
ef58cb1926421ad0fd33e4bc239f84058e0cac33
| 2,183
|
py
|
Python
|
examples/python/geometry/triangle_mesh_sampling.py
|
amoran-symbio/Open3D
|
ae7e44e0dcef11a5df763819d47dec8c5bd5294b
|
[
"MIT"
] | 1,455
|
2021-07-27T19:44:50.000Z
|
2022-03-31T19:39:21.000Z
|
examples/python/geometry/triangle_mesh_sampling.py
|
amoran-symbio/Open3D
|
ae7e44e0dcef11a5df763819d47dec8c5bd5294b
|
[
"MIT"
] | 1,439
|
2021-07-27T16:02:52.000Z
|
2022-03-31T22:29:05.000Z
|
examples/python/geometry/triangle_mesh_sampling.py
|
amoran-symbio/Open3D
|
ae7e44e0dcef11a5df763819d47dec8c5bd5294b
|
[
"MIT"
] | 339
|
2021-07-28T03:07:28.000Z
|
2022-03-31T13:38:00.000Z
|
# ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2018-2021 www.open3d.org
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ----------------------------------------------------------------------------
import open3d as o3d
import numpy as np
import os
import sys
pyexample_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(pyexample_path)
import open3d_example as o3dex
if __name__ == "__main__":
mesh = o3dex.get_bunny_mesh()
mesh.compute_vertex_normals()
print("Displaying input mesh ...")
o3d.visualization.draw([mesh])
print("Displaying pointcloud using uniform sampling ...")
pcd = mesh.sample_points_uniformly(number_of_points=1000)
o3d.visualization.draw([pcd], point_size=5)
print("Displaying pointcloud using Poisson disk sampling ...")
pcd = mesh.sample_points_poisson_disk(number_of_points=1000, init_factor=5)
o3d.visualization.draw([pcd], point_size=5)
| 43.66
| 79
| 0.662391
|
f3b992f1379d7a705fc296f3814507e03b5d94bb
| 316
|
py
|
Python
|
other-problems/filetest.py
|
KristianMariyanov/PythonPlayground
|
c9a50e2cf95012af1a020eeeb9be2a419d748661
|
[
"MIT"
] | null | null | null |
other-problems/filetest.py
|
KristianMariyanov/PythonPlayground
|
c9a50e2cf95012af1a020eeeb9be2a419d748661
|
[
"MIT"
] | null | null | null |
other-problems/filetest.py
|
KristianMariyanov/PythonPlayground
|
c9a50e2cf95012af1a020eeeb9be2a419d748661
|
[
"MIT"
] | null | null | null |
""" Read and print an integer series """
import sys
def read_series(filename):
with open(filename, mode='rt', encoding='utf-8') as f:
return [int(line.strip()) for line in f]
def main(filename):
series = read_series(filename)
print(series)
if __name__ == '__main__':
main(sys.argv[1])
| 17.555556
| 58
| 0.64557
|
23d77c15c25d6ca74a5733bcf0d6434f8974d193
| 6,685
|
py
|
Python
|
_python/Call_Thread.py
|
CoCl-Jerry/Flashlapse_RELEASE
|
09a4dbe4bf99908ee09e161dc6dda4f15b012f83
|
[
"MIT"
] | null | null | null |
_python/Call_Thread.py
|
CoCl-Jerry/Flashlapse_RELEASE
|
09a4dbe4bf99908ee09e161dc6dda4f15b012f83
|
[
"MIT"
] | null | null | null |
_python/Call_Thread.py
|
CoCl-Jerry/Flashlapse_RELEASE
|
09a4dbe4bf99908ee09e161dc6dda4f15b012f83
|
[
"MIT"
] | null | null | null |
import Settings
import Functions
import UI_Update
import Threads
def start_motion_preset(self):
if not Settings.motionPreset_running:
try:
Settings.gravitropism_wait = self.gravitropism_spinBox.value()
Settings.rotateAmount = self.rotateAmount_spinBox.value()
Settings.rotateDelay = self.rotateDelay_spinBox.value()
Settings.motionPreset_mode = self.motionPreset_tabWidget.currentIndex()
self.MPreset_Thread = Threads.MPreset()
self.MPreset_Thread.started.connect(
lambda: UI_Update.motionPreset_update(self))
self.MPreset_Thread.finished.connect(
lambda: UI_Update.motionPreset_update(self))
self.MPreset_Thread.start()
except Exception as e:
print(e)
else:
Settings.motionPreset_running = False
UI_Update.motionPreset_update(self)
def start_cycle(self):
if not Settings.cycle_running:
try:
Settings.cycle_time = self.powerCycle_spinBox.value()
self.Cycle_Thread = Threads.Cycle()
self.Cycle_Thread.started.connect(
lambda: UI_Update.cycle_update(self))
self.Cycle_Thread.start()
except Exception as e:
print(e)
else:
Settings.cycle_running = False
UI_Update.cycle_update(self)
def schedule_test(self):
if not Settings.test_running:
try:
Settings.angle_1 = self.rotate1_spinbox.value()
Settings.angle_2 = self.rotate2_spinbox.value()
self.Test_Thread = Threads.Test()
self.Test_Thread.started.connect(
lambda: UI_Update.test_update(self))
self.Test_Thread.finished.connect(
lambda: UI_Update.test_update(self))
self.Test_Thread.start()
except Exception as e:
print(e)
else:
Settings.test_running = False
UI_Update.test_update(self)
def schedule_run(self):
if not Settings.sch_running:
try:
Settings.angle_1 = self.rotate1_spinbox.value()
Settings.angle_2 = self.rotate2_spinbox.value()
Settings.delay_1 = self.wait1_spinbox.value()
Settings.delay_2 = self.wait2_spinbox.value()
self.Schedule_Thread = Threads.Schedule()
self.Schedule_Thread.started.connect(
lambda: UI_Update.schedule_update(self))
self.Schedule_Thread.start()
except Exception as e:
print(e)
else:
Settings.sch_running = False
UI_Update.schedule_update(self)
def start_snapshot(self):
try:
Functions.Camera_update(self)
self.Snap_Thread = Threads.Snap()
self.Snap_Thread.started.connect(
lambda: UI_Update.imaging_disable(self))
self.Snap_Thread.finished.connect(
lambda: UI_Update.update_frame_snap(self, "../_temp/snapshot.jpg"))
self.Snap_Thread.start()
except Exception as e:
print(e)
def CV_authenticate(self):
Settings.cyverseUsername = self.cyverseUsername_lineEdit.text()
Settings.cyversePassword = self.cyversePassword_lineEdit.text()
try:
self.Auth_Thread = Threads.Auth()
self.Auth_Thread.started.connect(
lambda: UI_Update.CV_authenticating(self))
self.Auth_Thread.finished.connect(
lambda: UI_Update.CV_authenticated(self))
self.Auth_Thread.start()
except Exception as e:
print(e)
def start_livefeed(self):
try:
Settings.livetime = self.liveFeed_spinBox.value()
self.livefeed_Thread = Threads.Live()
self.livefeed_Thread.started.connect(
lambda: UI_Update.imaging_disable(self))
self.livefeed_Thread.finished.connect(
lambda: UI_Update.imaging_enable(self))
self.livefeed_Thread.start()
except Exception as e:
print(e)
def start_preview(self):
try:
Functions.Camera_update(self)
self.Preview_Thread = Threads.Preview()
self.Preview_Thread.started.connect(
lambda: UI_Update.imaging_disable(self))
if(Settings.image_format):
self.Preview_Thread.finished.connect(
lambda: UI_Update.update_frame_alt(self, "../_temp/preview.jpg"))
else:
self.Preview_Thread.finished.connect(
lambda: UI_Update.update_frame_alt(self, "../_temp/preview.png"))
self.Preview_Thread.start()
except Exception as e:
print(e)
def rotate_image(self):
try:
Functions.Camera_update(self)
Settings.rotation += 1
self.Snap_Thread = Threads.Snap()
self.Snap_Thread.started.connect(
lambda: UI_Update.imaging_disable(self))
self.Snap_Thread.finished.connect(
lambda: UI_Update.update_frame(self, "../_temp/snapshot.jpg"))
self.Snap_Thread.start()
except Exception as e:
print(e)
def start_sequence(self):
if(Settings.image_format):
Settings.file = Settings.full_dir + "/" + Settings.sequence_name + "_%04d.jpg"
else:
Settings.file = Settings.full_dir + "/" + Settings.sequence_name + "_%04d.png"
self.Progress_Bar.setMaximum(Settings.total)
try:
if not Settings.timelapse_running:
Functions.Camera_update(self)
self.Imaging_Thread = Threads.Image()
self.Imaging_Thread.started.connect(
lambda: UI_Update.timelapse_update(self))
self.Imaging_Thread.finished.connect(
lambda: UI_Update.timelapse_update(self))
self.Imaging_Thread.capturing.connect(
lambda: UI_Update.imaging_disable(self))
self.Imaging_Thread.complete.connect(
lambda: UI_Update.update_frame(self, Settings.current_image))
self.Imaging_Thread.start()
else:
Settings.timelapse_running = False
UI_Update.timelapse_update(self)
except Exception as e:
print(e)
if Settings.storage_mode and Settings.cyverse_authenticated:
try:
if Settings.cyverse_authenticated:
print("Starting Cyverse Sync Thread")
self.Cyverse_Thread = Threads.Cyverse()
self.Cyverse_Thread.start()
except Exception as e:
print(e)
def sensor_init(self):
try:
self.Sensor_Thread = Threads.Sensor()
self.Sensor_Thread.update.connect(
lambda: UI_Update.sensor_update(self))
self.Sensor_Thread.start()
except Exception as e:
print(e)
| 32.294686
| 86
| 0.636051
|
3985785d84137c8706901916250401ed3c848ef4
| 3,408
|
py
|
Python
|
neptune/internal/common/models/parameter_value_converter.py
|
jiji-online/neptune-cli
|
50cf680a80d141497f9331ab7cdaee49fcb90b0c
|
[
"Apache-2.0"
] | null | null | null |
neptune/internal/common/models/parameter_value_converter.py
|
jiji-online/neptune-cli
|
50cf680a80d141497f9331ab7cdaee49fcb90b0c
|
[
"Apache-2.0"
] | null | null | null |
neptune/internal/common/models/parameter_value_converter.py
|
jiji-online/neptune-cli
|
50cf680a80d141497f9331ab7cdaee49fcb90b0c
|
[
"Apache-2.0"
] | null | null | null |
#
# Copyright (c) 2016, deepsense.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from future.builtins import object
from neptune.internal.common.models.exceptions import NeptuneParameterConversionException
from neptune.internal.common.parsers.type_mapper import TypeMapper
from neptune.internal.common.utils.str import to_unicode
class ParameterValueConverter(object):
PARAMETER_TYPE_INT = u'int'
PARAMETER_TYPE_DOUBLE = u'double'
PARAMETER_TYPE_BOOLEAN = u'boolean'
PARAMETER_TYPE_STRING = u'string'
_PYTHON_TYPES = {
PARAMETER_TYPE_INT: int,
PARAMETER_TYPE_DOUBLE: float,
PARAMETER_TYPE_BOOLEAN: bool,
PARAMETER_TYPE_STRING: str
}
_CONVERSION_FUNCTIONS = {
PARAMETER_TYPE_INT: TypeMapper.to_int,
PARAMETER_TYPE_DOUBLE: TypeMapper.to_float,
PARAMETER_TYPE_BOOLEAN: TypeMapper.to_bool,
PARAMETER_TYPE_STRING: to_unicode
}
def __init__(self, parameter_api_model):
super(ParameterValueConverter, self).__init__()
self.parameter_api_model = parameter_api_model
def convert_value(self, parameter_value, parameter_type):
param_type = self._is_int_float_or_bool(parameter_value, parameter_type)
if parameter_value is None:
return None
conversion_function = self.type2conversion(param_type)
destination_type = self.type2python(param_type)
try:
converted_value = conversion_function(parameter_value)
return converted_value
except ValueError as ex:
raise NeptuneParameterConversionException(
self.parameter_api_model,
parameter_value,
destination_type,
ex)
@classmethod
def type2python(cls, type_name):
if type_name in cls._PYTHON_TYPES:
return cls._PYTHON_TYPES[type_name]
else:
raise ValueError(u'Unsupported parameter type: "{}"'.format(type_name))
def _is_int_float_or_bool(self, s, defined_type):
if s == "True" or s == "False":
return self.PARAMETER_TYPE_BOOLEAN
if defined_type == self.PARAMETER_TYPE_STRING:
return self.PARAMETER_TYPE_STRING
try:
floating = float(s)
try:
integer = int(s)
if floating == integer:
return self.PARAMETER_TYPE_INT
else:
return self.PARAMETER_TYPE_DOUBLE
except ValueError:
return self.PARAMETER_TYPE_DOUBLE
except ValueError:
return self.PARAMETER_TYPE_STRING
@classmethod
def type2conversion(cls, type_name):
if type_name in cls._CONVERSION_FUNCTIONS:
return cls._CONVERSION_FUNCTIONS[type_name]
else:
raise ValueError(u'Unsupported parameter type: "{}"'.format(type_name))
| 35.5
| 89
| 0.678404
|
3f72556bbd7d1fad0caee277284974b7e00cf497
| 5,312
|
py
|
Python
|
bin/atlas_traceroute.py
|
USC-NSL/ripe-atlas
|
9c512b0660923779031ec62909bc13bccace5890
|
[
"MIT"
] | 4
|
2015-09-17T18:22:36.000Z
|
2016-03-11T21:00:57.000Z
|
bin/atlas_traceroute.py
|
USC-NSL/ripe-atlas
|
9c512b0660923779031ec62909bc13bccace5890
|
[
"MIT"
] | null | null | null |
bin/atlas_traceroute.py
|
USC-NSL/ripe-atlas
|
9c512b0660923779031ec62909bc13bccace5890
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python
import sys
import traceback
import os
import time
import socket
from atlas import measure_baseclass
from measure_baseclass import MeasurementBase
from measure_baseclass import load_input, readkey, process_response
from measure_baseclass import SLEEP_TIME
class Traceroute(MeasurementBase):
def __init__(self, target, key, probe_list=None, sess=None,
dont_frag=False, protocol='ICMP', timeout=4000, paris=0):
super(Traceroute, self).__init__(target, key, probe_list, sess)
self.measurement_type = 'traceroute'
self.dont_frag = dont_frag
self.protocol = protocol
self.timeout = timeout
self.paris = paris
def setup_definitions(self):
definitions = super(Traceroute, self).setup_definitions()
definitions['dontfrag'] = str(self.dont_frag).lower()
definitions['protocol'] = self.protocol
definitions['timeout'] = self.timeout
if self.paris >= 1 and self.paris <= 16:
definitions['paris'] = self.paris
return definitions
def config_argparser():
parser = measure_baseclass.config_argparser()
parser.add_argument('-p', '--protocol', default=['ICMP'], nargs=1, help='Must be ICMP or UDP (default: ICMP)')
parser.add_argument('--dont-frag', action='store_true', help='Don\'t fragment the packet (default: off)')
parser.add_argument('--paris', default=[0], type=int,
help='Use Paris. Value must be between 1 and 16. (default: off)')
parser.add_argument('--timeout', default=[4000], type=int, # list default and type=int do not seem to work
help='Value (in milliseconds) must be between 1 and 60000 (default: 4000)')
parser.add_argument('--npackets', default=[3], nargs=1,
help='Number of packets to send to each hop (default: 3)')
return parser
if __name__ == '__main__':
parser = config_argparser() #set up command line parameters
args = parser.parse_args()
try:
key_file = args.key_file[0]
key = readkey(key_file) #read in Atlas API key
except:
sys.stderr.write('Error reading key file at %s\n' % key_file)
sys.exit(1)
#get args
target_dict = load_input(args.target_list[0])
outfile = args.meas_id_output[0]
dont_frag = args.dont_frag
protocol = args.protocol[0]
timeout = args.timeout[0]
paris = args.paris[0]
is_public = args.private
ipv6 = args.ipv6
description = args.description[0]
repeating = args.repeats[0]
npackets = args.npackets[0]
if not target_dict:
sys.stderr.write('No targets defined\n')
sys.exit(1)
try:
outf = open(outfile, 'w')
i = 0
target_list = target_dict.keys()
while i < len(target_list):
try:
target = target_list[i]
probe_list = target_dict[target]
"""
The maxmimum number of probes per requet is 500 so we need to break
this is up into several requests.
"""
probe_list_chunks = [probe_list[x:x+500] for x in xrange(0, len(probe_list), 500)]
j = 0
#for probe_list_chunk in probe_list_chunks:
while j < len(probe_list_chunks):
probe_list_chunk = probe_list_chunks[j]
traceroute = Traceroute(target, key, probe_list=probe_list_chunk,
dont_frag=dont_frag, protocol=protocol, timeout=timeout, paris=paris)
traceroute.description = description
traceroute.af = 4 if not ipv6 else 6
traceroute.is_oneoff = True if repeating == 0 else False
if not traceroute.is_oneoff: traceroute.interval = repeating #set the repeating interval
traceroute.is_public = is_public
traceroute.npackets = npackets
response = traceroute.run()
status, result = process_response(response)
if status == 'error':
sys.stderr.write('Request got error %s. Sleeping for %d seconds\n' % (result, SLEEP_TIME))
time.sleep(SLEEP_TIME)
continue #try again
else: #on success
measurement_list = result
measurement_list_str = map(str, measurement_list)
outstr = '\n'.join(measurement_list_str)
outf.write(outstr+'\n')
print(outstr)
j += 1 #only increment on success
time.sleep(10)
i += 1
except socket.error:
sys.stderr.write('Got network error. Going to sleep for %d seconds\n' % SLEEP_TIME)
traceback.print_exc(file=sys.stderr)
time.sleep(SLEEP_TIME)
except:
sys.stderr.write('Got error making traceroute request\n')
traceback.print_exc(file=sys.stderr)
finally:
outf.close()
| 39.058824
| 114
| 0.57436
|
951a372fea35b485b9d340004105a21136fef4bc
| 65
|
py
|
Python
|
redata/models/__init__.py
|
guicalare/redata
|
1cc04398eef984428fae4bedd9da98f06aae87ec
|
[
"MIT"
] | null | null | null |
redata/models/__init__.py
|
guicalare/redata
|
1cc04398eef984428fae4bedd9da98f06aae87ec
|
[
"MIT"
] | null | null | null |
redata/models/__init__.py
|
guicalare/redata
|
1cc04398eef984428fae4bedd9da98f06aae87ec
|
[
"MIT"
] | null | null | null |
from .metrics import *
from .table import *
from .alerts import *
| 21.666667
| 22
| 0.738462
|
673189574f97fcf4c5f8957e28dc07d30133709d
| 11,413
|
py
|
Python
|
telloCV.py
|
dronefreak/dji-tello-collision-avoidance-pydnet
|
d4d33059dab9bc4a81fadb42b503d6e9a1cecdf8
|
[
"MIT"
] | 23
|
2019-05-02T16:19:46.000Z
|
2022-03-30T08:05:56.000Z
|
dji-tello-collision-avoidance-pydnet/telloCV.py
|
driver005/tello
|
fdb67fa4c4c24f6b9dbaacdc22b8f0681b677b7f
|
[
"Apache-2.0"
] | 2
|
2019-08-25T08:34:22.000Z
|
2021-02-17T04:09:22.000Z
|
dji-tello-collision-avoidance-pydnet/telloCV.py
|
driver005/tello
|
fdb67fa4c4c24f6b9dbaacdc22b8f0681b677b7f
|
[
"Apache-2.0"
] | 13
|
2019-07-18T11:30:58.000Z
|
2021-10-31T11:17:50.000Z
|
"""
tellotracker:
Allows manual operation of the drone and demo tracking mode.
Requires mplayer to record/save video.
Controls:
- tab to lift off
- WASD to move the drone
- space/shift to ascend/descent slowly
- Q/E to yaw slowly
- arrow keys to ascend, descend, or yaw quickly
- backspace to land, or P to palm-land
- enter to take a picture
- R to start recording video, R again to stop recording
(video and photos will be saved to a timestamped file in ~/Pictures/)
- Z to toggle camera zoom state
(zoomed-in widescreen or high FOV 4:3)
- T to toggle tracking
@author Leonie Buckley, Saksham Sinha and Jonathan Byrne
@copyright 2018 see license file for details
"""
import time
import datetime
import os
import tellopy
import numpy
import av
import cv2
from pynput import keyboard
from tracker import Tracker
def main():
count = 0
t_stamp = time.time()
f=open("custom-dataset-3/rgb.txt", "w+")
f.write("# color images\n")
f.write("# file: 'rgbd_dataset_freiburg1_xyz.bag'\n")
f.write("# timestamp filename\n")
offset = 0.04
""" Create a tello controller and show the video feed."""
tellotrack = TelloCV()
for packet in tellotrack.container.demux((tellotrack.vid_stream,)):
for frame in packet.decode():
image = tellotrack.process_frame(frame)
image = cv2.resize(image, (640,480), interpolation = cv2.INTER_AREA)
cv2.imwrite("custom-dataset-3/rgb/{}.jpg".format(t_stamp), image) # save frame as JPEG file
f.write(str(t_stamp) + " " + "rgb/" + '{}.jpg'.format(t_stamp) + "\n")
t_stamp = t_stamp + offset
cv2.imshow('tello', image)
_ = cv2.waitKey(1) & 0xFF
f.close()
class TelloCV(object):
"""
TelloTracker builds keyboard controls on top of TelloPy as well
as generating images from the video stream and enabling opencv support
"""
def __init__(self):
self.prev_flight_data = None
self.record = False
self.tracking = False
self.keydown = False
self.date_fmt = '%Y-%m-%d_%H%M%S'
self.speed = 50
self.drone = tellopy.Tello()
self.init_drone()
self.init_controls()
# container for processing the packets into frames
self.container = av.open(self.drone.get_video_stream())
self.vid_stream = self.container.streams.video[0]
self.out_file = None
self.out_stream = None
self.out_name = None
self.start_time = time.time()
# tracking a color
green_lower = (30, 50, 50)
green_upper = (80, 255, 255)
#red_lower = (0, 50, 50)
# red_upper = (20, 255, 255)
# blue_lower = (110, 50, 50)
# upper_blue = (130, 255, 255)
self.track_cmd = ""
self.tracker = Tracker(self.vid_stream.height,
self.vid_stream.width,
green_lower, green_upper)
def init_drone(self):
"""Connect, uneable streaming and subscribe to events"""
# self.drone.log.set_level(2)
self.drone.connect()
self.drone.start_video()
self.drone.subscribe(self.drone.EVENT_FLIGHT_DATA,
self.flight_data_handler)
self.drone.subscribe(self.drone.EVENT_FILE_RECEIVED,
self.handle_flight_received)
def on_press(self, keyname):
"""handler for keyboard listener"""
if self.keydown:
return
try:
self.keydown = True
keyname = str(keyname).strip('\'')
print('+' + keyname)
if keyname == 'Key.esc':
self.drone.quit()
exit(0)
if keyname in self.controls:
key_handler = self.controls[keyname]
if isinstance(key_handler, str):
getattr(self.drone, key_handler)(self.speed)
else:
key_handler(self.speed)
except AttributeError:
print('special key {0} pressed'.format(keyname))
def on_release(self, keyname):
"""Reset on key up from keyboard listener"""
self.keydown = False
keyname = str(keyname).strip('\'')
print('-' + keyname)
if keyname in self.controls:
key_handler = self.controls[keyname]
if isinstance(key_handler, str):
getattr(self.drone, key_handler)(0)
else:
key_handler(0)
def init_controls(self):
"""Define keys and add listener"""
self.controls = {
'w': 'forward',
's': 'backward',
'a': 'left',
'd': 'right',
'Key.space': 'up',
'Key.shift': 'down',
'Key.shift_r': 'down',
'q': 'counter_clockwise',
'e': 'clockwise',
'i': lambda speed: self.drone.flip_forward(),
'k': lambda speed: self.drone.flip_back(),
'j': lambda speed: self.drone.flip_left(),
'l': lambda speed: self.drone.flip_right(),
# arrow keys for fast turns and altitude adjustments
'Key.left': lambda speed: self.drone.counter_clockwise(speed),
'Key.right': lambda speed: self.drone.clockwise(speed),
'Key.up': lambda speed: self.drone.up(speed),
'Key.down': lambda speed: self.drone.down(speed),
'Key.tab': lambda speed: self.drone.takeoff(),
'Key.backspace': lambda speed: self.drone.land(),
'p': lambda speed: self.palm_land(speed),
't': lambda speed: self.toggle_tracking(speed),
'r': lambda speed: self.toggle_recording(speed),
'z': lambda speed: self.toggle_zoom(speed),
'Key.enter': lambda speed: self.take_picture(speed)
}
self.key_listener = keyboard.Listener(on_press=self.on_press,
on_release=self.on_release)
self.key_listener.start()
# self.key_listener.join()
def process_frame(self, frame):
"""convert frame to cv2 image and show"""
image = cv2.cvtColor(numpy.array(
frame.to_image()), cv2.COLOR_RGB2BGR)
# image = self.write_hud(image)
# if self.record:
# self.record_vid(frame)
# xoff, yoff = self.tracker.track(image)
# image = self.tracker.draw_arrows(image)
# distance = 100
# cmd = ""
# if self.tracking:
# if xoff < -distance:
# cmd = "counter_clockwise"
# elif xoff > distance:
# cmd = "clockwise"
# elif yoff < -distance:
# cmd = "down"
# elif yoff > distance:
# cmd = "up"
# else:
# if self.track_cmd is not "":
# getattr(self.drone, self.track_cmd)(0)
# self.track_cmd = ""
# if cmd is not self.track_cmd:
# if cmd is not "":
# print("track command:", cmd)
# getattr(self.drone, cmd)(self.speed)
# self.track_cmd = cmd
return image
def write_hud(self, frame):
"""Draw drone info, tracking and record on frame"""
stats = self.prev_flight_data.split('|')
stats.append("Tracking:" + str(self.tracking))
if self.drone.zoom:
stats.append("VID")
else:
stats.append("PIC")
if self.record:
diff = int(time.time() - self.start_time)
mins, secs = divmod(diff, 60)
stats.append("REC {:02d}:{:02d}".format(mins, secs))
for idx, stat in enumerate(stats):
text = stat.lstrip()
cv2.putText(frame, text, (0, 30 + (idx * 30)),
cv2.FONT_HERSHEY_SIMPLEX,
1.0, (255, 0, 0), lineType=30)
return frame
def toggle_recording(self, speed):
"""Handle recording keypress, creates output stream and file"""
if speed == 0:
return
self.record = not self.record
if self.record:
datename = [os.getenv('HOME'), datetime.datetime.now().strftime(self.date_fmt)]
self.out_name = '{}/Pictures/tello-{}.mp4'.format(*datename)
print("Outputting video to:", self.out_name)
self.out_file = av.open(self.out_name, 'w')
self.start_time = time.time()
self.out_stream = self.out_file.add_stream(
'mpeg4', self.vid_stream.rate)
self.out_stream.pix_fmt = 'yuv420p'
self.out_stream.width = self.vid_stream.width
self.out_stream.height = self.vid_stream.height
if not self.record:
print("Video saved to ", self.out_name)
self.out_file.close()
self.out_stream = None
def record_vid(self, frame):
"""
convert frames to packets and write to file
"""
new_frame = av.VideoFrame(
width=frame.width, height=frame.height, format=frame.format.name)
for i in range(len(frame.planes)):
new_frame.planes[i].update(frame.planes[i])
pkt = None
try:
pkt = self.out_stream.encode(new_frame)
except IOError as err:
print("encoding failed: {0}".format(err))
if pkt is not None:
try:
self.out_file.mux(pkt)
except IOError:
print('mux failed: ' + str(pkt))
def take_picture(self, speed):
"""Tell drone to take picture, image sent to file handler"""
if speed == 0:
return
self.drone.take_picture()
def palm_land(self, speed):
"""Tell drone to land"""
if speed == 0:
return
self.drone.palm_land()
def toggle_tracking(self, speed):
""" Handle tracking keypress"""
if speed == 0: # handle key up event
return
self.tracking = not self.tracking
print("tracking:", self.tracking)
return
def toggle_zoom(self, speed):
"""
In "video" mode the self.drone sends 1280x720 frames.
In "photo" mode it sends 2592x1936 (952x720) frames.
The video will always be centered in the window.
In photo mode, if we keep the window at 1280x720 that gives us ~160px on
each side for status information, which is ample.
Video mode is harder because then we need to abandon the 16:9 display size
if we want to put the HUD next to the video.
"""
if speed == 0:
return
self.drone.set_video_mode(not self.drone.zoom)
def flight_data_handler(self, event, sender, data):
"""Listener to flight data from the drone."""
text = str(data)
if self.prev_flight_data != text:
self.prev_flight_data = text
def handle_flight_received(self, event, sender, data):
"""Create a file in ~/Pictures/ to receive image from the drone"""
path = '%s/Pictures/tello-%s.jpeg' % (
os.getenv('HOME'),
datetime.datetime.now().strftime(self.date_fmt))
with open(path, 'wb') as out_file:
out_file.write(data)
print('Saved photo to %s' % path)
if __name__ == '__main__':
main()
| 35.554517
| 113
| 0.563655
|
0c78fff3f1194561cf83cf422c4c19713cc4ca0f
| 1,601
|
py
|
Python
|
src/foremast/elb/splay_health.py
|
gitter-badger/foremast
|
33530438ba5893a1d5cf822a63e03d7ab49dfcd7
|
[
"Apache-2.0"
] | null | null | null |
src/foremast/elb/splay_health.py
|
gitter-badger/foremast
|
33530438ba5893a1d5cf822a63e03d7ab49dfcd7
|
[
"Apache-2.0"
] | null | null | null |
src/foremast/elb/splay_health.py
|
gitter-badger/foremast
|
33530438ba5893a1d5cf822a63e03d7ab49dfcd7
|
[
"Apache-2.0"
] | null | null | null |
# Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Cut Health Target up into pieces."""
import collections
import logging
LOG = logging.getLogger(__name__)
def splay_health(health_target):
"""Set Health Check path, port, and protocol.
Args:
health_target (str): The health target. ie ``HTTP:80``
Returns:
HealthCheck: A **collections.namedtuple** class with *path*, *port*,
*proto*, and *target* attributes.
"""
HealthCheck = collections.namedtuple('HealthCheck', ['path', 'port',
'proto', 'target'])
proto, health_port_path = health_target.split(':')
port, *health_path = health_port_path.split('/')
if proto == 'TCP':
path = ''
elif not health_path:
path = '/healthcheck'
else:
path = '/{0}'.format('/'.join(health_path))
target = '{0}:{1}{2}'.format(proto, port, path)
health = HealthCheck(path, port, proto, target)
LOG.info(health)
return health
| 30.788462
| 76
| 0.643973
|
bd970fc9958293f978f3953137ea955da037b959
| 1,965
|
py
|
Python
|
files/tag-ec2.py
|
rb-org/tfm-aws-lambda
|
b56f38e683c36c2be160df71ffc08719982e1e66
|
[
"MIT"
] | null | null | null |
files/tag-ec2.py
|
rb-org/tfm-aws-lambda
|
b56f38e683c36c2be160df71ffc08719982e1e66
|
[
"MIT"
] | null | null | null |
files/tag-ec2.py
|
rb-org/tfm-aws-lambda
|
b56f38e683c36c2be160df71ffc08719982e1e66
|
[
"MIT"
] | null | null | null |
import boto3
import os
# import json
# from datetime import datetime
from botocore.exceptions import ClientError
client = boto3.client('ec2')
ec2 = boto3.resource('ec2')
region = os.environ['REGION']
resource_ids = []
def lambda_handler(event, context):
try:
# print(event)
# Create EC2
if event['detail']['eventName'] == 'RunInstances':
items = event['detail']['responseElements']['instancesSet']['items']
for item in items:
resource_ids.append(item['instanceId'])
volumes = client.describe_volumes(
Filters=[
{
'Name': 'attachment.instance-id',
'Values': [
item['instanceId'],
]
},
]
)
vol_list = volumes['Volumes']
for vol in vol_list:
vol_id = vol['VolumeId']
resource_ids.append(vol_id)
# Create EBS
elif event['detail']['eventName'] == 'CreateVolume':
resource_ids.append(
event['detail']['responseElements']['volumeId'])
# Create Snapshot
elif event['detail']['eventName'] == 'CreateSnapshot':
resource_ids.append(
event['detail']['responseElements']['snapshotId'])
else:
print('Not supported: {0}'.format(event['detail']['eventName']))
# Create Tags
client.create_tags(
Resources=resource_ids,
Tags=[
{
'Key': 'SecureTag',
'Value': 'true'
},
{
'Key': 'Name',
'Value': 'testing123'
}
]
)
except Exception as e:
print('Error - reason "%s"' % str(e))
| 29.328358
| 80
| 0.453944
|
4c3d2a864a7fc638d8cc7054a10ede916e9caabb
| 3,062
|
py
|
Python
|
SDK/Examples/Python/Lib3MF_Example.py
|
alexanderoster/lib3mf
|
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
|
[
"BSD-2-Clause"
] | 171
|
2015-04-30T21:54:02.000Z
|
2022-03-13T13:33:59.000Z
|
SDK/Examples/Python/Lib3MF_Example.py
|
alexanderoster/lib3mf
|
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
|
[
"BSD-2-Clause"
] | 190
|
2015-07-21T22:15:54.000Z
|
2022-03-30T15:48:37.000Z
|
SDK/Examples/Python/Lib3MF_Example.py
|
alexanderoster/lib3mf
|
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
|
[
"BSD-2-Clause"
] | 80
|
2015-04-30T22:15:54.000Z
|
2022-03-09T12:38:49.000Z
|
'''++
Copyright (C) 2019 3MF Consortium (Original Author)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0-develop.
Abstract: This is an autogenerated Python application that demonstrates the
usage of the Python bindings of the 3MF Library
Interface version: 2.2.0
'''
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "Bindings", "Python"))
import Lib3MF
def buildTriangle(mesh):
triangle = Lib3MF.Triangle()
position = Lib3MF.Position()
position.Coordinates[0] = 0
position.Coordinates[1] = 0
position.Coordinates[2] = 0
triangle.Indices[0] = mesh.AddVertex(position)
position.Coordinates[0] = 0
position.Coordinates[1] = 1
position.Coordinates[2] = 0
triangle.Indices[1] = mesh.AddVertex(position)
position.Coordinates[0] = 0
position.Coordinates[1] = 0
position.Coordinates[2] = 1
triangle.Indices[2] = mesh.AddVertex(position)
mesh.AddTriangle(triangle)
def main():
libpath = '../../Bin' # TODO add the location of the shared library binary here
wrapper = Lib3MF.Wrapper(os.path.join(libpath, "lib3mf"))
major, minor, micro = wrapper.GetLibraryVersion()
print("Lib3MF version: {:d}.{:d}.{:d}".format(major, minor, micro), end="")
hasInfo, prereleaseinfo = wrapper.GetPrereleaseInformation()
if hasInfo:
print("-"+prereleaseinfo, end="")
hasInfo, buildinfo = wrapper.GetBuildInformation()
if hasInfo:
print("+"+buildinfo, end="")
print("")
# this example is REALLY simplisitic, but you get the point :)
model = wrapper.CreateModel()
meshObject = model.AddMeshObject()
buildTriangle(meshObject)
writer = model.QueryWriter("3mf")
writer.WriteToFile("triangle.3mf")
if __name__ == "__main__":
try:
main()
except Lib3MF.ELib3MFException as e:
print(e)
| 33.648352
| 108
| 0.763227
|
028fac412fc61833760bad32181587779712d2da
| 6,420
|
py
|
Python
|
pyleecan/Classes/DXFImport.py
|
mxgnsr/pyleecan
|
2b0a04e4ae67c073a91362ab42332908fef53bdd
|
[
"Apache-2.0"
] | 2
|
2019-06-08T15:04:39.000Z
|
2020-09-07T13:32:22.000Z
|
pyleecan/Classes/DXFImport.py
|
mxgnsr/pyleecan
|
2b0a04e4ae67c073a91362ab42332908fef53bdd
|
[
"Apache-2.0"
] | null | null | null |
pyleecan/Classes/DXFImport.py
|
mxgnsr/pyleecan
|
2b0a04e4ae67c073a91362ab42332908fef53bdd
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Simulation/DXFImport.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Simulation/DXFImport
"""
from os import linesep
from logging import getLogger
from ._check import check_var, raise_
from ..Functions.get_logger import get_logger
from ..Functions.save import save
from ._frozen import FrozenClass
# Import all class method
# Try/catch to remove unnecessary dependencies in unused method
try:
from ..Methods.Simulation.DXFImport.get_surfaces import get_surfaces
except ImportError as error:
get_surfaces = error
from ._check import InitUnKnowClassError
class DXFImport(FrozenClass):
"""Use a DXF to define a lamination"""
VERSION = 1
# cf Methods.Simulation.DXFImport.get_surfaces
if isinstance(get_surfaces, ImportError):
get_surfaces = property(
fget=lambda x: raise_(
ImportError(
"Can't use DXFImport method get_surfaces: " + str(get_surfaces)
)
)
)
else:
get_surfaces = get_surfaces
# save method is available in all object
save = save
# generic copy method
def copy(self):
"""Return a copy of the class
"""
return type(self)(init_dict=self.as_dict())
# get_logger method is available in all object
get_logger = get_logger
def __init__(
self, file_path="", surf_dict={}, BC_list=[], init_dict=None, init_str=None
):
"""Constructor of the class. Can be use in three ways :
- __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
for Matrix, None will initialise the property with an empty Matrix
for pyleecan type, None will call the default constructor
- __init__ (init_dict = d) d must be a dictionnary with every properties as keys
- __init__ (init_str = s) s must be a string
s is the file path to load
ndarray or list can be given for Vector and Matrix
object or dict can be given for pyleecan Object"""
if init_str is not None: # Initialisation by str
from ..Functions.load import load
assert type(init_str) is str
# load the object from a file
obj = load(init_str)
assert type(obj) is type(self)
file_path = obj.file_path
surf_dict = obj.surf_dict
BC_list = obj.BC_list
if init_dict is not None: # Initialisation by dict
assert type(init_dict) is dict
# Overwrite default value with init_dict content
if "file_path" in list(init_dict.keys()):
file_path = init_dict["file_path"]
if "surf_dict" in list(init_dict.keys()):
surf_dict = init_dict["surf_dict"]
if "BC_list" in list(init_dict.keys()):
BC_list = init_dict["BC_list"]
# Initialisation by argument
self.parent = None
self.file_path = file_path
self.surf_dict = surf_dict
if BC_list == -1:
BC_list = []
self.BC_list = BC_list
# The class is frozen, for now it's impossible to add new properties
self._freeze()
def __str__(self):
"""Convert this objet in a readeable string (for print)"""
DXFImport_str = ""
if self.parent is None:
DXFImport_str += "parent = None " + linesep
else:
DXFImport_str += "parent = " + str(type(self.parent)) + " object" + linesep
DXFImport_str += 'file_path = "' + str(self.file_path) + '"' + linesep
DXFImport_str += "surf_dict = " + str(self.surf_dict) + linesep
DXFImport_str += (
"BC_list = "
+ linesep
+ str(self.BC_list).replace(linesep, linesep + "\t")
+ linesep
)
return DXFImport_str
def __eq__(self, other):
"""Compare two objects (skip parent)"""
if type(other) != type(self):
return False
if other.file_path != self.file_path:
return False
if other.surf_dict != self.surf_dict:
return False
if other.BC_list != self.BC_list:
return False
return True
def as_dict(self):
"""Convert this objet in a json seriable dict (can be use in __init__)
"""
DXFImport_dict = dict()
DXFImport_dict["file_path"] = self.file_path
DXFImport_dict["surf_dict"] = self.surf_dict
DXFImport_dict["BC_list"] = self.BC_list
# The class name is added to the dict fordeserialisation purpose
DXFImport_dict["__class__"] = "DXFImport"
return DXFImport_dict
def _set_None(self):
"""Set all the properties to None (except pyleecan object)"""
self.file_path = None
self.surf_dict = None
self.BC_list = None
def _get_file_path(self):
"""getter of file_path"""
return self._file_path
def _set_file_path(self, value):
"""setter of file_path"""
check_var("file_path", value, "str")
self._file_path = value
file_path = property(
fget=_get_file_path,
fset=_set_file_path,
doc=u"""Path to the DXF file to import
:Type: str
""",
)
def _get_surf_dict(self):
"""getter of surf_dict"""
return self._surf_dict
def _set_surf_dict(self, value):
"""setter of surf_dict"""
check_var("surf_dict", value, "dict")
self._surf_dict = value
surf_dict = property(
fget=_get_surf_dict,
fset=_set_surf_dict,
doc=u"""Dictionnary to assign the surfaces: key=complex reference point coordinate, value=label of the surface
:Type: dict
""",
)
def _get_BC_list(self):
"""getter of BC_list"""
return self._BC_list
def _set_BC_list(self, value):
"""setter of BC_list"""
check_var("BC_list", value, "list")
self._BC_list = value
BC_list = property(
fget=_get_BC_list,
fset=_set_BC_list,
doc=u"""List of tuple to apply boundary conditions (complex reference point coordinate, is_arc, label of the BC to apply)
:Type: list
""",
)
| 32.1
| 129
| 0.61028
|
67b888dd52899c05f771ac65893a43390b1a0eec
| 1,810
|
py
|
Python
|
mt/base/functional.py
|
inteplus/mtbase
|
b211f25110f95be8b78be3e44feb1c16789c13b8
|
[
"MIT"
] | null | null | null |
mt/base/functional.py
|
inteplus/mtbase
|
b211f25110f95be8b78be3e44feb1c16789c13b8
|
[
"MIT"
] | null | null | null |
mt/base/functional.py
|
inteplus/mtbase
|
b211f25110f95be8b78be3e44feb1c16789c13b8
|
[
"MIT"
] | null | null | null |
'''Utitilites related to composing funcions.'''
__all__ = ['on_list', 'join_funcs', 'iterator_as_generator']
def on_list(func):
'''Turns a function that operates on each element at a time into a function that operates on a colletion of elements at a time. Can be used as a decorator.
Parameters
----------
func : function
the function to build upon. Its expected form is `def func(x, *args, **kwargs) -> object`.
Returns
-------
function
a wrapper function `def func_on_list(list_x, *args, **kwargs) -> list_of_objects` that invokes `func(x, *args, **kwargs)` for each x in list_x.
'''
def func_on_list(list_x, *args, **kwargs):
return [func(x, *args, **kwargs) for x in list_x]
return func_on_list
def join_funcs(*funcs, left_to_right=True):
'''Concatenates functions taking a single argument into a single function.
Parameters
----------
*funcs : list
list of functions f1(x), f2(x), ..., fn(x)
left_to_right : boolean
whether to concatenate from left to right or from right to left.
Returns
-------
func : function
The function `f(x) = fn(...f2(f1(x))...)` if left_to_right is True, else `f(x) = f1(f2(...fn(x)...))`.
'''
def left_to_right_func(x):
for f in funcs:
x = f(x)
return x
def right_to_left_func(x):
for f in reversed(funcs):
x = f(x)
return x
return left_to_right_func if left_to_right else right_to_left_func
def iterator_as_generator(iterator):
'''Turns a Python iterator into a Python generator that generates items forever. Probably only useful for keras.'''
def asgenerator(iterator):
while True:
yield next(iterator)
return asgenerator(iterator)
| 29.672131
| 159
| 0.628177
|
0f831147437faad6fa88edb7049ef2d1d3c92e87
| 2,122
|
py
|
Python
|
ds-sdk-mini/DeepSecurity/IntrusionPrevention.py
|
zachwhaley/thus
|
22b006c4ea110fbdc09a79c38e49e79ba04bb4d4
|
[
"MIT"
] | 24
|
2020-09-10T18:34:04.000Z
|
2022-02-09T01:52:20.000Z
|
ds-sdk-mini/DeepSecurity/IntrusionPrevention.py
|
zachwhaley/thus
|
22b006c4ea110fbdc09a79c38e49e79ba04bb4d4
|
[
"MIT"
] | 5
|
2020-09-11T17:22:08.000Z
|
2021-09-08T15:51:58.000Z
|
ds-sdk-mini/DeepSecurity/IntrusionPrevention.py
|
zachwhaley/thus
|
22b006c4ea110fbdc09a79c38e49e79ba04bb4d4
|
[
"MIT"
] | 6
|
2020-09-10T20:03:00.000Z
|
2021-06-25T07:33:21.000Z
|
# Copyright (c) 2020. Brendan Johnson. All Rights Reserved.
#import connect
#import config
class IntrusionPrevention:
def __init__(self, config, connection):
self._config=config
self._connection = connection
## Application Types
def listTypes(self):
return self._connection.get(url='/applicationtypes')
def createType(self, payload):
return self._connection.post(url='/applicationtypes', data=payload)
def createType(self, applicationTypeID):
return self._connection.get(url='/applicationtypes/{applicationTypeID}'.format(applicationTypeID=applicationTypeID))
def modifyType(self, applicationTypeID, payload):
return self._connection.post(url='/applicationtypes/{applicationTypeID}'.format(applicationTypeID=applicationTypeID), data=payload)
def deleteType(self, applicationTypeID):
return self._connection.delete(url='/applicationtypes/{applicationTypeID}'.format(applicationTypeID=applicationTypeID))
def searchTypes(self, payload):
return self._connection.post(url='/applicationtypes/search', data=payload)
## Rules
def listRules(self):
return self._connection.get(url='/intrusionpreventionrules')
def createRules(self, payload):
return self._connection.post(url='/intrusionpreventionrules', data=payload)
def describeRule(self, intrusionPreventionRuleID):
return self._connection.get(url='/intrusionpreventionrules/{intrusionPreventionRuleID}'.format(intrusionPreventionRuleID=intrusionPreventionRuleID))
def modifyRule(self, intrusionPreventionRuleID, payload):
return self._connection.post(url='/intrusionpreventionrules/{intrusionPreventionRuleID}'.format(intrusionPreventionRuleID=intrusionPreventionRuleID), data=payload)
def deleteRule(self, intrusionPreventionRuleID):
return self._connection.delete(url='/intrusionpreventionrules/{intrusionPreventionRuleID}'.format(intrusionPreventionRuleID=intrusionPreventionRuleID))
def searchRules(self, payload):
return self._connection.post(url='/intrusionpreventionrules/search', data=payload)
| 58.944444
| 171
| 0.768615
|
91b5dc72e5f80a12991b89d62f564525112b912d
| 1,063
|
py
|
Python
|
migrations/versions/e604a3970f2b_initial_migration.py
|
samwel-chege/Pitches
|
06e8ad720e123958b64d8fef24a6eea3bee22715
|
[
"MIT"
] | null | null | null |
migrations/versions/e604a3970f2b_initial_migration.py
|
samwel-chege/Pitches
|
06e8ad720e123958b64d8fef24a6eea3bee22715
|
[
"MIT"
] | null | null | null |
migrations/versions/e604a3970f2b_initial_migration.py
|
samwel-chege/Pitches
|
06e8ad720e123958b64d8fef24a6eea3bee22715
|
[
"MIT"
] | null | null | null |
"""Initial Migration
Revision ID: e604a3970f2b
Revises:
Create Date: 2021-08-17 14:39:49.259942
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e604a3970f2b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('comments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('comment', sa.String(length=255), nullable=True),
sa.Column('author_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('comments')
op.drop_table('users')
# ### end Alembic commands ###
| 25.926829
| 65
| 0.668862
|
0e76e138188ee7432bfa0a8c0f3816a23608d503
| 56,475
|
py
|
Python
|
src/sage/combinat/set_partition.py
|
bopopescu/Sage-8
|
71be00ad5f25ca95381fae7cce96421ffdd43425
|
[
"BSL-1.0"
] | null | null | null |
src/sage/combinat/set_partition.py
|
bopopescu/Sage-8
|
71be00ad5f25ca95381fae7cce96421ffdd43425
|
[
"BSL-1.0"
] | null | null | null |
src/sage/combinat/set_partition.py
|
bopopescu/Sage-8
|
71be00ad5f25ca95381fae7cce96421ffdd43425
|
[
"BSL-1.0"
] | null | null | null |
r"""
Set Partitions
AUTHORS:
- Mike Hansen
- MuPAD-Combinat developers (for algorithms and design inspiration).
- Travis Scrimshaw (2013-02-28): Removed ``CombinatorialClass`` and added
entry point through :class:`SetPartition`.
"""
#*****************************************************************************
# Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>,
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# The full text of the GPL is available at:
#
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.sets.set import Set, is_Set
import itertools
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.list_clone import ClonableArray
from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
from sage.misc.classcall_metaclass import ClasscallMetaclass
from sage.rings.infinity import infinity
from sage.rings.integer import Integer
from sage.combinat.cartesian_product import CartesianProduct
from sage.combinat.misc import IterableFunctionCall
from sage.combinat.combinatorial_map import combinatorial_map
import sage.combinat.subset as subset
from sage.combinat.partition import Partition, Partitions
from sage.combinat.set_partition_ordered import OrderedSetPartitions
from sage.combinat.combinat import bell_number, stirling_number2
from sage.combinat.permutation import Permutation
from functools import reduce
class SetPartition(ClonableArray):
"""
A partition of a set.
A set partition `p` of a set `S` is a partition of `S` into subsets
called parts and represented as a set of sets. By extension, a set
partition of a nonnegative integer `n` is the set partition of the
integers from 1 to `n`. The number of set partitions of `n` is called
the `n`-th Bell number.
There is a natural integer partition associated with a set partition,
namely the nonincreasing sequence of sizes of all its parts.
There is a classical lattice associated with all set partitions of
`n`. The infimum of two set partitions is the set partition obtained
by intersecting all the parts of both set partitions. The supremum
is obtained by transitive closure of the relation `i` related to `j`
if and only if they are in the same part in at least one of the set
partitions.
We will use terminology from partitions, in particular the *length* of
a set partition `A = \{A_1, \ldots, A_k\}` is the number of parts of `A`
and is denoted by `|A| := k`. The *size* of `A` is the cardinality of `S`.
We will also sometimes use the notation `[n] := \{1, 2, \ldots, n\}`.
EXAMPLES:
There are 5 set partitions of the set `\{1,2,3\}`::
sage: SetPartitions(3).cardinality()
5
Here is the list of them::
sage: SetPartitions(3).list()
[{{1, 2, 3}},
{{1}, {2, 3}},
{{1, 3}, {2}},
{{1, 2}, {3}},
{{1}, {2}, {3}}]
There are 6 set partitions of `\{1,2,3,4\}` whose underlying partition is
`[2, 1, 1]`::
sage: SetPartitions(4, [2,1,1]).list()
[{{1}, {2}, {3, 4}},
{{1}, {2, 4}, {3}},
{{1}, {2, 3}, {4}},
{{1, 4}, {2}, {3}},
{{1, 3}, {2}, {4}},
{{1, 2}, {3}, {4}}]
Since :trac:`14140`, we can create a set partition directly by
:class:`SetPartition`, which creates the base set by taking the
union of the parts passed in::
sage: s = SetPartition([[1,3],[2,4]]); s
{{1, 3}, {2, 4}}
sage: s.parent()
Set partitions
"""
__metaclass__ = ClasscallMetaclass
@staticmethod
def __classcall_private__(cls, parts, check=True):
"""
Create a set partition from ``parts`` with the appropriate parent.
EXAMPLES::
sage: s = SetPartition([[1,3],[2,4]]); s
{{1, 3}, {2, 4}}
sage: s.parent()
Set partitions
"""
P = SetPartitions()
return P.element_class(P, parts)
def __init__(self, parent, s):
"""
Initialize ``self``.
EXAMPLES::
sage: S = SetPartitions(4)
sage: s = S([[1,3],[2,4]])
sage: TestSuite(s).run()
sage: SetPartition([])
{}
"""
ClonableArray.__init__(self, parent, sorted(map(Set, s), key=min))
def check(self):
"""
Check that we are a valid ordered set partition.
EXAMPLES::
sage: OS = OrderedSetPartitions(4)
sage: s = OS([[1, 3], [2, 4]])
sage: s.check()
"""
assert self in self.parent()
def __hash__(self):
"""
Return the hash of ``self``.
The parent is not included as part of the hash.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = SetPartition([[1], [2,3], [4]])
sage: B = P([[1], [2,3], [4]])
sage: hash(A) == hash(B)
True
"""
return sum(hash(x) for x in self)
def __eq__(self, y):
"""
Check equality of ``self`` and ``y``.
The parent is not included as part of the equality check.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = SetPartition([[1], [2,3], [4]])
sage: B = P([[1], [2,3], [4]])
sage: A == B
True
sage: C = P([[2, 3], [1], [4]])
sage: A == C
True
sage: D = P([[1], [2, 4], [3]])
sage: A == D
False
"""
if not isinstance(y, SetPartition):
return False
return list(self) == list(y)
def __lt__(self, y):
"""
Check that ``self`` is less than ``y``.
The ordering used is lexicographic, where:
- a set partition is considered as the list of its parts
sorted by increasing smallest element;
- each part is regarded as a list of its elements, sorted
in increasing order;
- the parts themselves are compared lexicographically.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: A < B
True
sage: C = P([[1,2,4], [3]])
sage: B < C
True
sage: B < B
False
sage: D = P([[1,4], [2], [3]])
sage: E = P([[1,4], [2,3]])
sage: D < E
True
sage: F = P([[1,2,4], [3]])
sage: E < C
False
sage: A < E
True
sage: A < C
True
"""
if not isinstance(y, SetPartition):
return False
return [sorted(_) for _ in self] < [sorted(_) for _ in y]
def __gt__(self, y):
"""
Check that ``self`` is greater than ``y``.
The ordering used is lexicographic, where:
- a set partition is considered as the list of its parts
sorted by increasing smallest element;
- each part is regarded as a list of its elements, sorted
in increasing order;
- the parts themselves are compared lexicographically.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: B > A
True
sage: A > B
False
"""
if not isinstance(y, SetPartition):
return False
return [sorted(_) for _ in self] > [sorted(_) for _ in y]
def __le__(self, y):
"""
Check that ``self`` is less than or equals ``y``.
The ordering used is lexicographic, where:
- a set partition is considered as the list of its parts
sorted by increasing smallest element;
- each part is regarded as a list of its elements, sorted
in increasing order;
- the parts themselves are compared lexicographically.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: A <= B
True
sage: A <= A
True
"""
return self.__eq__(y) or self.__lt__(y)
def __ge__(self, y):
"""
Check that ``self`` is greater than or equals ``y``.
The ordering used is lexicographic, where:
- a set partition is considered as the list of its parts
sorted by increasing smallest element;
- each part is regarded as a list of its elements, sorted
in increasing order;
- the parts themselves are compared lexicographically.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: B >= A
True
sage: B >= B
True
"""
return self.__eq__(y) or self.__gt__(y)
def _cmp_(self, y):
"""
Return the result of ``cmp``.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: A < B
True
sage: cmp(A, B)
-1
sage: cmp(B, A)
1
"""
if self < y:
return -1
if self > y:
return 1
return 0
__cmp__ = _cmp_
def __mul__(self, other):
r"""
The product of the set partitions ``self`` and ``other``.
The product of two set partitions `B` and `C` is defined as the
set partition whose parts are the nonempty intersections between
each part of `B` and each part of `C`. This product is also
the infimum of `B` and `C` in the classical set partition
lattice (that is, the coarsest set partition which is finer than
each of `B` and `C`). Consequently, ``inf`` acts as an alias for
this method.
.. SEEALSO::
:meth:`sup`
EXAMPLES::
sage: x = SetPartition([ [1,2], [3,5,4] ])
sage: y = SetPartition(( (3,1,2), (5,4) ))
sage: x * y
{{1, 2}, {3}, {4, 5}}
sage: S = SetPartitions(4)
sage: sp1 = S([[2,3,4], [1]])
sage: sp2 = S([[1,3], [2,4]])
sage: s = S([[2,4], [3], [1]])
sage: sp1.inf(sp2) == s
True
TESTS:
Here is a different implementation of the ``__mul__`` method
(one that was formerly used for the ``inf`` method, before it
was realized that the methods do the same thing)::
sage: def mul2(s, t):
....: temp = [ss.intersection(ts) for ss in s for ts in t]
....: temp = filter(lambda x: x != Set([]), temp)
....: return s.__class__(s.parent(), temp)
Let us check that this gives the same as ``__mul__`` on set
partitions of `\{1, 2, 3, 4\}`::
sage: all( all( mul2(s, t) == s * t for s in SetPartitions(4) )
....: for t in SetPartitions(4) )
True
"""
new_composition = []
for B in self:
for C in other:
BintC = B.intersection(C)
if BintC:
new_composition.append(BintC)
return SetPartition(new_composition)
inf = __mul__
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: S = SetPartitions(4)
sage: S([[1,3],[2,4]])
{{1, 3}, {2, 4}}
"""
return '{' + ', '.join(('{' + repr(sorted(x))[1:-1] + '}' for x in self)) + '}'
def _latex_(self):
r"""
Return a `\LaTeX` string representation of ``self``.
EXAMPLES::
sage: x = SetPartition([[1,2], [3,5,4]])
sage: latex(x)
\{\{1, 2\}, \{3, 4, 5\}\}
"""
return repr(self).replace("{",r"\{").replace("}",r"\}")
cardinality = ClonableArray.__len__
def sup(self, t):
"""
Return the supremum of ``self`` and ``t`` in the classical set
partition lattice.
The supremum of two set partitions `B` and `C` is obtained as the
transitive closure of the relation which relates `i` to `j` if
and only if `i` and `j` are in the same part in at least
one of the set partitions `B` and `C`.
.. SEEALSO::
:meth:`__mul__`
EXAMPLES::
sage: S = SetPartitions(4)
sage: sp1 = S([[2,3,4], [1]])
sage: sp2 = S([[1,3], [2,4]])
sage: s = S([[1,2,3,4]])
sage: sp1.sup(sp2) == s
True
"""
res = Set(list(self))
for p in t:
inters = Set([x for x in list(res) if x.intersection(p) != Set([])])
res = res.difference(inters).union(_set_union(inters))
return SetPartition(res)
def pipe(self, other):
r"""
Return the pipe of the set partitions ``self`` and ``other``.
The pipe of two set partitions is defined as follows:
For any integer `k` and any subset `I` of `\ZZ`, let `I + k`
denote the subset of `\ZZ` obtained by adding `k` to every
element of `k`.
If `B` and `C` are set partitions of `[n]` and `[m]`,
respectively, then the pipe of `B` and `C` is defined as the
set partition
.. MATH::
\{ B_1, B_2, \ldots, B_b,
C_1 + n, C_2 + n, \ldots, C_c + n \}
of `[n+m]`, where `B = \{ B_1, B_2, \ldots, B_b \}` and
`C = \{ C_1, C_2, \ldots, C_c \}`. This pipe is denoted by
`B | C`.
EXAMPLES::
sage: SetPartition([[1,3],[2,4]]).pipe(SetPartition([[1,3],[2]]))
{{1, 3}, {2, 4}, {5, 7}, {6}}
sage: SetPartition([]).pipe(SetPartition([[1,2],[3,5],[4]]))
{{1, 2}, {3, 5}, {4}}
sage: SetPartition([[1,2],[3,5],[4]]).pipe(SetPartition([]))
{{1, 2}, {3, 5}, {4}}
sage: SetPartition([[1,2],[3]]).pipe(SetPartition([[1]]))
{{1, 2}, {3}, {4}}
"""
# Note: GIGO if self and other are not standard.
parts = list(self)
n = self.base_set_cardinality()
for newpart in other:
raised_newpart = Set([i + n for i in newpart])
parts.append(raised_newpart)
return SetPartition(parts)
@combinatorial_map(name='shape')
def shape(self):
r"""
Return the integer partition whose parts are the sizes of the sets
in ``self``.
EXAMPLES::
sage: S = SetPartitions(5)
sage: x = S([[1,2], [3,5,4]])
sage: x.shape()
[3, 2]
sage: y = S([[2], [3,1], [5,4]])
sage: y.shape()
[2, 2, 1]
"""
return Partition(sorted(map(len, self), reverse=True))
# we define aliases for shape()
shape_partition = shape
to_partition = shape
@combinatorial_map(name='to permutation')
def to_permutation(self):
"""
Convert ``self`` to a permutation by considering the partitions as
cycles.
EXAMPLES::
sage: s = SetPartition([[1,3],[2,4]])
sage: s.to_permutation()
[3, 4, 1, 2]
"""
return Permutation(tuple( map(tuple, self.standard_form()) ))
def standard_form(self):
r"""
Return ``self`` as a list of lists.
This is not related to standard set partitions (which simply
means set partitions of `[n] = \{ 1, 2, \ldots , n \}` for some
integer `n`) or standardization (:meth:`standardization`).
EXAMPLES::
sage: [x.standard_form() for x in SetPartitions(4, [2,2])]
[[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[1, 4], [2, 3]]]
"""
return [list(_) for _ in self]
def apply_permutation(self, p):
r"""
Apply ``p`` to the underlying set of ``self``.
INPUT:
- ``p`` -- A permutation
EXAMPLES::
sage: x = SetPartition([[1,2], [3,5,4]])
sage: p = Permutation([2,1,4,5,3])
sage: x.apply_permutation(p)
{{1, 2}, {3, 4, 5}}
sage: q = Permutation([3,2,1,5,4])
sage: x.apply_permutation(q)
{{1, 4, 5}, {2, 3}}
"""
return self.__class__(self.parent(), [Set(map(p, B)) for B in self])
def is_noncrossing(self):
r"""
Check if ``self`` is noncrossing.
EXAMPLES::
sage: x = SetPartition([[1,2],[3,4]])
sage: x.is_noncrossing()
True
sage: x = SetPartition([[1,3],[2,4]])
sage: x.is_noncrossing()
False
AUTHOR: Florent Hivert
"""
l = list(self)
mins = [min(_) for _ in l]
maxs = [max(_) for _ in l]
for i in range(1, len(l)):
for j in range(i):
poss = [mins[i], maxs[i], mins[j], maxs[j]]
possort = sorted(poss)
cont = [possort.index(mins[i]), possort.index(maxs[i])]
if cont == [0,2] or cont == [1,3]:
return False
if (cont == [0,3] and
any(mins[j] < x < maxs[j] for x in l[i])):
return False
if (cont == [1,2] and
any(mins[i] < x < maxs[i] for x in l[j])):
return False
return True
def is_atomic(self):
"""
Return if ``self`` is an atomic set partition.
A (standard) set partition `A` can be split if there exist `j < i`
such that `\max(A_j) < \min(A_i)` where `A` is ordered by minimal
elements. This means we can write `A = B | C` for some nonempty set
partitions `B` and `C`. We call a set partition *atomic* if it
cannot be split and is nonempty. Here, the pipe symbol
`|` is as defined in method :meth:`pipe`.
EXAMPLES::
sage: SetPartition([[1,3], [2]]).is_atomic()
True
sage: SetPartition([[1,3], [2], [4]]).is_atomic()
False
sage: SetPartition([[1], [2,4], [3]]).is_atomic()
False
sage: SetPartition([[1,2,3,4]]).is_atomic()
True
sage: SetPartition([[1, 4], [2], [3]]).is_atomic()
True
sage: SetPartition([]).is_atomic()
False
"""
if len(self) == 0:
return False
maximum_so_far = max(self[0])
for S in self[1:]:
if maximum_so_far < min(S):
return False
maximum_so_far = max(maximum_so_far, max(S))
return True
def base_set(self):
"""
Return the base set of ``self``, which is the union of all parts
of ``self``.
EXAMPLES::
sage: SetPartition([[1], [2,3], [4]]).base_set()
{1, 2, 3, 4}
sage: SetPartition([[1,2,3,4]]).base_set()
{1, 2, 3, 4}
sage: SetPartition([]).base_set()
{}
"""
return reduce(lambda x,y: x.union(y), self, Set([]))
def base_set_cardinality(self):
"""
Return the cardinality of the base set of ``self``, which is the sum
of the sizes of the parts of ``self``.
This is also known as the *size* (sometimes the *weight*) of
a set partition.
EXAMPLES::
sage: SetPartition([[1], [2,3], [4]]).base_set_cardinality()
4
sage: SetPartition([[1,2,3,4]]).base_set_cardinality()
4
"""
return sum(len(x) for x in self)
size = base_set_cardinality
def standardization(self):
"""
Return the standardization of ``self``.
Given a set partition `A = \{A_1, \ldots, A_n\}` of an ordered
set `S`, the standardization of `A` is the set partition of
`\{1, 2, \ldots, |S|\}` obtained by replacing the elements of
the parts of `A` by the integers `1, 2, \ldots, |S|` in such
a way that their relative order is preserved (i. e., the
smallest element in the whole set partition is replaced by
`1`, the next-smallest by `2`, and so on).
EXAMPLES::
sage: SetPartition([[4], [1, 3]]).standardization()
{{1, 2}, {3}}
sage: SetPartition([[4], [6, 3]]).standardization()
{{1, 3}, {2}}
sage: SetPartition([]).standardization()
{}
"""
if len(self) == 0:
return self
temp = [list(_) for _ in self]
mins = [min(p) for p in temp]
over_max = max([max(p) for p in temp]) + 1
ret = [[] for i in range(len(temp))]
cur = 1
while min(mins) != over_max:
m = min(mins)
i = mins.index(m)
ret[i].append(cur)
cur += 1
temp[i].pop(temp[i].index(m))
if len(temp[i]) != 0:
mins[i] = min(temp[i])
else:
mins[i] = over_max
return SetPartition(ret)
def restriction(self, I):
"""
Return the restriction of ``self`` to a subset ``I``
(which is given as a set or list or any other iterable).
EXAMPLES::
sage: A = SetPartition([[1], [2,3]])
sage: A.restriction([1,2])
{{1}, {2}}
sage: A.restriction([2,3])
{{2, 3}}
sage: A.restriction([])
{}
sage: A.restriction([4])
{}
"""
ret = []
for part in self:
newpart = [i for i in part if i in I]
if len(newpart) != 0:
ret.append(newpart)
return SetPartition(ret)
def ordered_set_partition_action(self, s):
r"""
Return the action of an ordered set partition ``s`` on ``self``.
Let `A = \{A_1, A_2, \ldots, A_k\}` be a set partition of some
set `S` and `s` be an ordered set partition (i.e., set composition)
of a subset of `[k]`. Let `A^{\downarrow}` denote the standardization
of `A`, and `A_{\{ i_1, i_2, \ldots, i_m \}}` denote the sub-partition
`\{A_{i_1}, A_{i_2}, \ldots, A_{i_m}\}` for any subset
`\{i_1, \ldots, i_m\}` of `\{1, \ldots, k\}`. We define the set
partition `s(A)` by
.. MATH::
s(A) = A_{s_1}^{\downarrow} | A_{s_2}^{\downarrow} | \cdots
| A_{s_q}^{\downarrow}.
where `s = (s_1, s_2, \ldots, s_q)`. Here, the pipe symbol
`|` is as defined in method :meth:`pipe`.
This is `s[A]` in section 2.3 in [LM2011]_.
INPUT:
- ``s`` -- an ordered set partition with base set a subset
of `\{1, \ldots, k\}`
EXAMPLES::
sage: A = SetPartition([[1], [2,4], [3]])
sage: s = OrderedSetPartition([[1,3], [2]])
sage: A.ordered_set_partition_action(s)
{{1}, {2}, {3, 4}}
sage: s = OrderedSetPartition([[2,3], [1]])
sage: A.ordered_set_partition_action(s)
{{1, 3}, {2}, {4}}
We create Figure 1 in [LM2011]_ (we note that there is a typo in the
lower-left corner of the table in the published version of the
paper, whereas the arXiv version gives the correct partition)::
sage: A = SetPartition([[1,3], [2,9], [4,5,8], [7]])
sage: B = SetPartition([[1,3], [2,8], [4,5,6], [7]])
sage: C = SetPartition([[1,5], [2,8], [3,4,6], [7]])
sage: s = OrderedSetPartition([[1,3], [2]])
sage: t = OrderedSetPartition([[2], [3,4]])
sage: u = OrderedSetPartition([[1], [2,3,4]])
sage: A.ordered_set_partition_action(s)
{{1, 2}, {3, 4, 5}, {6, 7}}
sage: A.ordered_set_partition_action(t)
{{1, 2}, {3, 4, 6}, {5}}
sage: A.ordered_set_partition_action(u)
{{1, 2}, {3, 8}, {4, 5, 7}, {6}}
sage: B.ordered_set_partition_action(s)
{{1, 2}, {3, 4, 5}, {6, 7}}
sage: B.ordered_set_partition_action(t)
{{1, 2}, {3, 4, 5}, {6}}
sage: B.ordered_set_partition_action(u)
{{1, 2}, {3, 8}, {4, 5, 6}, {7}}
sage: C.ordered_set_partition_action(s)
{{1, 4}, {2, 3, 5}, {6, 7}}
sage: C.ordered_set_partition_action(t)
{{1, 2}, {3, 4, 5}, {6}}
sage: C.ordered_set_partition_action(u)
{{1, 2}, {3, 8}, {4, 5, 6}, {7}}
REFERENCES:
.. [LM2011] A. Lauve, M. Mastnak. *The primitives and antipode in
the Hopf algebra of symmetric functions in noncommuting variables*.
Advances in Applied Mathematics. **47** (2011). 536-544.
:arxiv:`1006.0367v3` :doi:`10.1016/j.aam.2011.01.002`.
"""
cur = 1
ret = []
for part in s:
sub_parts = [list(self[i-1]) for i in part] # -1 for indexing
# Standardizing sub_parts (the cur variable not being reset
# to 1 gives us the offset we want):
mins = [min(_) for _ in sub_parts]
over_max = max(map(max, sub_parts)) + 1
temp = [[] for i in range(len(part))]
while min(mins) != over_max:
m = min(mins)
i = mins.index(m)
temp[i].append(cur)
cur += 1
sub_parts[i].pop(sub_parts[i].index(m))
if len(sub_parts[i]) != 0:
mins[i] = min(sub_parts[i])
else:
mins[i] = over_max
ret += temp
return SetPartition(ret)
def refinements(self):
"""
Return a list of refinements of ``self``.
EXAMPLES::
sage: SetPartition([[1,3],[2,4]]).refinements()
[{{1, 3}, {2, 4}},
{{1, 3}, {2}, {4}},
{{1}, {2, 4}, {3}},
{{1}, {2}, {3}, {4}}]
sage: SetPartition([[1],[2,4],[3]]).refinements()
[{{1}, {2, 4}, {3}}, {{1}, {2}, {3}, {4}}]
sage: SetPartition([]).refinements()
[{}]
"""
L = [SetPartitions(part) for part in self]
return [SetPartition(sum(map(list, x), [])) for x in CartesianProduct(*L)]
def coarsenings(self):
"""
Return a list of coarsenings of ``self``.
EXAMPLES::
sage: SetPartition([[1,3],[2,4]]).coarsenings()
[{{1, 2, 3, 4}}, {{1, 3}, {2, 4}}]
sage: SetPartition([[1],[2,4],[3]]).coarsenings()
[{{1, 2, 3, 4}},
{{1}, {2, 3, 4}},
{{1, 3}, {2, 4}},
{{1, 2, 4}, {3}},
{{1}, {2, 4}, {3}}]
sage: SetPartition([]).coarsenings()
[{}]
"""
SP = SetPartitions(len(self))
def union(s):
# Return the partition obtained by combining, for every
# part of s, those parts of self which are indexed by
# the elements of this part of s into a single part.
ret = []
for part in s:
cur = Set([])
for i in part:
cur = cur.union(self[i-1]) # -1 for indexing
ret.append(cur)
return ret
return [SetPartition(union(s)) for s in SP]
def strict_coarsenings(self):
r"""
Return all strict coarsenings of ``self``.
Strict coarsening is the binary relation on set partitions
defined as the transitive-and-reflexive closure of the
relation `\prec` defined as follows: For two set partitions
`A` and `B`, we have `A \prec B` if there exist parts
`A_i, A_j` of `A` such that `\max(A_i) < \min(A_j)` and
`B = A \setminus \{A_i, A_j\} \cup \{ A_i \cup A_j \}`.
EXAMPLES::
sage: A = SetPartition([[1],[2,3],[4]])
sage: A.strict_coarsenings()
[{{1}, {2, 3}, {4}}, {{1, 2, 3}, {4}}, {{1, 4}, {2, 3}},
{{1}, {2, 3, 4}}, {{1, 2, 3, 4}}]
sage: SetPartition([[1],[2,4],[3]]).strict_coarsenings()
[{{1}, {2, 4}, {3}}, {{1, 2, 4}, {3}}, {{1, 3}, {2, 4}}]
sage: SetPartition([]).strict_coarsenings()
[{}]
"""
# This is more or less generic code for computing a
# transitive-and-reflexive closure by depth-first search.
todo = [self]
visited = set([self])
ret = [self]
while todo:
A = todo.pop()
for i, part in enumerate(A):
for j, other in enumerate(A[i+1:]):
if max(part) < min(other):
next = A[:i]
next.append(part.union(other))
next += A[i+1:i+1+j] + A[i+j+2:]
next = SetPartition(next)
if next not in visited:
todo.append(next)
visited.add(next)
ret.append(next)
return ret
def arcs(self):
r"""
Return ``self`` as a list of arcs.
Consider a set partition `X = \{X_1, X_2, \ldots, X_n\}`,
then the arcs are the pairs `i - j` such that `i,j \in X_k`
for some `k`.
EXAMPLES::
sage: A = SetPartition([[1],[2,3],[4]])
sage: A.arcs()
[(2, 3)]
sage: B = SetPartition([[1,3,6,7],[2,5],[4]])
sage: B.arcs()
[(1, 3), (3, 6), (6, 7), (2, 5)]
"""
arcs = []
for p in self:
p = sorted(p)
for i in range(len(p)-1):
arcs.append((p[i], p[i+1]))
return arcs
class SetPartitions(Parent, UniqueRepresentation):
r"""
An (unordered) partition of a set `S` is a set of pairwise
disjoint nonempty subsets with union `S`, and is represented
by a sorted list of such subsets.
``SetPartitions(s)`` returns the class of all set partitions of the set
``s``, which can be given as a set or a string; if a string, each
character is considered an element.
``SetPartitions(n)``, where ``n`` is an integer, returns the class of
all set partitions of the set `\{1, 2, \ldots, n\}`.
You may specify a second argument `k`. If `k` is an integer,
:class:`SetPartitions` returns the class of set partitions into `k` parts;
if it is an integer partition, :class:`SetPartitions` returns the class of
set partitions whose block sizes correspond to that integer partition.
The Bell number `B_n`, named in honor of Eric Temple Bell,
is the number of different partitions of a set with `n` elements.
EXAMPLES::
sage: S = [1,2,3,4]
sage: SetPartitions(S,2)
Set partitions of {1, 2, 3, 4} with 2 parts
sage: SetPartitions([1,2,3,4], [3,1]).list()
[{{1}, {2, 3, 4}}, {{1, 3, 4}, {2}}, {{1, 2, 4}, {3}}, {{1, 2, 3}, {4}}]
sage: SetPartitions(7, [3,3,1]).cardinality()
70
In strings, repeated letters are not considered distinct as of
:trac:`14140`::
sage: SetPartitions('abcde').cardinality()
52
sage: SetPartitions('aabcd').cardinality()
15
REFERENCES:
- :wikipedia:`Partition_of_a_set`
"""
@staticmethod
def __classcall_private__(cls, s=None, part=None):
"""
Normalize input to ensure a unique representation.
EXAMPLES::
sage: S = SetPartitions(4)
sage: T = SetPartitions([1,2,3,4])
sage: S is T
True
"""
if s is None:
return SetPartitions_all()
if isinstance(s, (int, Integer)):
s = frozenset(range(1, s+1))
else:
try:
if s.cardinality() == infinity:
raise ValueError("The set must be finite")
except AttributeError:
pass
s = frozenset(s)
if part is not None:
if isinstance(part, (int, Integer)):
if len(s) < part:
raise ValueError("part must be <= len(set)")
else:
return SetPartitions_setn(s, part)
else:
if part not in Partitions(len(s)):
raise ValueError("part must be a partition of %s"%len(s))
else:
return SetPartitions_setparts(s, Partition(part))
else:
return SetPartitions_set(s)
def __contains__(self, x):
"""
TESTS::
sage: S = SetPartitions(4, [2,2])
sage: SA = SetPartitions()
sage: all([sp in SA for sp in S])
True
sage: Set([Set([1,2]),Set([3,7])]) in SA
True
sage: Set([Set([1,2]),Set([2,3])]) in SA
False
sage: Set([]) in SA
True
"""
# x must be a set
if not (isinstance(x, (SetPartition, set, frozenset)) or is_Set(x)):
return False
# Check that all parts are disjoint
base_set = reduce( lambda x,y: x.union(y), map(Set, x), Set([]) )
if len(base_set) != sum(map(len, x)):
return False
# Check to make sure each element of x is a set
for s in x:
if not (isinstance(s, (set, frozenset)) or is_Set(s)):
return False
return True
def _element_constructor_(self, s):
"""
Construct an element of ``self`` from ``s``.
INPUT:
- ``s`` -- A set of sets
EXAMPLES::
sage: S = SetPartitions(4)
sage: elt = S([[1,3],[2,4]]); elt
{{1, 3}, {2, 4}}
sage: P = SetPartitions()
sage: P(elt).parent() is P
True
sage: S = SetPartitions([])
sage: S([])
{}
"""
if isinstance(s, SetPartition):
if s.parent() is self:
return s
if isinstance(s.parent(), SetPartitions):
return self.element_class(self, list(s))
raise ValueError("cannot convert %s into an element of %s"%(s, self))
return self.element_class(self, s)
Element = SetPartition
def _iterator_part(self, part):
"""
Return an iterator for the set partitions with block sizes
corresponding to the partition ``part``.
INPUT:
- ``part`` -- a :class:`Partition` object
EXAMPLES::
sage: S = SetPartitions(3)
sage: it = S._iterator_part(Partition([1,1,1]))
sage: list(sorted(map(list, next(it))))
[[1], [2], [3]]
sage: S21 = SetPartitions(3,Partition([2,1]))
sage: len(list(S._iterator_part(Partition([2,1])))) == S21.cardinality()
True
"""
nonzero = []
expo = [0]+part.to_exp()
for i in range(len(expo)):
if expo[i] != 0:
nonzero.append([i, expo[i]])
taillesblocs = [(x[0])*(x[1]) for x in nonzero]
blocs = OrderedSetPartitions(self._set, taillesblocs)
for b in blocs:
lb = [IterableFunctionCall(_listbloc, nonzero[i][0], nonzero[i][1], b[i]) for i in range(len(nonzero))]
for x in itertools.imap(lambda x: _union(x), CartesianProduct( *lb )):
yield x
def is_less_than(self, s, t):
r"""
Check if `s < t` in the refinement ordering on set partitions.
This means that `s` is a refinement of `t` and satisfies
`s \neq t`.
A set partition `s` is said to be a refinement of a set
partition `t` of the same set if and only if each part of
`s` is a subset of a part of `t`.
EXAMPLES::
sage: S = SetPartitions(4)
sage: s = S([[1,3],[2,4]])
sage: t = S([[1],[2],[3],[4]])
sage: S.is_less_than(t, s)
True
sage: S.is_less_than(s, t)
False
sage: S.is_less_than(s, s)
False
"""
if hasattr(s.parent(), "_set"):
S = s.parent()._set
else:
S = s.base_set()
if hasattr(t.parent(), "_set"):
T = t.parent()._set
else:
T = t.base_set()
if S != T:
raise ValueError("cannot compare partitions of different sets")
if s == t:
return False
for p in s:
if len([ z for z in list(t) if z.intersection(p) != Set([]) ]) != 1:
return False
return True
lt = is_less_than
def is_strict_refinement(self, s, t):
r"""
Return ``True`` if ``s`` is a strict refinement of ``t`` and
satisfies `s \neq t`.
A set partition `s` is said to be a strict refinement of a set
partition `t` of the same set if and only if one can obtain
`t` from `s` by repeatedly combining pairs of parts whose
convex hulls don't intersect (i. e., whenever we are combining
two parts, the maximum of each of them should be smaller than
the minimum of the other).
EXAMPLES::
sage: S = SetPartitions(4)
sage: s = S([[1],[2],[3],[4]])
sage: t = S([[1,3],[2,4]])
sage: u = S([[1,2,3,4]])
sage: S.is_strict_refinement(s, t)
True
sage: S.is_strict_refinement(t, u)
False
sage: A = SetPartition([[1,3],[2,4]])
sage: B = SetPartition([[1,2,3,4]])
sage: S.is_strict_refinement(s, A)
True
sage: S.is_strict_refinement(t, B)
False
"""
if hasattr(s.parent(), "_set"):
S = s.parent()._set
else:
S = frozenset(s.base_set())
if hasattr(t.parent(), "_set"):
T = t.parent()._set
else:
T = frozenset(t.base_set())
if S != T:
raise ValueError("cannot compare partitions of different sets")
if s == t:
return False
for p in t:
L = [x for x in list(s) if x.issubset(p)]
if sum(len(x) for x in L) != len(p) \
or any(max(L[i]) > min(L[i+1]) for i in range(len(L)-1)):
return False
return True
class SetPartitions_all(SetPartitions):
r"""
All set partitions.
"""
def __init__(self):
"""
Initialize ``self``.
EXAMPLES::
sage: S = SetPartitions()
sage: TestSuite(S).run()
"""
SetPartitions.__init__(self, category=InfiniteEnumeratedSets())
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: SetPartitions()
Set partitions
"""
return "Set partitions"
def __iter__(self):
"""
Iterate over ``self``.
EXAMPLES::
sage: it = SetPartitions().__iter__()
sage: [next(it) for x in range(10)]
[{}, {{1}}, {{1, 2}}, {{1}, {2}}, {{1, 2, 3}}, {{1}, {2, 3}},
{{1, 3}, {2}}, {{1, 2}, {3}}, {{1}, {2}, {3}}, {{1, 2, 3, 4}}]
"""
n = 0
while True:
for x in SetPartitions_set(frozenset(range(1, n+1))):
yield self.element_class(self, list(x))
n += 1
class SetPartitions_set(SetPartitions):
"""
Set partitions of a fixed set `S`.
"""
@staticmethod
def __classcall_private__(cls, s):
"""
Normalize ``s`` to ensure a unique representation.
EXAMPLES::
sage: S1 = SetPartitions(set([2,1,4]))
sage: S2 = SetPartitions([4,1,2])
sage: S3 = SetPartitions((1,2,4))
sage: S1 is S2, S1 is S3
(True, True)
"""
return super(SetPartitions_set, cls).__classcall__(cls, frozenset(s))
def __init__(self, s):
"""
Initialize ``self``.
EXAMPLES::
sage: S = SetPartitions(3)
sage: TestSuite(S).run()
sage: SetPartitions(0).list()
[{}]
sage: SetPartitions([]).list()
[{}]
"""
self._set = s
SetPartitions.__init__(self, category=FiniteEnumeratedSets())
def _repr_(self):
"""
TESTS::
sage: SetPartitions([1,2,3])
Set partitions of {1, 2, 3}
"""
return "Set partitions of %s"%(Set(self._set))
def __contains__(self, x):
"""
TESTS::
sage: S = SetPartitions(4, [2,2])
sage: all([sp in S for sp in S])
True
sage: SetPartition([[1,3],[2,4]]) in SetPartitions(3)
False
sage: SetPartition([[1,3],[2,4]]) in SetPartitions(4, [3,1])
False
sage: SetPartition([[2],[1,3,4]]) in SetPartitions(4, [3,1])
True
"""
# Must pass the general check
if not SetPartitions.__contains__(self, x):
return False
# Make sure that the number of elements match up
if sum(map(len, x)) != len(self._set):
return False
# Make sure that the union of all the sets is the original set
if reduce(lambda u, s: u.union(Set(s)), x, Set([])) != Set(self._set):
return False
return True
def cardinality(self):
"""
Return the number of set partitions of the set `S`.
The cardinality is given by the `n`-th Bell number where `n` is the
number of elements in the set `S`.
EXAMPLES::
sage: SetPartitions([1,2,3,4]).cardinality()
15
sage: SetPartitions(3).cardinality()
5
sage: SetPartitions(3,2).cardinality()
3
sage: SetPartitions([]).cardinality()
1
"""
return bell_number(len(self._set))
def __iter__(self):
"""
Iterate over ``self``.
EXAMPLES::
sage: SetPartitions(3).list()
[{{1, 2, 3}}, {{1}, {2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}}, {{1}, {2}, {3}}]
"""
for p in Partitions(len(self._set)):
for sp in self._iterator_part(p):
yield self.element_class(self, sp)
def base_set(self):
"""
Return the base set of ``self``.
EXAMPLES::
sage: SetPartitions(3).base_set()
{1, 2, 3}
"""
return Set(self._set)
def base_set_cardinality(self):
"""
Return the cardinality of the base set of ``self``.
EXAMPLES::
sage: SetPartitions(3).base_set_cardinality()
3
"""
return len(self._set)
class SetPartitions_setparts(SetPartitions_set):
r"""
Class of all set partitions with fixed partition sizes corresponding to
an integer partition `\lambda`.
"""
@staticmethod
def __classcall_private__(cls, s, parts):
"""
Normalize input to ensure a unique representation.
EXAMPLES::
sage: S = SetPartitions(4, [2,2])
sage: T = SetPartitions([1,2,3,4], Partition([2,2]))
sage: S is T
True
"""
if isinstance(s, (int, Integer)):
s = xrange(1, s+1)
return super(SetPartitions_setparts, cls).__classcall__(cls, frozenset(s), Partition(parts))
def __init__(self, s, parts):
"""
TESTS::
sage: S = SetPartitions(4, [2,2])
sage: TestSuite(S).run()
"""
SetPartitions_set.__init__(self, s)
self.parts = parts
def _repr_(self):
"""
TESTS::
sage: SetPartitions(4, [2,2])
Set partitions of {1, 2, 3, 4} with sizes in [2, 2]
"""
return "Set partitions of %s with sizes in %s"%(Set(self._set), self.parts)
def cardinality(self):
r"""
Return the cardinality of ``self``.
This algorithm counts for each block of the partition the
number of ways to fill it using values from the set. Then,
for each distinct value `v` of block size, we divide the result by
the number of ways to arrange the blocks of size `v` in the
set partition.
For example, if we want to count the number of set partitions
of size 13 having [3,3,3,2,2] as underlying partition we
compute the number of ways to fill each block of the
partition, which is `\binom{13}{3} \binom{10}{3} \binom{7}{3}
\binom{4}{2}\binom{2}{2}` and as we have three blocks of size
`3` and two blocks of size `2`, we divide the result by
`3!2!` which gives us `600600`.
EXAMPLES::
sage: SetPartitions(3, [2,1]).cardinality()
3
sage: SetPartitions(13, Partition([3,3,3,2,2])).cardinality()
600600
TESTS::
sage: all((len(SetPartitions(size, part)) == SetPartitions(size, part).cardinality() for size in range(8) for part in Partitions(size)))
True
sage: sum((SetPartitions(13, p).cardinality() for p in Partitions(13))) == SetPartitions(13).cardinality()
True
"""
from sage.misc.misc_c import prod
remaining_subset_size = Integer(len(self._set))
cardinal = Integer(1)
for subset_size in self.parts:
cardinal *= remaining_subset_size.binomial(subset_size)
remaining_subset_size -= subset_size
repetitions = (Integer(rep).factorial()
for rep in self.parts.to_exp_dict().values()
if rep != 1)
cardinal /= prod(repetitions)
return Integer(cardinal)
def __iter__(self):
"""
An iterator for all the set partitions of the given set with
the given sizes.
EXAMPLES::
sage: SetPartitions(3, [2,1]).list()
[{{1}, {2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}}]
"""
for sp in self._iterator_part(self.parts):
yield self.element_class(self, sp)
def __contains__(self, x):
"""
Check containment.
TESTS::
sage: S = SetPartitions(4, [3,1])
sage: Set([Set([1,2,3]), Set([4])]) in S
True
sage: Set([Set([1,3]), Set([2,4])]) in S
False
sage: Set([Set([1,2,3,4])]) in S
False
"""
if not SetPartitions_set.__contains__(self, x):
return False
return sorted(map(len, x)) == list(reversed(self.parts))
class SetPartitions_setn(SetPartitions_set):
@staticmethod
def __classcall_private__(cls, s, n):
"""
Normalize ``s`` to ensure a unique representation.
EXAMPLES::
sage: S1 = SetPartitions(set([2,1,4]), 2)
sage: S2 = SetPartitions([4,1,2], 2)
sage: S3 = SetPartitions((1,2,4), 2)
sage: S1 is S2, S1 is S3
(True, True)
"""
return super(SetPartitions_setn, cls).__classcall__(cls, frozenset(s), n)
def __init__(self, s, n):
"""
TESTS::
sage: S = SetPartitions(5, 3)
sage: TestSuite(S).run()
"""
self.n = n
SetPartitions_set.__init__(self, s)
def _repr_(self):
"""
TESTS::
sage: SetPartitions(5, 3)
Set partitions of {1, 2, 3, 4, 5} with 3 parts
"""
return "Set partitions of %s with %s parts"%(Set(self._set), self.n)
def cardinality(self):
"""
The Stirling number of the second kind is the number of partitions
of a set of size `n` into `k` blocks.
EXAMPLES::
sage: SetPartitions(5, 3).cardinality()
25
sage: stirling_number2(5,3)
25
"""
return stirling_number2(len(self._set), self.n)
def __iter__(self):
"""
Iterate over ``self``.
EXAMPLES::
sage: SetPartitions(3).list()
[{{1, 2, 3}}, {{1}, {2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}}, {{1}, {2}, {3}}]
"""
for p in Partitions(len(self._set), length=self.n):
for sp in self._iterator_part(p):
yield self.element_class(self, sp)
def __contains__(self, x):
"""
Check containment.
TESTS::
sage: S = SetPartitions(4, 2)
sage: Set([Set([1,2,3]), Set([4])]) in S
True
sage: Set([Set([1,3]), Set([2,4])]) in S
True
sage: Set([Set([1,2,3,4])]) in S
False
"""
if not SetPartitions_set.__contains__(self, x):
return False
return len(x) == self.n
def _listbloc(n, nbrepets, listint=None):
r"""
Decompose a set of `n \times n` ``brepets`` integers (the list
``listint``) in ``nbrepets`` parts.
It is used in the algorithm to generate all set partitions.
.. WARNING::
Internal function that is not to be called by the user.
EXAMPLES::
sage: list(sage.combinat.set_partition._listbloc(2,1))
[{{1, 2}}]
sage: l = [Set([Set([3, 4]), Set([1, 2])]), Set([Set([2, 4]), Set([1, 3])]), Set([Set([2, 3]), Set([1, 4])])]
sage: list(sage.combinat.set_partition._listbloc(2,2,[1,2,3,4])) == l
True
"""
if isinstance(listint, (int, Integer)) or listint is None:
listint = Set(range(1,n+1))
if nbrepets == 1:
yield Set([listint])
return
l = sorted(listint)
smallest = Set(l[:1])
new_listint = Set(l[1:])
f = lambda u, v: u.union(_set_union([smallest,v]))
for ssens in subset.Subsets(new_listint, n-1):
for z in _listbloc(n, nbrepets-1, new_listint-ssens):
yield f(z,ssens)
def _union(s):
"""
TESTS::
sage: s = Set([ Set([1,2]), Set([3,4]) ])
sage: sage.combinat.set_partition._union(s)
{1, 2, 3, 4}
"""
result = Set([])
for ss in s:
result = result.union(ss)
return result
def _set_union(s):
"""
TESTS::
sage: s = Set([ Set([1,2]), Set([3,4]) ])
sage: sage.combinat.set_partition._set_union(s)
{{1, 2, 3, 4}}
"""
result = Set([])
for ss in s:
result = result.union(ss)
return Set([result])
def inf(s,t):
"""
Deprecated in :trac:`14140`. Use :meth:`SetPartition.inf()` instead.
EXAMPLES::
sage: sp1 = Set([Set([2,3,4]),Set([1])])
sage: sp2 = Set([Set([1,3]), Set([2,4])])
sage: s = Set([ Set([2,4]), Set([3]), Set([1])]) #{{2, 4}, {3}, {1}}
sage: sage.combinat.set_partition.inf(sp1, sp2) == s
doctest:...: DeprecationWarning: inf(s, t) is deprecated. Use s.inf(t) instead.
See http://trac.sagemath.org/14140 for details.
True
"""
from sage.misc.superseded import deprecation
deprecation(14140, 'inf(s, t) is deprecated. Use s.inf(t) instead.')
temp = [ss.intersection(ts) for ss in s for ts in t]
temp = [x for x in temp if x != Set([])]
return Set(temp)
def sup(s,t):
"""
Deprecated in :trac:`14140`. Use :meth:`SetPartition.sup()` instead.
EXAMPLES::
sage: sp1 = Set([Set([2,3,4]),Set([1])])
sage: sp2 = Set([Set([1,3]), Set([2,4])])
sage: s = Set([ Set([1,2,3,4]) ])
sage: sage.combinat.set_partition.sup(sp1, sp2) == s
doctest:...: DeprecationWarning: sup(s, t) is deprecated. Use s.sup(t) instead.
See http://trac.sagemath.org/14140 for details.
True
"""
from sage.misc.superseded import deprecation
deprecation(14140, 'sup(s, t) is deprecated. Use s.sup(t) instead.')
res = s
for p in t:
inters = Set([x for x in list(res) if x.intersection(p) != Set([])])
res = res.difference(inters).union(_set_union(inters))
return res
def standard_form(sp):
"""
Deprecated in :trac:`14140`. Use :meth:`SetPartition.standard_form()`
instead.
EXAMPLES::
sage: map(sage.combinat.set_partition.standard_form, SetPartitions(4, [2,2]))
doctest:...: DeprecationWarning: standard_form(sp) is deprecated. Use sp.standard_form() instead.
See http://trac.sagemath.org/14140 for details.
[[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[1, 4], [2, 3]]]
"""
from sage.misc.superseded import deprecation
deprecation(14140, 'standard_form(sp) is deprecated. Use sp.standard_form() instead.')
return [list(x) for x in sp]
def less(s, t):
"""
Deprecated in :trac:`14140`. Use :meth:`SetPartitions.is_less_than()`
instead.
EXAMPLES::
sage: z = SetPartitions(3).list()
sage: sage.combinat.set_partition.less(z[0], z[1])
doctest:...: DeprecationWarning: less(s, t) is deprecated. Use SetPartitions.is_less_tan(s, t) instead.
See http://trac.sagemath.org/14140 for details.
False
"""
from sage.misc.superseded import deprecation
deprecation(14140, 'less(s, t) is deprecated. Use SetPartitions.is_less_tan(s, t) instead.')
if _union(s) != _union(t):
raise ValueError("cannot compare partitions of different sets")
if s == t:
return False
for p in s:
if len([ z for z in list(t) if z.intersection(p) != Set([]) ]) != 1:
return False
return True
def cyclic_permutations_of_set_partition(set_part):
"""
Returns all combinations of cyclic permutations of each cell of the
set partition.
AUTHORS:
- Robert L. Miller
EXAMPLES::
sage: from sage.combinat.set_partition import cyclic_permutations_of_set_partition
sage: cyclic_permutations_of_set_partition([[1,2,3,4],[5,6,7]])
[[[1, 2, 3, 4], [5, 6, 7]],
[[1, 2, 4, 3], [5, 6, 7]],
[[1, 3, 2, 4], [5, 6, 7]],
[[1, 3, 4, 2], [5, 6, 7]],
[[1, 4, 2, 3], [5, 6, 7]],
[[1, 4, 3, 2], [5, 6, 7]],
[[1, 2, 3, 4], [5, 7, 6]],
[[1, 2, 4, 3], [5, 7, 6]],
[[1, 3, 2, 4], [5, 7, 6]],
[[1, 3, 4, 2], [5, 7, 6]],
[[1, 4, 2, 3], [5, 7, 6]],
[[1, 4, 3, 2], [5, 7, 6]]]
"""
return list(cyclic_permutations_of_set_partition_iterator(set_part))
def cyclic_permutations_of_set_partition_iterator(set_part):
"""
Iterates over all combinations of cyclic permutations of each cell
of the set partition.
AUTHORS:
- Robert L. Miller
EXAMPLES::
sage: from sage.combinat.set_partition import cyclic_permutations_of_set_partition_iterator
sage: list(cyclic_permutations_of_set_partition_iterator([[1,2,3,4],[5,6,7]]))
[[[1, 2, 3, 4], [5, 6, 7]],
[[1, 2, 4, 3], [5, 6, 7]],
[[1, 3, 2, 4], [5, 6, 7]],
[[1, 3, 4, 2], [5, 6, 7]],
[[1, 4, 2, 3], [5, 6, 7]],
[[1, 4, 3, 2], [5, 6, 7]],
[[1, 2, 3, 4], [5, 7, 6]],
[[1, 2, 4, 3], [5, 7, 6]],
[[1, 3, 2, 4], [5, 7, 6]],
[[1, 3, 4, 2], [5, 7, 6]],
[[1, 4, 2, 3], [5, 7, 6]],
[[1, 4, 3, 2], [5, 7, 6]]]
"""
from sage.combinat.permutation import CyclicPermutations
if len(set_part) == 1:
for i in CyclicPermutations(set_part[0]):
yield [i]
else:
for right in cyclic_permutations_of_set_partition_iterator(set_part[1:]):
for perm in CyclicPermutations(set_part[0]):
yield [perm] + right
| 31.515067
| 148
| 0.504807
|
daeeef092777560da767e254a741b2192a0df3fb
| 1,481
|
py
|
Python
|
2019-04-15/sqrt.py
|
williamsirotkin/archive
|
8c909e232ee979df9ba0c0c0384f2e4770b37cf7
|
[
"Unlicense"
] | 2
|
2018-10-16T03:17:53.000Z
|
2018-10-16T17:49:10.000Z
|
2019-04-15/sqrt.py
|
williamsirotkin/archive
|
8c909e232ee979df9ba0c0c0384f2e4770b37cf7
|
[
"Unlicense"
] | null | null | null |
2019-04-15/sqrt.py
|
williamsirotkin/archive
|
8c909e232ee979df9ba0c0c0384f2e4770b37cf7
|
[
"Unlicense"
] | null | null | null |
def sqrt(n, accuracy=0.001):
'''Compute the square root of `n`.
The value of `n` must be between 0 and 16,777,216 (i.e. 2^24).
This function implements a naive binary search. There are MUCH better
algorithms, though most require a math background through Calc 2.
See the Wikipedia page:
<https://en.wikipedia.org/wiki/Methods_of_computing_square_roots>
Most real-world software square root algorithms are based on the CORDIC
method: <https://en.wikipedia.org/wiki/CORDIC>
Arguments:
n (int):
The value to square-root. It must be between 0 and 16,777,216.
accuracy (float):
The error of the solution will be no greater than this value.
Returns:
float:
The square root of ``n``.
'''
# Check that the input is valid: 0 <= n <= 16777216.
if n < 0:
raise ValueError('input must not be negative')
elif n == 0:
return 0
elif n < 16777216:
lo = accuracy # The smallest non-zero solution is equal to the accuracy.
hi = 4096
elif n == 16777216:
return 4096
else:
raise ValueError('input must not be greater than or equal to 2^24')
# Binary search until we reach the desired accuracy.
while accuracy < hi - lo:
mid = (hi + lo) / 2
if mid ** 2 <= n:
lo = mid
else:
hi = mid
# Return the average of the hi and lo estimates.
return (hi + lo) / 2
| 30.854167
| 81
| 0.603646
|
2ac79377f8ef8c66f279e8c68c44c8bd61d87dbb
| 462
|
py
|
Python
|
mmpose/datasets/datasets/bottom_up/__init__.py
|
nightfuryyy/mmpose
|
910d9e31dd9d46e3329be1b7567e6309d70ab64c
|
[
"Apache-2.0"
] | 1,775
|
2020-07-10T01:20:01.000Z
|
2022-03-31T16:31:50.000Z
|
mmpose/datasets/datasets/bottom_up/__init__.py
|
KHB1698/mmpose
|
93c3a742c540dfb4ca515ad545cef705a07d90b4
|
[
"Apache-2.0"
] | 1,021
|
2020-07-11T11:40:24.000Z
|
2022-03-31T14:32:26.000Z
|
mmpose/datasets/datasets/bottom_up/__init__.py
|
KHB1698/mmpose
|
93c3a742c540dfb4ca515ad545cef705a07d90b4
|
[
"Apache-2.0"
] | 477
|
2020-07-11T11:27:51.000Z
|
2022-03-31T09:42:25.000Z
|
# Copyright (c) OpenMMLab. All rights reserved.
from .bottom_up_aic import BottomUpAicDataset
from .bottom_up_coco import BottomUpCocoDataset
from .bottom_up_coco_wholebody import BottomUpCocoWholeBodyDataset
from .bottom_up_crowdpose import BottomUpCrowdPoseDataset
from .bottom_up_mhp import BottomUpMhpDataset
__all__ = [
'BottomUpCocoDataset', 'BottomUpCrowdPoseDataset', 'BottomUpMhpDataset',
'BottomUpAicDataset', 'BottomUpCocoWholeBodyDataset'
]
| 38.5
| 76
| 0.844156
|
5b0eb8c5dd22d1e86d4fa6ea57e9ac9a9108c3dd
| 1,177
|
py
|
Python
|
Udemy/reversed.py
|
WSantos79/estudosPyCharm
|
dc75dd897574adf08f59fed70d556bb4f50dfe88
|
[
"MIT"
] | null | null | null |
Udemy/reversed.py
|
WSantos79/estudosPyCharm
|
dc75dd897574adf08f59fed70d556bb4f50dfe88
|
[
"MIT"
] | null | null | null |
Udemy/reversed.py
|
WSantos79/estudosPyCharm
|
dc75dd897574adf08f59fed70d556bb4f50dfe88
|
[
"MIT"
] | null | null | null |
"""
Reversed
OBS: Não confunda com a função reverse() que estudamos nas listas.
A função reverse() só funciona em listas.
Já a função reversed() funciona com qualquer iteravel.
Sua função é inverter o iterável.
A função reversed() retorna um iterável chamado List Reverse Iterator
"""
lista = [1, 2, 3, 4, 5]
res = reversed(lista)
print(res)
print(type(res))
# Podemos converter o elemento retornado para uma Lista, Tupla ou Conjunto
# Lista
print(list(reversed(lista)))
# Tupla
print(tuple(reversed(lista)))
# Conjunto(Set)
print(set(reversed(lista))) # Em conjuntos (SET), não definimos a ordem dos elementos
# Podemos iterar sobre o reversed
for letra in reversed('Wellington e Tarcia'):
print(letra, end='')
# Podemos fazer o mesmo sem o uso do For
print('\n')
print(''.join(list(reversed('Wellington e Tarcia'))))
# Já vimos como fazer isso mais fácil com o slice de strings
print('Wellington e Tarcia'[::-1])
# Podemos também utilizar o reversed() para fazer um loop for reverso
for n in reversed(range(0, 10)):
print(n)
# Apesar que já vimos como fazer isso utilizando o próprio range()
print('\n')
for n in range(9, -1, -1):
print(n)
| 21.017857
| 86
| 0.712829
|
c1b52e0dd99c0384abe55afa60e758a9044be965
| 477
|
py
|
Python
|
data/scripts/templates/object/tangible/mission/quest_item/shared_noren_krast_q2_needed.py
|
obi-two/GameServer
|
7d37024e2291a97d49522610cd8f1dbe5666afc2
|
[
"MIT"
] | 20
|
2015-02-23T15:11:56.000Z
|
2022-03-18T20:56:48.000Z
|
data/scripts/templates/object/tangible/mission/quest_item/shared_noren_krast_q2_needed.py
|
apathyboy/swganh
|
665128efe9154611dec4cb5efc61d246dd095984
|
[
"MIT"
] | null | null | null |
data/scripts/templates/object/tangible/mission/quest_item/shared_noren_krast_q2_needed.py
|
apathyboy/swganh
|
665128efe9154611dec4cb5efc61d246dd095984
|
[
"MIT"
] | 20
|
2015-04-04T16:35:59.000Z
|
2022-03-24T14:54:37.000Z
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/mission/quest_item/shared_noren_krast_q2_needed.iff"
result.attribute_template_id = -1
result.stfName("loot_corl_n","noren_krast_q2_needed")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result
| 28.058824
| 88
| 0.742138
|
71f11973c32e49a31f901dcc71a554c7c99e34d0
| 4,089
|
py
|
Python
|
CheckCooldown/CheckCooldown_StreamlabsParameter.py
|
EinWesen/slchatbotscripts
|
0e6fed2b319fe6a5fd20814109800f6891cefa95
|
[
"MIT"
] | null | null | null |
CheckCooldown/CheckCooldown_StreamlabsParameter.py
|
EinWesen/slchatbotscripts
|
0e6fed2b319fe6a5fd20814109800f6891cefa95
|
[
"MIT"
] | null | null | null |
CheckCooldown/CheckCooldown_StreamlabsParameter.py
|
EinWesen/slchatbotscripts
|
0e6fed2b319fe6a5fd20814109800f6891cefa95
|
[
"MIT"
] | null | null | null |
#---------------------------
# Import Libraries
#---------------------------
import clr
clr.AddReference("IronPython.SQLite.dll")
clr.AddReference("IronPython.Modules.dll")
#---------------------------
# [Required] Script Information
#---------------------------
ScriptName = "CoolDownParameter"
Website = "https://github.com/EinWesen"
Description = "$checkcooldown"
Creator = "EinWesen"
Version = "1.1.0.0"
#---------------------------
# Script specic Information
#---------------------------
CHECKUSERCOOLDOWN = "$checkcooldown"
COOLDOWN = "$cooldown"
COOLDOWNTYPE_USER = 1;
COOLDOWNTYPE_GLOBAL = 2;
COOLDOWNTYPE_NOMOD_USER = 3;
COOLDOWNTYPE_NOMOD_GLOBAL = 4;
#---------------------------
# [Required] Initialize Data (Only called on load)
#---------------------------
def Init():
return
def parseMyParameters(text):
# Very bad, but should work for most basic cases
# - find the first bracketpair (for this param)
# - split the contents in between by ","
# - ignore first and last "
end = text.index(")")
params = (text[text.index("(")+2:end-1]).split("\",\"", 3);
if len(params) == 4:
result = {"type": int(params[0]), "name" : params[1], "cooldown": int(params[2]), "message" : params[3], "length": end+1}
#Parent.Log(ScriptName, str(result))
return result
else:
raise ValueError("Incorrect number of parameters")
#end def parseMyParameters
def hasCooldown(cooldownType, command, userid):
if cooldownType == COOLDOWNTYPE_NOMOD_USER:
if not Parent.HasPermission(userid, "Moderator", ""):
return Parent.IsOnUserCooldown(ScriptName, command, userid)
else:
return False
elif cooldownType == COOLDOWNTYPE_NOMOD_GLOBAL:
if not Parent.HasPermission(userid, "Moderator", ""):
return Parent.IsOnCooldown(ScriptName, command)
else:
return False
elif cooldownType == COOLDOWNTYPE_USER:
return Parent.IsOnUserCooldown(ScriptName, command, userid)
elif cooldownType == COOLDOWNTYPE_GLOBAL:
return Parent.IsOnCooldown(ScriptName, command)
def getCooldown(cooldownType, command, userid):
if cooldownType == COOLDOWNTYPE_USER or cooldownType == COOLDOWNTYPE_NOMOD_USER:
return Parent.GetUserCooldownDuration(ScriptName, command, userid)
elif cooldownType == COOLDOWNTYPE_GLOBAL or cooldownType == COOLDOWNTYPE_NOMOD_GLOBAL:
return Parent.GetCooldownDuration(ScriptName, command)
def addCooldown(cooldownType, command, userid,seconds):
if cooldownType == COOLDOWNTYPE_USER or cooldownType == COOLDOWNTYPE_NOMOD_USER:
return Parent.AddUserCooldown(ScriptName, command, userid, seconds)
elif cooldownType == COOLDOWNTYPE_GLOBAL or cooldownType == COOLDOWNTYPE_NOMOD_GLOBAL:
# The Method is called Parent.addCooldown (as in addition), but it actually only sets the cooldown
# if the command is not on cooldown already, so we don't need to make sure it doesn't extend beyond the intended time.
# But this also means we have to live with the fact, that in case of COOLDOWNTYPE_NOMOD_GLOBAL
# the use of a command by a mod which is currently on global cooldown
# will not prevent others from using the command a second later (if the cooldown has elabsed by then)
return Parent.AddCooldown(ScriptName, command, seconds)
def Parse(parseString, userid, username, targetid, targetname, message):
if parseString.startswith(CHECKUSERCOOLDOWN):
#try:
parsedValues = parseMyParameters(parseString)
if hasCooldown(parsedValues["type"], parsedValues["name"], userid):
return parsedValues["message"].replace(COOLDOWN, str(getCooldown(parsedValues["type"], parsedValues["name"], userid)))
else:
addCooldown(parsedValues["type"], parsedValues["name"], userid, parsedValues["cooldown"])
return parseString[parsedValues["length"]:]
#except:
# return "): Error :("
#end if CHECKUSERCOOLDOWN
return parseString
| 41.30303
| 134
| 0.658352
|
332b343cf9915cd47280b2c76ca85cfd669ed7f6
| 27,991
|
py
|
Python
|
labour/models/signup.py
|
darkismus/kompassi
|
35dea2c7af2857a69cae5c5982b48f01ba56da1f
|
[
"CC-BY-3.0"
] | 13
|
2015-11-29T12:19:12.000Z
|
2021-02-21T15:42:11.000Z
|
labour/models/signup.py
|
darkismus/kompassi
|
35dea2c7af2857a69cae5c5982b48f01ba56da1f
|
[
"CC-BY-3.0"
] | 23
|
2015-04-29T19:43:34.000Z
|
2021-02-10T05:50:17.000Z
|
labour/models/signup.py
|
darkismus/kompassi
|
35dea2c7af2857a69cae5c5982b48f01ba56da1f
|
[
"CC-BY-3.0"
] | 11
|
2015-09-20T18:59:00.000Z
|
2020-02-07T08:47:34.000Z
|
from collections import OrderedDict
from django.conf import settings
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
from django.utils.translation import ugettext_lazy as _
from six import text_type
from core.csv_export import CsvExportMixin
from core.utils import (
alias_property,
ensure_user_group_membership,
get_previous_and_next,
time_bool_property,
)
from .constants import (
JOB_TITLE_LENGTH,
SIGNUP_STATE_NAMES,
NUM_FIRST_CATEGORIES,
SIGNUP_STATE_LABEL_CLASSES,
SIGNUP_STATE_BUTTON_CLASSES,
SIGNUP_STATE_DESCRIPTIONS,
SIGNUP_STATE_IMPERATIVES,
STATE_FLAGS_BY_NAME,
STATE_NAME_BY_FLAGS,
STATE_TIME_FIELDS,
SIGNUP_STATE_GROUPS,
)
class StateTransition(object):
"""
This class represents a potential state transition of a Signup from its current state to
another. The state transition is illustrated by a color (a CSS class) and a piece of text in the
imperative form.
Furthermore, we may want to disable some transitions that would otherwise be legal. These cases
warrant an explanation to the user.
These state transitions will be represented by buttons on the State tab of the admin signup view.
"""
__slots__ = ['signup', 'to_state', 'disabled_reason']
from core.utils import simple_object_repr as __repr__
def __init__(self, signup, to_state):
self.signup = signup
self.to_state = to_state
self.disabled_reason = self._determine_disabled_reason()
@property
def from_state(self):
return self.signup.state
@property
def css_class(self):
return SIGNUP_STATE_BUTTON_CLASSES[self.to_state]
@property
def text(self):
return SIGNUP_STATE_IMPERATIVES[self.to_state]
def _determine_disabled_reason(self):
# XXX In the Grand Order, the first flag is `is_active`.
# If the worker would end up in an inactive state, they must not have shifts.
if not STATE_FLAGS_BY_NAME[self.to_state][0] and self.signup.shifts.exists():
return _(
'This signup has shifts. Please remove the shifts before cancelling or '
'rejecting the signup.'
)
return ''
@property
def is_disabled(self):
return bool(self.disabled_reason)
class SignupMixin:
"""
Contains functionality common to both Signup and ArchivedSignup.
"""
@property
def job_category_accepted_labels(self):
state = self.state
label_class = SIGNUP_STATE_LABEL_CLASSES[state]
if state == 'new':
label_texts = [cat.name for cat in self.get_first_categories()]
labels = [(label_class, label_text, None) for label_text in label_texts]
if self.is_more_categories:
labels.append((label_class, '...', self.get_redacted_category_names()))
elif state == 'cancelled':
labels = [(label_class, 'Peruutettu', None)]
elif state == 'rejected':
labels = [(label_class, 'Hylätty', None)]
elif state == 'beyond_logic':
labels = [(label_class, 'Perätilassa', None)]
elif self.is_accepted:
label_texts = [cat.name for cat in self.job_categories_accepted.all()]
labels = [(label_class, label_text, None) for label_text in label_texts]
else:
from warnings import warn
warn('Unknown state: {state}'.format(self=self))
labels = []
return labels
@property
def personnel_class_labels(self):
label_texts = [pc.name for pc in self.personnel_classes.all()]
return [('label-default', label_text, None) for label_text in label_texts]
@property
def formatted_state(self):
return dict(SIGNUP_STATE_NAMES).get(self.state, '')
@property
def job_categories_label(self):
if self.state == 'new':
return 'Haetut tehtävät'
else:
return 'Hyväksytyt tehtävät'
@property
def state_label_class(self):
return SIGNUP_STATE_LABEL_CLASSES[self.state]
@property
def state_description(self):
return SIGNUP_STATE_DESCRIPTIONS.get(self.state, '')
class Signup(CsvExportMixin, SignupMixin, models.Model):
person = models.ForeignKey('core.Person', on_delete=models.CASCADE, related_name='signups')
event = models.ForeignKey('core.Event', on_delete=models.CASCADE)
personnel_classes = models.ManyToManyField('labour.PersonnelClass',
blank=True,
verbose_name='Henkilöstöluokat',
help_text='Mihin henkilöstöryhmiin tämä henkilö kuuluu? Henkilö saa valituista ryhmistä '
'ylimmän mukaisen badgen.',
)
job_categories = models.ManyToManyField('labour.JobCategory',
verbose_name='Haettavat tehtävät',
help_text='Valitse kaikki ne tehtävät, joissa olisit valmis työskentelemään '
'tapahtumassa. Huomaathan, että sinulle tarjottavia tehtäviä voi rajoittaa se, '
'mitä pätevyyksiä olet ilmoittanut sinulla olevan. Esimerkiksi järjestyksenvalvojaksi '
'voivat ilmoittautua ainoastaan JV-kortilliset.',
related_name='signup_set'
)
notes = models.TextField(
blank=True,
verbose_name='Käsittelijän merkinnät',
help_text=(
'Tämä kenttä ei normaalisti näy henkilölle itselleen, mutta jos tämä '
'pyytää henkilörekisteriotetta, kentän arvo on siihen sisällytettävä.'
),
)
created_at = models.DateTimeField(auto_now_add=True, verbose_name='Luotu')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Päivitetty')
job_categories_accepted = models.ManyToManyField('labour.JobCategory',
blank=True,
related_name='accepted_signup_set',
verbose_name='Hyväksytyt tehtäväalueet',
help_text='Tehtäväalueet, joilla hyväksytty vapaaehtoistyöntekijä tulee työskentelemään. '
'Tämän perusteella henkilölle mm. lähetetään oman tehtäväalueensa työvoimaohjeet. '
'Harmaalla merkityt tehtäväalueet ovat niitä, joihin hakija ei ole itse hakenut.'
)
job_categories_rejected = models.ManyToManyField('labour.JobCategory',
blank=True,
related_name='+',
verbose_name=_('Rejected job categories'),
help_text=_('The workforce manager may use this field to inform other workforce managers that '
'this applicant will not be accepted to a certain job category. This field is not visible '
'to the applicant, but should they request a record of their own information, this field will '
'be included.')
)
xxx_interim_shifts = models.TextField(
blank=True,
null=True,
default="",
verbose_name="Työvuorot",
help_text=(
"Tämä tekstikenttä on väliaikaisratkaisu, jolla vänkärin työvuorot voidaan "
"merkitä Kompassiin ja lähettää vänkärille työvoimaviestissä jo ennen kuin "
"lopullinen työvuorotyökalu on käyttökunnossa."
),
)
alternative_signup_form_used = models.ForeignKey('labour.AlternativeSignupForm', on_delete=models.CASCADE,
blank=True,
null=True,
verbose_name="Ilmoittautumislomake",
help_text=(
"Tämä kenttä ilmaisee, mitä ilmoittautumislomaketta hakemuksen täyttämiseen käytettiin. "
"Jos kenttä on tyhjä, käytettiin oletuslomaketta."
),
)
job_title = models.CharField(
max_length=JOB_TITLE_LENGTH,
blank=True,
default='',
verbose_name="Tehtävänimike",
help_text=(
"Printataan badgeen ym. Asetetaan automaattisesti hyväksyttyjen tehtäväalueiden perusteella, "
"mikäli kenttä jätetään tyhjäksi."
),
)
is_active = models.BooleanField(verbose_name='Aktiivinen', default=True)
time_accepted = models.DateTimeField(
null=True,
blank=True,
verbose_name='Hyväksytty',
)
time_confirmation_requested = models.DateTimeField(
null=True,
blank=True,
verbose_name='Vahvistusta vaadittu',
)
time_finished = models.DateTimeField(
null=True,
blank=True,
verbose_name='Vuorot valmiit',
)
time_complained = models.DateTimeField(
null=True,
blank=True,
verbose_name='Vuoroista reklamoitu',
)
time_cancelled = models.DateTimeField(
null=True,
blank=True,
verbose_name='Peruutettu',
)
time_rejected = models.DateTimeField(
null=True,
blank=True,
verbose_name='Hylätty',
)
time_arrived = models.DateTimeField(
null=True,
blank=True,
verbose_name='Saapunut tapahtumaan',
)
time_work_accepted = models.DateTimeField(
null=True,
blank=True,
verbose_name='Työpanos hyväksytty',
)
time_reprimanded = models.DateTimeField(
null=True,
blank=True,
verbose_name='Työpanoksesta esitetty moite',
)
is_accepted = time_bool_property('time_accepted')
is_confirmation_requested = time_bool_property('time_confirmation_requested')
is_finished = time_bool_property('time_finished')
is_complained = time_bool_property('time_complained')
is_cancelled = time_bool_property('time_cancelled')
is_rejected = time_bool_property('time_rejected')
is_arrived = time_bool_property('time_arrived')
is_work_accepted = time_bool_property('time_work_accepted')
is_workaccepted = alias_property('is_work_accepted') # for automagic groupiness
is_reprimanded = time_bool_property('time_reprimanded')
is_new = property(lambda self: self.state == 'new')
is_applicants = alias_property('is_active') # group is called applicants for historical purposes
is_confirmation = alias_property('is_confirmation_requested')
is_processed = property(lambda self: self.state != 'new')
class Meta:
verbose_name = _('signup')
verbose_name_plural = _('signups')
def __str__(self):
p = self.person.full_name if self.person else 'None'
e = self.event.name if self.event else 'None'
return '{p} / {e}'.format(**locals())
@property
def personnel_class(self):
"""
The highest personnel class of this Signup (possibly None).
"""
return self.personnel_classes.first()
@property
def signup_extra_model(self):
return self.event.labour_event_meta.signup_extra_model
@property
def signup_extra(self):
if not hasattr(self, '_signup_extra'):
SignupExtra = self.signup_extra_model
self._signup_extra = SignupExtra.for_signup(self)
return self._signup_extra
def get_first_categories(self):
return self.job_categories.all()[:NUM_FIRST_CATEGORIES]
@property
def is_more_categories(self):
return self.job_categories.count() > NUM_FIRST_CATEGORIES
def get_redacted_category_names(self):
return ', '.join(cat.name for cat in self.job_categories.all()[NUM_FIRST_CATEGORIES:])
@property
def some_job_title(self):
"""
Tries to figure a job title for this worker using the following methods in this order
1. A manually set job title
2. The title of the job category the worker is accepted into
3. A generic job title
"""
if self.job_title:
return self.job_title
elif self.job_categories_accepted.exists():
return self.job_categories_accepted.first().name
else:
return 'Työvoima'
@property
def granted_privileges(self):
if 'access' not in settings.INSTALLED_APPS:
return []
from access.models import GrantedPrivilege
return GrantedPrivilege.objects.filter(
person=self.person,
privilege__group_privileges__group__in=self.person.user.groups.all(),
privilege__group_privileges__event=self.event,
)
@property
def potential_privileges(self):
if 'access' not in settings.INSTALLED_APPS:
return []
from access.models import Privilege
return Privilege.get_potential_privileges(person=self.person, group_privileges__event=self.event)
@classmethod
def get_or_create_dummy(cls, accepted=False):
from core.models import Person, Event
from .job_category import JobCategory
person, unused = Person.get_or_create_dummy()
event, unused = Event.get_or_create_dummy()
job_category, unused = JobCategory.get_or_create_dummy()
signup, created = Signup.objects.get_or_create(person=person, event=event)
if created:
signup.job_categories.set([job_category])
if accepted:
signup.job_categories_accepted.set(signup.job_categories.all())
signup.personnel_classes.add(signup.job_categories.first().personnel_classes.first())
signup.state = 'accepted'
signup.save()
signup.apply_state()
return signup, created
@classmethod
def get_state_query_params(cls, state):
flag_values = STATE_FLAGS_BY_NAME[state]
assert len(STATE_TIME_FIELDS) == len(flag_values)
query_params = []
for time_field_name, flag_value in zip(STATE_TIME_FIELDS, flag_values):
time_field_preposition = '{}__isnull'.format(time_field_name)
query_params.append((time_field_preposition, not flag_value))
# First state flag is not a time bool field, but an actual bona fide boolean field.
# Also "is null" semantics mean that flag values are flipped, so we need to backflip it.
query_params[0] = ('is_active', not query_params[0][1])
return OrderedDict(query_params)
@classmethod
def mass_reject(cls, signups):
return cls._mass_state_change('new', 'rejected', signups)
@classmethod
def mass_request_confirmation(cls, signups):
return cls._mass_state_change('accepted', 'confirmation', signups)
@classmethod
def filter_signups_for_mass_send_shifts(cls, signups):
return signups.filter(
**cls.get_state_query_params('accepted')
).exclude(
xxx_interim_shifts='',
shifts__isnull=True,
)
@classmethod
def mass_send_shifts(cls, signups):
return cls._mass_state_change(
old_state='accepted',
new_state='finished',
signups=signups,
filter_func=cls.filter_signups_for_mass_send_shifts
)
@classmethod
def _mass_state_change(cls, old_state, new_state, signups, filter_func=None):
if filter_func is None:
signups = signups.filter(**Signup.get_state_query_params(old_state))
else:
signups = filter_func(signups)
for signup in signups:
signup.state = new_state
signup.save()
signup.apply_state()
return signups
def apply_state(self):
self.apply_state_sync()
if 'background_tasks' in settings.INSTALLED_APPS:
from ..tasks import signup_apply_state
signup_apply_state.delay(self.pk)
else:
self._apply_state()
def apply_state_sync(self):
self.apply_state_ensure_job_categories_accepted_is_set()
self.apply_state_ensure_personnel_class_is_set()
self.signup_extra.apply_state()
self.apply_state_create_badges()
def _apply_state(self):
self.apply_state_group_membership()
self.apply_state_email_aliases()
self.apply_state_send_messages()
def apply_state_group_membership(self):
from .job_category import JobCategory
from .personnel_class import PersonnelClass
groups_to_add = set()
groups_to_remove = set()
for group_suffix in SIGNUP_STATE_GROUPS:
should_belong_to_group = getattr(self, 'is_{group_suffix}'.format(group_suffix=group_suffix))
group = self.event.labour_event_meta.get_group(group_suffix)
if should_belong_to_group:
groups_to_add.add(group)
else:
groups_to_remove.add(group)
for job_category in JobCategory.objects.filter(event=self.event):
should_belong_to_group = self.job_categories_accepted.filter(pk=job_category.pk).exists()
group = self.event.labour_event_meta.get_group(job_category.slug)
if should_belong_to_group:
groups_to_add.add(group)
else:
groups_to_remove.add(group)
for personnel_class in PersonnelClass.objects.filter(event=self.event, app_label='labour'):
should_belong_to_group = self.personnel_classes.filter(pk=personnel_class.pk).exists()
group = self.event.labour_event_meta.get_group(personnel_class.slug)
if should_belong_to_group:
groups_to_add.add(group)
else:
groups_to_remove.add(group)
ensure_user_group_membership(self.person.user, groups_to_add, groups_to_remove)
def apply_state_email_aliases(self):
if 'access' not in settings.INSTALLED_APPS:
return
from access.models import GroupEmailAliasGrant
GroupEmailAliasGrant.ensure_aliases(self.person)
def apply_state_send_messages(self, resend=False):
if 'mailings' not in settings.INSTALLED_APPS:
return
from mailings.models import Message
Message.send_messages(self.event, 'labour', self.person)
def apply_state_ensure_job_categories_accepted_is_set(self):
if self.is_accepted and not self.job_categories_accepted.exists() and self.job_categories.count() == 1:
self.job_categories_accepted.add(self.job_categories.get())
def apply_state_ensure_personnel_class_is_set(self):
for app_label in self.job_categories_accepted.values_list('app_label', flat=True).distinct():
if self.personnel_classes.filter(app_label=app_label).exists():
continue
any_jca = self.job_categories_accepted.filter(app_label=app_label).first()
personnel_class = any_jca.personnel_classes.first()
self.personnel_classes.add(personnel_class)
def apply_state_create_badges(self):
if 'badges' not in settings.INSTALLED_APPS:
return
if self.event.badges_event_meta is None:
return
from badges.models import Badge
Badge.ensure(event=self.event, person=self.person)
def get_previous_and_next_signup(self):
queryset = self.event.signup_set.order_by('person__surname', 'person__first_name', 'id').all()
return get_previous_and_next(queryset, self)
@property
def _state_flags(self):
# The Grand Order is defined here.
return (
self.is_active,
self.is_accepted,
self.is_confirmation_requested,
self.is_finished,
self.is_complained,
self.is_arrived,
self.is_work_accepted,
self.is_reprimanded,
self.is_rejected,
self.is_cancelled,
)
@_state_flags.setter
def _state_flags(self, flags):
# These need to be in the Grand Order.
(
self.is_active,
self.is_accepted,
self.is_confirmation_requested,
self.is_finished,
self.is_complained,
self.is_arrived,
self.is_work_accepted,
self.is_reprimanded,
self.is_rejected,
self.is_cancelled,
) = flags
@property
def state(self):
return STATE_NAME_BY_FLAGS[self._state_flags]
@state.setter
def state(self, new_state):
self._state_flags = STATE_FLAGS_BY_NAME[new_state]
@property
def next_states(self):
cur_state = self.state
states = []
if cur_state == 'new':
states.extend(('accepted', 'rejected', 'cancelled'))
elif cur_state == 'accepted':
states.extend(('finished', 'confirmation', 'cancelled'))
elif cur_state == 'confirmation':
states.extend(('accepted', 'cancelled'))
elif cur_state == 'finished':
states.extend(('arrived', 'complained', 'no_show', 'relieved'))
elif cur_state == 'complained':
states.extend(('finished', 'relieved'))
elif cur_state == 'arrived':
states.extend(('honr_discharged', 'dish_discharged', 'relieved'))
elif cur_state == 'beyond_logic':
states.extend((
'new', 'accepted', 'finished', 'complained', 'rejected', 'cancelled', 'arrived',
'honr_discharged', 'no_show',
))
if cur_state != 'beyond_logic':
states.append('beyond_logic')
return states
@property
def next_states_buttons(self):
return [StateTransition(self, to_state) for to_state in self.next_states]
@property
def state_times(self):
return [
(
self._meta.get_field(field_name).verbose_name,
getattr(self, field_name, None),
)
for field_name in STATE_TIME_FIELDS
if getattr(self, field_name, None)
]
@property
def person_messages(self):
if 'mailings' in settings.INSTALLED_APPS:
if getattr(self, '_person_messages', None) is None:
self._person_messages = self.person.personmessage_set.filter(
message__recipient__event=self.event,
message__recipient__app_label='labour',
).order_by('-created_at')
return self._person_messages
else:
return []
@property
def have_person_messages(self):
if 'mailings' in settings.INSTALLED_APPS:
return self.person_messages.exists()
else:
return False
@property
def applicant_has_actions(self):
return any([
self.applicant_can_edit,
self.applicant_can_confirm,
self.applicant_can_cancel,
])
@property
def applicant_can_edit(self):
return self.state == 'new' and self.is_registration_open
@property
def is_registration_open(self):
if self.alternative_signup_form_used is not None:
return self.alternative_signup_form_used.is_active
else:
return self.event.labour_event_meta.is_registration_open
@property
def applicant_can_confirm(self):
return self.state == 'confirmation'
def confirm(self):
assert self.state == 'confirmation'
self.state = 'accepted'
self.save()
self.apply_state()
@property
def applicant_can_cancel(self):
return self.is_active and not self.is_cancelled and not self.is_rejected and \
not self.is_arrived
@property
def formatted_personnel_classes(self):
from .job_category import format_job_categories
return format_job_categories(self.personnel_classes.all())
@property
def formatted_job_categories_accepted(self):
from .job_category import format_job_categories
return format_job_categories(self.job_categories_accepted.all())
@property
def formatted_job_categories(self):
from .job_category import format_job_categories
return format_job_categories(self.job_categories.all())
@property
def formatted_shifts(self):
parts = []
if self.xxx_interim_shifts:
parts.append(self.xxx_interim_shifts)
parts.extend(text_type(shift) for shift in self.shifts.all())
return "\n\n".join(part for part in parts if part)
# for admin
@property
def full_name(self):
return self.person.full_name
@property
def info_links(self):
from .info_link import InfoLink
return InfoLink.objects.filter(
event=self.event,
group__user=self.person.user,
)
@property
def email_address(self):
from access.models import EmailAlias
email_alias = EmailAlias.objects.filter(
type__domain__organization=self.event.organization,
person=self.person,
).order_by('type__priority').first() # TODO order
return email_alias.email_address if email_alias else self.person.email
@classmethod
def get_csv_fields(cls, event):
if getattr(event, '_signup_csv_fields', None) is None:
from core.models import Person
event._signup_csv_fields = []
related_models = [Person, Signup]
fields_to_skip = [
# useless & non-serializable
(Person, 'user'),
(Signup, 'person'),
# too official
(Person, 'official_first_names'),
(Person, 'muncipality'),
]
SignupExtra = event.labour_event_meta.signup_extra_model
if SignupExtra is not None:
related_models.append(SignupExtra)
fields_to_skip.extend([
# SignupExtraBase ("V2")
(SignupExtra, 'event'),
(SignupExtra, 'person'),
# ObsoleteSignupExtraBaseV1
(SignupExtra, 'signup'),
])
# XXX HACK jv-kortin numero
if 'labour_common_qualifications' in settings.INSTALLED_APPS:
from labour_common_qualifications.models import JVKortti
related_models.append(JVKortti)
fields_to_skip.append((JVKortti, 'personqualification'))
for model in related_models:
for field in model._meta.fields:
if (model, field.name) in fields_to_skip:
continue
event._signup_csv_fields.append((model, field))
for field in model._meta.many_to_many:
event._signup_csv_fields.append((model, field))
return event._signup_csv_fields
def get_csv_related(self):
from core.models import Person
related = {Person: self.person}
signup_extra_model = self.signup_extra_model
if signup_extra_model:
related[signup_extra_model] = self.signup_extra
# XXX HACK jv-kortin numero
if 'labour_common_qualifications' in settings.INSTALLED_APPS:
from labour_common_qualifications.models import JVKortti
try:
jv_kortti = JVKortti.objects.get(personqualification__person=self.person)
related[JVKortti] = jv_kortti
except JVKortti.DoesNotExist:
related[JVKortti] = None
return related
def as_dict(self):
# XXX?
signup_extra = self.signup_extra
shift_wishes = signup_extra.shift_wishes if signup_extra.get_field('shift_wishes') else ''
total_work = signup_extra.total_work if signup_extra.get_field('total_work') else ''
shift_type = signup_extra.get_shift_type_display() if signup_extra.get_field('shift_type') else ''
return dict(
id=self.person.id,
fullName=self.person.full_name,
shiftWishes=shift_wishes,
totalWork=total_work,
currentlyAssigned=self.shifts.all().aggregate(
sum_hours=Coalesce(Sum('hours'), 0)
)['sum_hours'],
shiftType=shift_type,
)
@classmethod
def for_signup(cls, signup):
"""
Surveys make use of this method.
"""
return signup
| 33.362336
| 111
| 0.648744
|
2ef4a3879d651fbd77fd4cef505bcbc8065dab4a
| 3,063
|
py
|
Python
|
simple_CNN.py
|
XiangyuDing/Tensorflow-learning
|
233d7ef4ae61b333c3fb6ff0dcc8bcf31de9a359
|
[
"MIT"
] | null | null | null |
simple_CNN.py
|
XiangyuDing/Tensorflow-learning
|
233d7ef4ae61b333c3fb6ff0dcc8bcf31de9a359
|
[
"MIT"
] | null | null | null |
simple_CNN.py
|
XiangyuDing/Tensorflow-learning
|
233d7ef4ae61b333c3fb6ff0dcc8bcf31de9a359
|
[
"MIT"
] | null | null | null |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def compute_accuarcy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs:v_xs, keep_prob: 1})
correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs:v_xs, ys:v_ys, keep_prob: 1})
return result
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
# stride=[1, x_movement, y_movement, 1]
# Must have strides[0] = strides[3] = 1
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
# stride=[1, x_movement, y_movement, 1]
# Must have strides[0] = strides[3] = 1
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding = 'SAME')
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) / 255 # 28*28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])
# print(x_image.shape) # [n_samples, 28, 28, 1]
## conv1 layer ##
W_conv1 = weight_variable([5, 5, 1, 32]) # patch 5*5, in size 1, out size 32
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28*28*32
h_pool1 = max_pool_2x2(h_conv1) # output size 14*14*32
## conv2 layer ##
W_conv2 = weight_variable([5, 5, 32, 64]) # patch 5*5, in size 32, out size 64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14*14*64
h_pool2 = max_pool_2x2(h_conv2) # output size 7*7*64
## fuc1 layer ##
W_func1 = weight_variable([7*7*64, 1024])
b_func1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) # [n_samples, 7, 7, 64] >> [n_samples, 7*7*64]
h_func1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_func1) + b_func1)
h_func1_drop = tf.nn.dropout(h_func1, keep_prob)
## fuc2 layer ##
W_func2 = weight_variable([1024, 10])
b_func2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_func1_drop, W_func2) + b_func2)
# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1])) # loss
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
sess = tf.Session()
# important step
sess.run(tf.global_variables_initializer())
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if i % 50 == 0:
print(compute_accuracy(
mnist.test.images, mnist.test.lables))
| 39.779221
| 95
| 0.669931
|
52782195c923043fe2fdb557651e1476e368cfd8
| 71,551
|
py
|
Python
|
import_export_batches/views_admin.py
|
mattare2/WeVoteServer
|
c12f1a4a64a94a3b22f97c9582ed1058749326d5
|
[
"MIT"
] | null | null | null |
import_export_batches/views_admin.py
|
mattare2/WeVoteServer
|
c12f1a4a64a94a3b22f97c9582ed1058749326d5
|
[
"MIT"
] | null | null | null |
import_export_batches/views_admin.py
|
mattare2/WeVoteServer
|
c12f1a4a64a94a3b22f97c9582ed1058749326d5
|
[
"MIT"
] | null | null | null |
# import_export_batches/views_admin.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from .models import BatchDescription, BatchHeader, BatchHeaderMap, BatchManager, BatchRow, BatchSet, \
CONTEST_OFFICE, ELECTED_OFFICE, IMPORT_BALLOT_ITEM, \
BATCH_IMPORT_KEYS_ACCEPTED_FOR_CANDIDATES, BATCH_IMPORT_KEYS_ACCEPTED_FOR_CONTEST_OFFICES, \
BATCH_IMPORT_KEYS_ACCEPTED_FOR_ELECTED_OFFICES, BATCH_IMPORT_KEYS_ACCEPTED_FOR_MEASURES, \
BATCH_IMPORT_KEYS_ACCEPTED_FOR_ORGANIZATIONS, BATCH_IMPORT_KEYS_ACCEPTED_FOR_POLITICIANS, \
BATCH_IMPORT_KEYS_ACCEPTED_FOR_POSITIONS, BATCH_IMPORT_KEYS_ACCEPTED_FOR_BALLOT_ITEMS, \
IMPORT_CREATE, IMPORT_ADD_TO_EXISTING, IMPORT_VOTER
from .controllers import create_batch_header_translation_suggestions, create_batch_row_actions, \
create_or_update_batch_header_mapping, export_voter_list, import_data_from_batch_row_actions
from import_export_ballotpedia.controllers import groom_ballotpedia_data_for_processing, \
process_ballotpedia_voter_districts
from import_export_batches.controllers_ballotpedia import store_ballotpedia_json_response_to_import_batch_system
from admin_tools.views import redirect_to_sign_in_page
from ballot.models import MEASURE, CANDIDATE, POLITICIAN
import csv
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.messages import get_messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.utils.http import urlquote
from election.models import Election, ElectionManager
import json
from polling_location.models import PollingLocation, PollingLocationManager
from position.models import POSITION
import requests
from voter.models import voter_has_authority
from voter_guide.models import ORGANIZATION_WORD
# import wevote_functions.admin
from wevote_functions.functions import convert_to_int, positive_value_exists, STATE_CODE_MAP
# logger = wevote_functions.admin.get_logger(__name__)
@login_required
def batches_home_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# Create a voter_device_id and voter in the database if one doesn't exist yet
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
template_values = {
'google_civic_election_id': google_civic_election_id,
}
response = render(request, 'import_export_batches/index.html', template_values)
return response
@login_required
def batch_list_view(request):
"""
Display a list of import batches
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
kind_of_batch = request.GET.get('kind_of_batch', '')
batch_file = request.GET.get('batch_file', '')
batch_uri = request.GET.get('batch_uri', '')
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
polling_location_we_vote_id = request.GET.get('polling_location_we_vote_id', '')
polling_location_city = request.GET.get('polling_location_city', '')
polling_location_zip = request.GET.get('polling_location_zip', '')
show_all_elections = request.GET.get('show_all_elections', False)
messages_on_stage = get_messages(request)
batch_list_found = False
modified_batch_list = []
batch_manager = BatchManager()
try:
batch_list = BatchDescription.objects.order_by('-batch_header_id')
if positive_value_exists(google_civic_election_id):
batch_list = batch_list.filter(google_civic_election_id=google_civic_election_id)
if positive_value_exists(kind_of_batch):
batch_list = batch_list.filter(kind_of_batch__iexact=kind_of_batch)
if len(batch_list):
batch_list_found = True
for one_batch in batch_list:
one_batch.batch_row_action_count = batch_manager.fetch_batch_row_action_count(
one_batch.batch_header_id, kind_of_batch)
one_batch.batch_row_action_to_update_count = batch_manager.fetch_batch_row_action_count(
one_batch.batch_header_id, kind_of_batch, IMPORT_ADD_TO_EXISTING)
one_batch.batch_row_count = batch_manager.fetch_batch_row_count(one_batch.batch_header_id)
modified_batch_list.append(one_batch)
except BatchDescription.DoesNotExist:
# This is fine
batch_list_found = False
pass
polling_location_found = False
polling_location = PollingLocation()
polling_location_manager = PollingLocationManager()
election_state = ''
if not polling_location_found and positive_value_exists(polling_location_we_vote_id):
results = polling_location_manager.retrieve_polling_location_by_id(0, polling_location_we_vote_id)
if results['polling_location_found']:
polling_location = results['polling_location']
polling_location_we_vote_id = polling_location.we_vote_id
polling_location_id = polling_location.id
polling_location_found = True
election_state = polling_location.state
if google_civic_election_id:
election_manager = ElectionManager()
results = election_manager.retrieve_election(google_civic_election_id)
if results['election_found']:
election = results['election']
election_state = election.get_election_state()
polling_location_list = []
results = polling_location_manager.retrieve_polling_locations_in_city_or_state(
election_state, polling_location_city, polling_location_zip)
if results['polling_location_list_found']:
polling_location_list = results['polling_location_list']
if kind_of_batch == ORGANIZATION_WORD or kind_of_batch == ELECTED_OFFICE or kind_of_batch == POLITICIAN:
# We do not want to ask the person importing the file for an election, because it isn't used
ask_for_election = False
election_list = []
else:
ask_for_election = True
election_manager = ElectionManager()
if positive_value_exists(show_all_elections):
results = election_manager.retrieve_elections()
election_list = results['election_list']
else:
results = election_manager.retrieve_upcoming_elections()
election_list = results['election_list']
template_values = {
'messages_on_stage': messages_on_stage,
'batch_list': modified_batch_list,
'ask_for_election': ask_for_election,
'election_list': election_list,
'kind_of_batch': kind_of_batch,
'batch_file': batch_file,
'batch_uri': batch_uri,
'google_civic_election_id': convert_to_int(google_civic_election_id),
'polling_location_we_vote_id': polling_location_we_vote_id,
'polling_location': polling_location,
'polling_location_list': polling_location_list,
'polling_location_city': polling_location_city,
'polling_location_zip': polling_location_zip,
'show_all_elections': show_all_elections,
}
return render(request, 'import_export_batches/batch_list.html', template_values)
@login_required
def batch_list_process_view(request):
"""
Load in a new batch to start the importing process
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
kind_of_batch = request.POST.get('kind_of_batch', '')
batch_uri = request.POST.get('batch_uri', '')
batch_uri_encoded = urlquote(batch_uri) if positive_value_exists(batch_uri) else ""
google_civic_election_id = request.POST.get('google_civic_election_id', 0)
polling_location_we_vote_id = request.POST.get('polling_location_we_vote_id', "")
polling_location_city = request.POST.get('polling_location_city', '')
polling_location_zip = request.POST.get('polling_location_zip', '')
show_all_elections = request.POST.get('show_all_elections', "")
state_code = request.POST.get('state_code', "")
if kind_of_batch not in (MEASURE, ELECTED_OFFICE, CONTEST_OFFICE, CANDIDATE, ORGANIZATION_WORD, POSITION,
POLITICIAN, IMPORT_BALLOT_ITEM):
messages.add_message(request, messages.ERROR, 'The kind_of_batch is required for a batch import.')
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&google_civic_election_id=" + str(google_civic_election_id) +
"&polling_location_we_vote_id=" + str(polling_location_we_vote_id) +
"&polling_location_city=" + str(polling_location_city) +
"&polling_location_zip=" + str(polling_location_zip) +
"&show_all_elections=" + str(show_all_elections) +
"&batch_uri=" + batch_uri_encoded)
# If here we know we have the required variables
organization_we_vote_id = request.POST.get('organization_we_vote_id', '')
# Was form submitted, or was election just changed?
import_batch_button = request.POST.get('import_batch_button', '')
batch_file = None
if positive_value_exists(import_batch_button):
try:
if request.method == 'POST' and request.FILES['batch_file']:
batch_file = request.FILES['batch_file']
except KeyError:
pass
# Make sure we have a file to process // Used to only be able to import IMPORT_BALLOT_ITEM from file
if kind_of_batch in ORGANIZATION_WORD and not batch_file:
messages.add_message(request, messages.ERROR, 'Please select a file to import.')
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&polling_location_we_vote_id=" + str(polling_location_we_vote_id) +
"&google_civic_election_id=" + str(google_civic_election_id) +
"&polling_location_city=" + str(polling_location_city) +
"&polling_location_zip=" + str(polling_location_zip) +
"&show_all_elections=" + str(show_all_elections) +
"&batch_uri=" + batch_uri_encoded)
# Make sure we have a Google Civic Election ID *unless* we are uploading an organization
if kind_of_batch not in ORGANIZATION_WORD and not positive_value_exists(google_civic_election_id):
messages.add_message(request, messages.ERROR, 'This kind_of_batch (\"{kind_of_batch}\") requires you '
'to choose an election.'.format(kind_of_batch=kind_of_batch))
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&polling_location_we_vote_id=" + str(polling_location_we_vote_id) +
"&google_civic_election_id=" + str(google_civic_election_id) +
"&polling_location_city=" + str(polling_location_city) +
"&polling_location_zip=" + str(polling_location_zip) +
"&show_all_elections=" + str(show_all_elections) +
"&batch_uri=" + batch_uri_encoded)
# Make sure we have a polling_location_we_vote_id
if kind_of_batch in IMPORT_BALLOT_ITEM and not positive_value_exists(polling_location_we_vote_id):
messages.add_message(request, messages.ERROR, 'This kind_of_batch (\"{kind_of_batch}\") requires you '
'to choose a polling location.'
''.format(kind_of_batch=kind_of_batch))
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&polling_location_we_vote_id=" + str(polling_location_we_vote_id) +
"&google_civic_election_id=" + str(google_civic_election_id) +
"&polling_location_city=" + str(polling_location_city) +
"&polling_location_zip=" + str(polling_location_zip) +
"&show_all_elections=" + str(show_all_elections) +
"&batch_uri=" + batch_uri_encoded)
election_name = "" # For printing status
if positive_value_exists(google_civic_election_id):
election_manager = ElectionManager()
results = election_manager.retrieve_election(google_civic_election_id)
if results['election_found']:
election = results['election']
election_name = election.election_name
batch_header_id = 0
if positive_value_exists(import_batch_button): # If the button was pressed...
batch_manager = BatchManager()
if batch_file is not None:
results = batch_manager.create_batch_from_local_file_upload(
batch_file, kind_of_batch, google_civic_election_id, organization_we_vote_id,
polling_location_we_vote_id)
if results['batch_saved']:
messages.add_message(request, messages.INFO, 'Import batch for {election_name} election saved.'
''.format(election_name=election_name))
batch_header_id = results['batch_header_id']
else:
messages.add_message(request, messages.ERROR, results['status'])
elif positive_value_exists(batch_uri):
if "api.ballotpedia.org" in batch_uri:
# response = requests.get(VOTER_INFO_URL, params={
# "key": GOOGLE_CIVIC_API_KEY,
# "address": text_for_map_search,
# "electionId": incoming_google_civic_election_id,
# })
response = requests.get(batch_uri)
structured_json = json.loads(response.text)
if "api/contains" in batch_uri:
contains_api = True
else:
contains_api = False
groom_results = groom_ballotpedia_data_for_processing(structured_json, google_civic_election_id,
state_code, contains_api)
modified_json_list = groom_results['modified_json_list']
kind_of_batch = groom_results['kind_of_batch']
if contains_api:
ballot_items_results = process_ballotpedia_voter_districts(
google_civic_election_id, state_code, modified_json_list, polling_location_we_vote_id)
if ballot_items_results['ballot_items_found']:
modified_json_list = ballot_items_results['ballot_item_dict_list']
results = store_ballotpedia_json_response_to_import_batch_system(
modified_json_list, google_civic_election_id, kind_of_batch) # Add state_code=state_code ?
else:
# check file type
filetype = batch_manager.find_file_type(batch_uri)
if "xml" in filetype:
# file is XML
# Retrieve the VIP data from XML
results = batch_manager.create_batch_vip_xml(batch_uri, kind_of_batch, google_civic_election_id,
organization_we_vote_id)
else:
results = batch_manager.create_batch_from_uri(
batch_uri, kind_of_batch, google_civic_election_id, organization_we_vote_id)
if results['batch_saved']:
messages.add_message(request, messages.INFO, 'Import batch for {election_name} election saved.'
''.format(election_name=election_name))
batch_header_id = results['batch_header_id']
else:
messages.add_message(request, messages.ERROR, results['status'])
if positive_value_exists(batch_header_id):
# Go straight to the new batch
return HttpResponseRedirect(reverse('import_export_batches:batch_action_list', args=()) +
"?batch_header_id=" + str(batch_header_id) +
"&kind_of_batch=" + str(kind_of_batch) +
"&polling_location_we_vote_id=" + str(polling_location_we_vote_id) +
"&google_civic_election_id=" + str(google_civic_election_id) +
"&batch_uri=" + batch_uri_encoded)
else:
# Go to the batch listing page
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&polling_location_we_vote_id=" + str(polling_location_we_vote_id) +
"&google_civic_election_id=" + str(google_civic_election_id) +
"&polling_location_city=" + str(polling_location_city) +
"&polling_location_zip=" + str(polling_location_zip) +
"&show_all_elections=" + str(show_all_elections) +
"&batch_uri=" + batch_uri_encoded)
@login_required
def batch_action_list_view(request):
"""
Display row-by-row details of batch actions being reviewed, leading up to processing an entire batch.
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_set_list = []
polling_location_we_vote_id = ""
batch_header_id = convert_to_int(request.GET.get('batch_header_id', 0))
kind_of_batch = request.GET.get('kind_of_batch', '')
show_all = request.GET.get('show_all', False)
state_code = request.GET.get('state_code', '')
position_owner_organization_we_vote_id = request.GET.get('position_owner_organization_we_vote_id', '')
if not positive_value_exists(batch_header_id):
messages.add_message(request, messages.ERROR, 'Batch_header_id required.')
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch))
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
batch_set_id = 0
try:
batch_description = BatchDescription.objects.get(batch_header_id=batch_header_id)
batch_description_found = True
batch_set_id = batch_description.batch_set_id
google_civic_election_id = batch_description.google_civic_election_id
polling_location_we_vote_id = batch_description.polling_location_we_vote_id
except BatchDescription.DoesNotExist:
# This is fine
batch_description = BatchDescription()
batch_description_found = False
batch_set_list_found = False
# if batch_set_id exists, send data sets associated with this batch_set_id
if positive_value_exists(batch_set_id):
try:
batch_set_list = BatchSet.objects.get(id=batch_set_id)
if batch_set_list:
batch_set_list_found = True
except BatchSet.DoesNotExist:
# This is fine
batch_set_list = BatchSet()
batch_set_list_found = False
try:
batch_header_map = BatchHeaderMap.objects.get(batch_header_id=batch_header_id)
except BatchHeaderMap.DoesNotExist:
# This is fine
batch_header_map = BatchHeaderMap()
batch_list_found = False
try:
batch_row_count_query = BatchRow.objects.order_by('id')
batch_row_count_query = batch_row_count_query.filter(batch_header_id=batch_header_id)
if positive_value_exists(state_code):
batch_row_count_query = batch_row_count_query.filter(state_code__iexact=state_code)
batch_row_count = batch_row_count_query.count()
batch_row_query = BatchRow.objects.order_by('id')
batch_row_query = batch_row_query.filter(batch_header_id=batch_header_id)
if positive_value_exists(state_code):
batch_row_query = batch_row_query.filter(state_code__iexact=state_code)
batch_row_list = list(batch_row_query)
else:
if positive_value_exists(show_all):
batch_row_list = list(batch_row_query)
else:
batch_row_list = batch_row_query[:200]
if len(batch_row_list):
batch_list_found = True
except BatchDescription.DoesNotExist:
# This is fine
batch_row_list = []
batch_list_found = False
modified_batch_row_list = []
active_state_codes = []
batch_manager = BatchManager()
if batch_list_found:
for one_batch_row in batch_row_list:
if positive_value_exists(one_batch_row.state_code):
if one_batch_row.state_code not in active_state_codes:
active_state_codes.append(one_batch_row.state_code)
if kind_of_batch == CANDIDATE:
existing_results = batch_manager.retrieve_batch_row_action_candidate(batch_header_id, one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_candidate']
one_batch_row.kind_of_batch = CANDIDATE
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
elif kind_of_batch == CONTEST_OFFICE:
existing_results = batch_manager.retrieve_batch_row_action_contest_office(batch_header_id,
one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_contest_office']
one_batch_row.kind_of_batch = CONTEST_OFFICE
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
elif kind_of_batch == ELECTED_OFFICE:
existing_results = batch_manager.retrieve_batch_row_action_elected_office(batch_header_id,
one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_elected_office']
one_batch_row.kind_of_batch = ELECTED_OFFICE
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
elif kind_of_batch == IMPORT_BALLOT_ITEM:
existing_results = \
batch_manager.retrieve_batch_row_action_ballot_item(batch_header_id, one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_ballot_item']
one_batch_row.kind_of_batch = IMPORT_BALLOT_ITEM
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
elif kind_of_batch == IMPORT_VOTER:
existing_results = \
batch_manager.retrieve_batch_row_action_ballot_item(batch_header_id, one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_ballot_item']
one_batch_row.kind_of_batch = IMPORT_VOTER
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
elif kind_of_batch == MEASURE:
existing_results = batch_manager.retrieve_batch_row_action_measure(batch_header_id, one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_measure']
one_batch_row.kind_of_batch = MEASURE
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
elif kind_of_batch == ORGANIZATION_WORD:
existing_results = batch_manager.retrieve_batch_row_action_organization(batch_header_id,
one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_organization']
one_batch_row.kind_of_batch = ORGANIZATION_WORD
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
elif kind_of_batch == POLITICIAN:
existing_results = batch_manager.retrieve_batch_row_action_politician(batch_header_id, one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_politician']
one_batch_row.kind_of_batch = POLITICIAN
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
elif kind_of_batch == POSITION:
existing_results = batch_manager.retrieve_batch_row_action_position(batch_header_id, one_batch_row.id)
if existing_results['batch_row_action_found']:
one_batch_row.batch_row_action = existing_results['batch_row_action_position']
one_batch_row.kind_of_batch = POSITION
one_batch_row.batch_row_action_exists = True
else:
one_batch_row.batch_row_action_exists = False
modified_batch_row_list.append(one_batch_row)
election_query = Election.objects.order_by('-election_day_text')
election_list = list(election_query)
# TODO Retrieve and send a list of polling_locations to choose from into the template
polling_location_list = []
if kind_of_batch == IMPORT_BALLOT_ITEM:
polling_location_list = []
filtered_state_list = []
state_list = STATE_CODE_MAP
sorted_state_list = sorted(state_list.items())
for one_state in sorted_state_list:
if one_state[0].lower() in active_state_codes:
filtered_state_list.append(one_state)
messages.add_message(request, messages.INFO, 'Batch Row Count: {batch_row_count}'
''.format(batch_row_count=batch_row_count))
messages_on_stage = get_messages(request)
template_values = {
'messages_on_stage': messages_on_stage,
'batch_header_id': batch_header_id,
'batch_description': batch_description,
'batch_set_id': batch_set_id,
'batch_header_map': batch_header_map,
'batch_set_list': batch_set_list,
'batch_row_list': modified_batch_row_list,
'election_list': election_list,
'kind_of_batch': kind_of_batch,
'google_civic_election_id': google_civic_election_id,
'polling_location_we_vote_id': polling_location_we_vote_id,
'state_code': state_code,
'state_list': filtered_state_list,
'position_owner_organization_we_vote_id': position_owner_organization_we_vote_id,
}
return render(request, 'import_export_batches/batch_action_list.html', template_values)
@login_required
def batch_action_list_export_view(request):
"""
Export batch list as a csv file.
:param request: HTTP request object.
:return response: HttpResponse object with csv export data.
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_set_list = []
batch_header_id = convert_to_int(request.GET.get('batch_header_id', 0))
kind_of_batch = request.GET.get('kind_of_batch', '')
state_code = request.GET.get('state_code', '')
if not positive_value_exists(batch_header_id):
messages.add_message(request, messages.ERROR, 'Batch_header_id required.')
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch))
batch_set_id = 0
try:
batch_description = BatchDescription.objects.get(batch_header_id=batch_header_id)
except BatchDescription.DoesNotExist:
# This is fine
batch_description = BatchDescription()
# if batch_set_id exists, send data sets associated with this batch_set_id
if positive_value_exists(batch_set_id):
try:
batch_set_list = BatchSet.objects.get(id=batch_set_id)
if batch_set_list:
batch_set_list_found = True
except BatchSet.DoesNotExist:
# This is fine
batch_set_list = BatchSet()
batch_set_list_found = False
try:
batch_header_map = BatchHeaderMap.objects.get(batch_header_id=batch_header_id)
except BatchHeaderMap.DoesNotExist:
# This is fine
batch_header_map = BatchHeaderMap()
batch_list_found = False
try:
batch_row_count_query = BatchRow.objects.order_by('id')
batch_row_count_query = batch_row_count_query.filter(batch_header_id=batch_header_id)
if positive_value_exists(state_code):
batch_row_count_query = batch_row_count_query.filter(state_code__iexact=state_code)
batch_row_query = BatchRow.objects.order_by('id')
batch_row_query = batch_row_query.filter(batch_header_id=batch_header_id)
if positive_value_exists(state_code):
batch_row_query = batch_row_query.filter(state_code__iexact=state_code)
batch_row_list = list(batch_row_query)
if len(batch_row_list):
batch_list_found = True
except BatchDescription.DoesNotExist:
# This is fine
batch_row_list = []
batch_list_found = False
# get header/first row information
header_opts = BatchHeaderMap._meta
header_field_names = []
for field in header_opts.fields:
if field.name not in ['id', 'batch_header_id']:
header_field_names.append(field.name)
# get row information
row_opts = BatchRow._meta
row_field_names = []
for field in row_opts.fields:
if field.name not in ['id', 'batch_header_id']:
row_field_names.append(field.name)
header_list = [getattr(batch_header_map, field) for field in header_field_names]
header_list.insert(0, 'google_civic_election_id')
header_list.insert(0, 'state_code')
# - Filter out headers that are None.
header_list = list(filter(None, header_list))
# create response for csv file
response = export_csv(batch_row_list, header_list, row_field_names, batch_description)
return response
def export_csv(batch_row_list, header_list, row_field_names, batch_description=None, filename=None):
"""
Helper function that creates a HttpResponse with csv data
:param batch_row_list: list of objects to export as csv
:param header_list: list of column headers for csv data
:param row_field_names: list of the object fields to be exported
:param batch_description: optional description of the batch to export
:param filename: optional name of csv file
:return response: HttpResponse with text/csv data
"""
if batch_description and not filename:
export_filename = batch_description.batch_name
elif filename:
export_filename = filename
response = HttpResponse(content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename="{0}"'.format(export_filename)
csv_writer = csv.writer(response)
csv_writer.writerow(header_list)
# output header/first row to csv
for obj in batch_row_list:
csv_writer.writerow([getattr(obj, field) for field in row_field_names])
return response
@login_required
def batch_action_list_export_voters_view(request):
"""
View used to create a csv export file of voters registered for the newsletter
:param request:
:return: HttpResponse with csv information of voters
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# get parameters from request object
kind_of_batch = request.GET.get('kind_of_batch', IMPORT_VOTER)
batch_header_id = request.GET.get('batch_header_id', 0)
google_civic_election_id = request.GET.get('google_civic_election_id', '')
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
result = export_voter_list()
messages.add_message(request, messages.INFO, 'Batch Action Export Voters: '
'Batch kind: {kind_of_batch}'
''.format(kind_of_batch=kind_of_batch))
filename = 'voter_export.csv'
batch_manager = BatchManager()
batch_created_result = dict()
if result and result['voter_list']:
# Create batch of voters registered for newsletter
batch_created_result = batch_manager.create_batch_from_voter_object_list(result['voter_list'])
if batch_created_result and batch_created_result['batch_header_id']:
batch_header_id = batch_created_result['batch_header_id']
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&batch_header_id=" + str(batch_header_id)
)
@login_required
def batch_action_list_analyze_process_view(request):
"""
Create BatchRowActions for either all of the BatchRows for batch_header_id, or only one with batch_row_id
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_header_id = convert_to_int(request.GET.get('batch_header_id', 0))
batch_row_id = convert_to_int(request.GET.get('batch_row_id', 0))
kind_of_batch = request.GET.get('kind_of_batch', '')
state_code = request.GET.get('state_code', '')
if state_code == "None":
state_code = ""
if not positive_value_exists(batch_header_id):
messages.add_message(request, messages.ERROR, 'Batch_header_id required.')
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch))
# if create_actions_button in (MEASURE, ELECTED_OFFICE, CANDIDATE, ORGANIZATION_WORD,
# POSITION, POLITICIAN, IMPORT_BALLOT_ITEM)
# Run the analysis of either A) every row in this batch, or B) Just the batch_row_id specified within this batch
results = create_batch_row_actions(batch_header_id, batch_row_id, state_code)
kind_of_batch = results['kind_of_batch']
messages.add_message(request, messages.INFO, 'Batch Actions: '
'Batch kind: {kind_of_batch}, '
'Created:{created} '
''.format(kind_of_batch=kind_of_batch,
created=results['number_of_batch_actions_created']))
return HttpResponseRedirect(reverse('import_export_batches:batch_action_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&batch_header_id=" + str(batch_header_id) +
"&state_code=" + str(state_code)
)
@login_required
def batch_header_mapping_view(request):
"""
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_header_id = convert_to_int(request.GET.get('batch_header_id', 0))
kind_of_batch = request.GET.get('kind_of_batch', '')
if not positive_value_exists(batch_header_id):
messages.add_message(request, messages.ERROR, 'Batch_header_id required.')
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch))
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
batch_set_id = 0
try:
batch_description = BatchDescription.objects.get(batch_header_id=batch_header_id)
batch_set_id = batch_description.batch_set_id
kind_of_batch = batch_description.kind_of_batch
except BatchDescription.DoesNotExist:
# This is fine
batch_description = BatchDescription()
# if batch_set_id exists, send data sets associated with this batch_set_id
if positive_value_exists(batch_set_id):
try:
batch_set_list = BatchSet.objects.get(id=batch_set_id)
except BatchSet.DoesNotExist:
# This is fine
batch_set_list = BatchSet()
try:
batch_header = BatchHeader.objects.get(id=batch_header_id)
except BatchHeader.DoesNotExist:
# This is fine
batch_header = BatchHeader()
try:
batch_header_map = BatchHeaderMap.objects.get(batch_header_id=batch_header_id)
except BatchHeaderMap.DoesNotExist:
# This is fine
batch_header_map = BatchHeaderMap()
if kind_of_batch == CANDIDATE:
batch_import_keys_accepted = BATCH_IMPORT_KEYS_ACCEPTED_FOR_CANDIDATES
elif kind_of_batch == CONTEST_OFFICE:
batch_import_keys_accepted = BATCH_IMPORT_KEYS_ACCEPTED_FOR_CONTEST_OFFICES
elif kind_of_batch == ELECTED_OFFICE:
batch_import_keys_accepted = BATCH_IMPORT_KEYS_ACCEPTED_FOR_ELECTED_OFFICES
elif kind_of_batch == MEASURE:
batch_import_keys_accepted = BATCH_IMPORT_KEYS_ACCEPTED_FOR_MEASURES
elif kind_of_batch == ORGANIZATION_WORD:
batch_import_keys_accepted = BATCH_IMPORT_KEYS_ACCEPTED_FOR_ORGANIZATIONS
elif kind_of_batch == POLITICIAN:
batch_import_keys_accepted = BATCH_IMPORT_KEYS_ACCEPTED_FOR_POLITICIANS
elif kind_of_batch == POSITION:
batch_import_keys_accepted = BATCH_IMPORT_KEYS_ACCEPTED_FOR_POSITIONS
elif kind_of_batch == IMPORT_BALLOT_ITEM:
batch_import_keys_accepted = BATCH_IMPORT_KEYS_ACCEPTED_FOR_BALLOT_ITEMS
else:
batch_import_keys_accepted = {}
sorted_batch_import_keys_accepted = sorted(batch_import_keys_accepted.items())
try:
batch_row_list = BatchRow.objects.all()
batch_row_list = batch_row_list.filter(batch_header_id=batch_header_id)[:3] # Limit to 3 rows
except BatchDescription.DoesNotExist:
# This is fine
batch_row_list = []
election_list = Election.objects.order_by('-election_day_text')
messages_on_stage = get_messages(request)
if batch_set_id:
template_values = {
'messages_on_stage': messages_on_stage,
'batch_header_id': batch_header_id,
'batch_description': batch_description,
'batch_set_id': batch_set_id,
'batch_header': batch_header,
'batch_header_map': batch_header_map,
'batch_import_keys_accepted': sorted_batch_import_keys_accepted,
'batch_row_list': batch_row_list,
'batch_set_list': batch_set_list,
'election_list': election_list,
'kind_of_batch': kind_of_batch,
'google_civic_election_id': google_civic_election_id,
}
else:
template_values = {
'messages_on_stage': messages_on_stage,
'batch_header_id': batch_header_id,
'batch_description': batch_description,
'batch_set_id': batch_set_id,
'batch_header': batch_header,
'batch_header_map': batch_header_map,
'batch_import_keys_accepted': sorted_batch_import_keys_accepted,
'batch_row_list': batch_row_list,
'election_list': election_list,
'kind_of_batch': kind_of_batch,
'google_civic_election_id': google_civic_election_id,
}
return render(request, 'import_export_batches/batch_header_mapping.html', template_values)
@login_required
def batch_header_mapping_process_view(request):
"""
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_header_id = convert_to_int(request.GET.get('batch_header_id', 0))
save_header_mapping_button = request.GET.get('save_header_mapping_button', '')
kind_of_batch = ""
if not positive_value_exists(batch_header_id):
messages.add_message(request, messages.ERROR, 'Batch_header_id required.')
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch))
batch_set_id = 0
try:
batch_description = BatchDescription.objects.get(batch_header_id=batch_header_id)
batch_set_id = batch_description.batch_set_id
kind_of_batch = batch_description.kind_of_batch
except BatchDescription.DoesNotExist:
# This is fine
batch_description = BatchDescription()
# Put all incoming header_mapping values into a dict
incoming_header_map_values = {
'batch_header_map_000': request.GET.get('batch_header_map_000', ''),
'batch_header_map_001': request.GET.get('batch_header_map_001', ''),
'batch_header_map_002': request.GET.get('batch_header_map_002', ''),
'batch_header_map_003': request.GET.get('batch_header_map_003', ''),
'batch_header_map_004': request.GET.get('batch_header_map_004', ''),
'batch_header_map_005': request.GET.get('batch_header_map_005', ''),
'batch_header_map_006': request.GET.get('batch_header_map_006', ''),
'batch_header_map_007': request.GET.get('batch_header_map_007', ''),
'batch_header_map_008': request.GET.get('batch_header_map_008', ''),
'batch_header_map_009': request.GET.get('batch_header_map_009', ''),
'batch_header_map_010': request.GET.get('batch_header_map_010', ''),
'batch_header_map_011': request.GET.get('batch_header_map_011', ''),
'batch_header_map_012': request.GET.get('batch_header_map_012', ''),
'batch_header_map_013': request.GET.get('batch_header_map_013', ''),
'batch_header_map_014': request.GET.get('batch_header_map_014', ''),
'batch_header_map_015': request.GET.get('batch_header_map_015', ''),
'batch_header_map_016': request.GET.get('batch_header_map_016', ''),
'batch_header_map_017': request.GET.get('batch_header_map_017', ''),
'batch_header_map_018': request.GET.get('batch_header_map_018', ''),
'batch_header_map_019': request.GET.get('batch_header_map_019', ''),
'batch_header_map_020': request.GET.get('batch_header_map_020', ''),
}
batch_header_mapping_results = create_or_update_batch_header_mapping(
batch_header_id, kind_of_batch, incoming_header_map_values)
try:
batch_header = BatchHeader.objects.get(id=batch_header_id)
batch_header_found = True
except BatchHeader.DoesNotExist:
# This is fine
batch_header = BatchHeader()
batch_header_found = False
suggestions_created = 0
if batch_header_found:
batch_header_translation_results = create_batch_header_translation_suggestions(
batch_header, kind_of_batch, incoming_header_map_values)
suggestions_created = batch_header_translation_results['suggestions_created']
messages.add_message(request, messages.INFO, 'Batch Header Mapping Updated: '
'Batch kind: {kind_of_batch}, '
'suggestions_created: {suggestions_created}, '
''.format(kind_of_batch=kind_of_batch,
suggestions_created=suggestions_created))
return HttpResponseRedirect(reverse('import_export_batches:batch_action_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&batch_header_id=" + str(batch_header_id))
@login_required
def batch_action_list_assign_election_to_rows_process_view(request):
"""
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_row_list_found = False
batch_row_list = []
batch_header_id = convert_to_int(request.GET.get('batch_header_id', 0))
batch_row_id = convert_to_int(request.GET.get('batch_row_id', 0))
kind_of_batch = request.GET.get('kind_of_batch', '')
kind_of_action = request.GET.get('kind_of_action')
state_code = request.GET.get('state_code', '')
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
# do for entire batch_rows
try:
batch_header_map = BatchHeaderMap.objects.get(batch_header_id=batch_header_id)
batch_header_map_found = True
except BatchHeaderMap.DoesNotExist:
# This is fine
batch_header_map = BatchHeaderMap()
batch_header_map_found = False
if batch_header_map_found:
try:
batch_row_query = BatchRow.objects.all()
batch_row_query = batch_row_query.filter(batch_header_id=batch_header_id)
if positive_value_exists(batch_row_id):
batch_row_query = batch_row_query.filter(id=batch_row_id)
if positive_value_exists(state_code):
batch_row_query = batch_row_query.filter(state_code__iexact=state_code)
batch_row_list = list(batch_row_query)
if len(batch_row_list):
batch_row_list_found = True
except BatchDescription.DoesNotExist:
# This is fine
batch_row_list_found = False
pass
if batch_header_map_found and batch_row_list_found:
for one_batch_row in batch_row_list:
try:
one_batch_row.google_civic_election_id = google_civic_election_id
one_batch_row.save()
except Exception as e:
pass
# messages.add_message(request, messages.INFO,
# 'Kind of Batch: {kind_of_batch}, ' 'Number Created: {created} '
# ''.format(kind_of_batch=kind_of_batch,
# created=results['number_of_table_rows_created']))
return HttpResponseRedirect(reverse('import_export_batches:batch_action_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&batch_header_id=" + str(batch_header_id) +
"&state_code=" + str(state_code) +
"&google_civic_election_id=" + str(google_civic_election_id)
)
@login_required
def batch_action_list_create_or_update_process_view(request):
"""
Use batch_row_action entries and create live data
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_row_list_found = False
batch_header_id = convert_to_int(request.GET.get('batch_header_id', 0))
batch_row_id = convert_to_int(request.GET.get('batch_row_id', 0))
kind_of_batch = request.GET.get('kind_of_batch', '')
kind_of_action = request.GET.get('kind_of_action')
state_code = request.GET.get('state_code', '')
# do for entire batch_rows
try:
batch_header_map = BatchHeaderMap.objects.get(batch_header_id=batch_header_id)
batch_header_map_found = True
except BatchHeaderMap.DoesNotExist:
# This is fine
batch_header_map = BatchHeaderMap()
batch_header_map_found = False
if batch_header_map_found:
try:
batch_row_query = BatchRow.objects.all()
batch_row_query = batch_row_query.filter(batch_header_id=batch_header_id)
if positive_value_exists(batch_row_id):
batch_row_query = batch_row_query.filter(id=batch_row_id)
if positive_value_exists(state_code):
batch_row_query = batch_row_query.filter(state_code__iexact=state_code)
batch_row_list = list(batch_row_query)
if len(batch_row_list):
batch_row_list_found = True
except BatchDescription.DoesNotExist:
# This is fine
batch_row_list_found = False
pass
if batch_header_map_found and batch_row_list_found:
results = import_data_from_batch_row_actions(
kind_of_batch, kind_of_action, batch_header_id, batch_row_id, state_code)
if kind_of_action == IMPORT_CREATE:
if results['success']:
messages.add_message(request, messages.INFO,
'Kind of Batch: {kind_of_batch}, ' 'Number Created: {created} '
''.format(kind_of_batch=kind_of_batch,
created=results['number_of_table_rows_created']))
else:
messages.add_message(request, messages.ERROR, 'Batch kind: {kind_of_batch} create failed: {status}'
''.format(kind_of_batch=kind_of_batch,
status=results['status']))
elif kind_of_action == IMPORT_ADD_TO_EXISTING:
if results['success']:
messages.add_message(request, messages.INFO,
'Kind of Batch: {kind_of_batch}, ' 'Number Updated: {updated} '
''.format(kind_of_batch=kind_of_batch,
updated=results['number_of_table_rows_updated']))
else:
messages.add_message(request, messages.ERROR, 'Batch kind: {kind_of_batch} update failed--'
'UPDATE may not be supported yet.'
''.format(kind_of_batch=kind_of_batch))
else:
messages.add_message(request, messages.ERROR, 'Batch kind: {kind_of_batch} import status: {status}'
''.format(kind_of_batch=kind_of_batch,
status=results['status']))
return HttpResponseRedirect(reverse('import_export_batches:batch_list', args=()))
return HttpResponseRedirect(reverse('import_export_batches:batch_action_list', args=()) +
"?kind_of_batch=" + str(kind_of_batch) +
"&batch_header_id=" + str(batch_header_id) +
"&state_code=" + str(state_code)
)
@login_required
def batch_set_list_view(request):
"""
Display a list of import batch set
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# kind_of_batch = request.GET.get('kind_of_batch', '')
batch_file = request.GET.get('batch_file', '')
batch_uri = request.GET.get('batch_uri', '')
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
messages_on_stage = get_messages(request)
batch_set_list_found = False
try:
batch_set_list = BatchSet.objects.order_by('-import_date')
# batch_set_list = batch_set_list.exclude(batch_set_id__isnull=True)
if positive_value_exists(google_civic_election_id):
batch_set_list = batch_set_list.filter(google_civic_election_id=google_civic_election_id)
if len(batch_set_list):
batch_set_list_found = True
except BatchSet.DoesNotExist:
# This is fine
batch_set_list = BatchSet()
batch_set_list_found = False
pass
election_list = Election.objects.order_by('-election_day_text')
if batch_set_list_found:
template_values = {
'messages_on_stage': messages_on_stage,
'batch_set_list': batch_set_list,
'election_list': election_list,
'batch_file': batch_file,
'batch_uri': batch_uri,
'google_civic_election_id': google_civic_election_id,
}
else:
template_values = {
'messages_on_stage': messages_on_stage,
'election_list': election_list,
'batch_file': batch_file,
'batch_uri': batch_uri,
'google_civic_election_id': google_civic_election_id,
}
return render(request, 'import_export_batches/batch_set_list.html', template_values)
@login_required
def batch_set_list_process_view(request):
"""
Load in a new batch set to start the importing process
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_uri = request.POST.get('batch_uri', '')
google_civic_election_id = request.POST.get('google_civic_election_id', 0)
organization_we_vote_id = request.POST.get('organization_we_vote_id', '')
# Was form submitted, or was election just changed?
import_batch_button = request.POST.get('import_batch_button', '')
batch_uri_encoded = urlquote(batch_uri) if positive_value_exists(batch_uri) else ""
batch_file = None
# Store contents of spreadsheet?
# if not positive_value_exists(google_civic_election_id):
# messages.add_message(request, messages.ERROR, 'This batch set requires you to choose an election.')
# return HttpResponseRedirect(reverse('import_export_batches:batch_set_list', args=()) +
# "?batch_uri=" + batch_uri_encoded)
election_manager = ElectionManager()
election_name = ""
results = election_manager.retrieve_election(google_civic_election_id)
if results['election_found']:
election = results['election']
election_name = election.election_name
if positive_value_exists(import_batch_button): # If the button was pressed...
batch_manager = BatchManager()
try:
if request.method == 'POST' and request.FILES['batch_file']:
batch_file = request.FILES['batch_file']
except KeyError:
pass
if batch_file is not None:
results = batch_manager.create_batch_set_vip_xml(
batch_file, batch_uri, google_civic_election_id, organization_we_vote_id)
if results['batch_saved']:
messages.add_message(request, messages.INFO, 'Import batch for {election_name} election saved.'
''.format(election_name=election_name))
else:
messages.add_message(request, messages.ERROR, results['status'])
elif positive_value_exists(batch_uri):
# check file type
filetype = batch_manager.find_file_type(batch_uri)
if "xml" in filetype:
# file is XML
# Retrieve the VIP data from XML
results = batch_manager.create_batch_set_vip_xml(
batch_file, batch_uri, google_civic_election_id, organization_we_vote_id)
else:
pass
# results = batch_manager.create_batch(batch_uri, google_civic_election_id, organization_we_vote_id)
if results['batch_saved']:
messages.add_message(request, messages.INFO, 'Import batch for {election_name} election saved.'
''.format(election_name=election_name))
else:
messages.add_message(request, messages.ERROR, results['status'])
return HttpResponseRedirect(reverse('import_export_batches:batch_set_list', args=()) +
"?google_civic_election_id=" + str(google_civic_election_id) +
"&batch_uri=" + batch_uri_encoded)
@login_required
def batch_set_batch_list_view(request):
"""
Display row-by-row details of batch_set actions being reviewed, leading up to processing an entire batch_set.
:param request:
:return:
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
batch_set_id = convert_to_int(request.GET.get('batch_set_id', 0))
if not positive_value_exists(batch_set_id):
messages.add_message(request, messages.ERROR, 'Batch_set_id required.')
return HttpResponseRedirect(reverse('import_export_batches:batch_set_list', args=()))
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
analyze_all_button = request.GET.get('analyze_all_button', 0)
create_all_button = request.GET.get('create_all_button', 0)
show_all_batches = request.GET.get('show_all_batches', False)
state_code = request.GET.get('state_code', "")
update_all_button = request.GET.get('update_all_button', 0)
batch_list_modified = []
batch_manager = BatchManager()
batch_set_count = 0
batch_set_kind_of_batch = ""
try:
if positive_value_exists(analyze_all_button):
batch_actions_analyzed = 0
batch_actions_not_analyzed = 0
batch_header_id_created_list = []
batch_description_query = BatchDescription.objects.filter(batch_set_id=batch_set_id)
batch_description_query = batch_description_query.filter(batch_description_analyzed=False)
batch_list = list(batch_description_query)
for one_batch_description in batch_list:
results = create_batch_row_actions(one_batch_description.batch_header_id)
if results['batch_actions_created']:
batch_actions_analyzed += 1
try:
# If BatchRowAction's were created for BatchDescription, this batch_description was analyzed
one_batch_description.batch_description_analyzed = True
one_batch_description.save()
batch_header_id_created_list.append(one_batch_description.batch_header_id)
except Exception as e:
pass
else:
batch_actions_not_analyzed += 1
batch_description_query = BatchDescription.objects.filter(batch_set_id=batch_set_id)
if positive_value_exists(len(batch_header_id_created_list)):
batch_description_query = batch_description_query.exclude(
batch_header_id__in=batch_header_id_created_list)
batch_list = list(batch_description_query)
for one_batch_description in batch_list:
results = create_batch_row_actions(one_batch_description.batch_header_id)
if results['batch_actions_created']:
batch_actions_analyzed += 1
try:
# If BatchRowAction's were created for BatchDescription, this batch_description was analyzed
one_batch_description.batch_description_analyzed = True
one_batch_description.save()
except Exception as e:
pass
else:
batch_actions_not_analyzed += 1
if positive_value_exists(batch_actions_analyzed):
messages.add_message(request, messages.INFO, "Analyze All, BatchRows Analyzed: "
"" + str(batch_actions_analyzed))
if positive_value_exists(batch_actions_not_analyzed):
messages.add_message(request, messages.ERROR, "Analyze All, BatchRows NOT Analyzed: "
"" + str(batch_actions_not_analyzed))
return HttpResponseRedirect(reverse('import_export_batches:batch_set_batch_list', args=()) +
"?google_civic_election_id=" + str(google_civic_election_id) +
"&batch_set_id=" + str(batch_set_id) +
"&state_code=" + state_code)
if positive_value_exists(update_all_button):
batch_description_query = BatchDescription.objects.filter(batch_set_id=batch_set_id)
batch_description_query = batch_description_query.filter(batch_description_analyzed=True)
batch_list = list(batch_description_query)
batch_actions_updated = 0
batch_actions_not_updated = 0
for one_batch_description in batch_list:
results = import_data_from_batch_row_actions(
one_batch_description.kind_of_batch, IMPORT_ADD_TO_EXISTING, one_batch_description.batch_header_id)
if results['number_of_table_rows_updated']:
batch_actions_updated += 1
else:
batch_actions_not_updated += 1
if positive_value_exists(batch_actions_updated):
messages.add_message(request, messages.INFO, "Update in All Batches, Updates: "
"" + str(batch_actions_updated))
if positive_value_exists(batch_actions_not_updated):
messages.add_message(request, messages.ERROR, "Update in All Batches, Failed Updates: "
"" + str(batch_actions_not_updated))
return HttpResponseRedirect(reverse('import_export_batches:batch_set_batch_list', args=()) +
"?google_civic_election_id=" + str(google_civic_election_id) +
"&batch_set_id=" + str(batch_set_id) +
"&state_code=" + state_code)
if positive_value_exists(create_all_button):
batch_description_query = BatchDescription.objects.filter(batch_set_id=batch_set_id)
batch_description_query = batch_description_query.filter(batch_description_analyzed=True)
batch_list = list(batch_description_query)
batch_actions_created = 0
batch_actions_not_created = 0
for one_batch_description in batch_list:
results = import_data_from_batch_row_actions(
one_batch_description.kind_of_batch, IMPORT_CREATE, one_batch_description.batch_header_id)
if results['number_of_table_rows_created']:
batch_actions_created += 1
else:
batch_actions_not_created += 1
if positive_value_exists(batch_actions_created):
messages.add_message(request, messages.INFO, "Create in All Batches, Creates: "
"" + str(batch_actions_created))
if positive_value_exists(batch_actions_not_created):
messages.add_message(request, messages.ERROR, "Create in All Batches, FAILED Creates: "
"" + str(batch_actions_not_created))
return HttpResponseRedirect(reverse('import_export_batches:batch_set_batch_list', args=()) +
"?google_civic_election_id=" + str(google_civic_election_id) +
"&batch_set_id=" + str(batch_set_id) +
"&state_code=" + state_code)
batch_description_query = BatchDescription.objects.filter(batch_set_id=batch_set_id)
batch_set_count = batch_description_query.count()
batch_list = list(batch_description_query)
if not positive_value_exists(show_all_batches):
batch_list = batch_list[:10]
# Loop through all batches and add count data
for one_batch_description in batch_list:
batch_header_id = one_batch_description.batch_header_id
one_batch_description.number_of_batch_rows_imported = batch_manager.fetch_batch_row_count(batch_header_id)
one_batch_description.number_of_batch_rows_analyzed = \
batch_manager.fetch_batch_row_action_count(batch_header_id, one_batch_description.kind_of_batch)
one_batch_description.number_of_batch_actions_to_create = \
batch_manager.fetch_batch_row_action_count(batch_header_id, one_batch_description.kind_of_batch,
IMPORT_CREATE)
one_batch_description.number_of_table_rows_to_update = \
batch_manager.fetch_batch_row_action_count(batch_header_id, one_batch_description.kind_of_batch,
IMPORT_ADD_TO_EXISTING)
one_batch_description.number_of_batch_actions_cannot_act = \
one_batch_description.number_of_batch_rows_analyzed - \
one_batch_description.number_of_batch_actions_to_create - \
one_batch_description.number_of_table_rows_to_update
batch_set_kind_of_batch = one_batch_description.kind_of_batch
batch_list_modified.append(one_batch_description)
except BatchDescription.DoesNotExist:
# This is fine
pass
election_list = Election.objects.order_by('-election_day_text')
status_message = '{batch_set_count} batches in this batch set. '.format(batch_set_count=batch_set_count)
batch_row_items_to_create_for_this_set = batch_manager.fetch_batch_row_action_count_in_batch_set(
batch_set_id, batch_set_kind_of_batch, IMPORT_CREATE)
if positive_value_exists(batch_row_items_to_create_for_this_set):
status_message += 'BatchRowActions to create: {batch_row_items_to_create_for_this_set} '.format(
batch_row_items_to_create_for_this_set=batch_row_items_to_create_for_this_set)
batch_row_items_to_update_for_this_set = batch_manager.fetch_batch_row_action_count_in_batch_set(
batch_set_id, batch_set_kind_of_batch, IMPORT_ADD_TO_EXISTING)
if positive_value_exists(batch_row_items_to_update_for_this_set):
status_message += 'BatchRowActions to update: {batch_row_items_to_update_for_this_set} '.format(
batch_row_items_to_update_for_this_set=batch_row_items_to_update_for_this_set)
messages.add_message(request, messages.INFO, status_message)
messages_on_stage = get_messages(request)
template_values = {
'messages_on_stage': messages_on_stage,
'batch_set_id': batch_set_id,
'batch_list': batch_list_modified,
'election_list': election_list,
'google_civic_election_id': google_civic_election_id,
'show_all_batches': show_all_batches,
}
return render(request, 'import_export_batches/batch_set_batch_list.html', template_values)
| 50.246489
| 120
| 0.652583
|
6114223291b33e16fb09186a92983ad362b82254
| 13,862
|
py
|
Python
|
bin/single_node_perf_run.py
|
garyli1019/impala
|
ea0e1def6160d596082b01365fcbbb6e24afb21d
|
[
"Apache-2.0"
] | null | null | null |
bin/single_node_perf_run.py
|
garyli1019/impala
|
ea0e1def6160d596082b01365fcbbb6e24afb21d
|
[
"Apache-2.0"
] | 1
|
2022-03-29T21:58:11.000Z
|
2022-03-29T21:58:11.000Z
|
bin/single_node_perf_run.py
|
garyli1019/impala
|
ea0e1def6160d596082b01365fcbbb6e24afb21d
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env impala-python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Usage:
# single_node_perf_run.py [options] git_hash_A [git_hash_B]
#
# When one hash is given, measures the performance on the specified workloads.
# When two hashes are given, compares their performance. Output is in
# $IMPALA_HOME/perf_results/latest. In the performance_result.txt file,
# git_hash_A is referred to as the "Base" result. For example, if you run with
# git_hash_A = aBad1dea... and git_hash_B = 8675309... the
# performance_result.txt will say at the top:
#
# Run Description: "aBad1dea... vs 8675309..."
#
# The different queries will have their run time statistics in columns
# "Avg(s)", "StdDev(%)", "BaseAvg(s)", "Base StdDev(%)". The first two refer
# to git_hash_B, the second two refer to git_hash_A. The column "Delta(Avg)"
# is negative if git_hash_B is faster and is positive if git_hash_A is faster.
#
# WARNING: This script will run git checkout. You should not touch the tree
# while the script is running. You should start the script from a clean git
# tree.
#
# WARNING: When --load is used, this script calls load_data.py which can
# overwrite your TPC-H and TPC-DS data.
#
# Options:
# -h, --help show this help message and exit
# --workloads=WORKLOADS
# comma-separated list of workloads. Choices: tpch,
# targeted-perf, tpcds. Default: targeted-perf
# --scale=SCALE scale factor for the workloads
# --iterations=ITERATIONS
# number of times to run each query
# --table_formats=TABLE_FORMATS
# comma-separated list of table formats. Default:
# parquet/none
# --num_impalads=NUM_IMPALADS
# number of impalads. Default: 1
# --query_names=QUERY_NAMES
# comma-separated list of regular expressions. A query
# is executed if it matches any regular expression in
# this list
# --load load databases for the chosen workloads
# --start_minicluster start a new Hadoop minicluster
# --ninja use ninja, rather than Make, as the build tool
from optparse import OptionParser
from tempfile import mkdtemp
import json
import os
import pipes
import sh
import shutil
import subprocess
import sys
import textwrap
from tests.common.test_dimensions import TableFormatInfo
IMPALA_HOME = os.environ["IMPALA_HOME"]
def configured_call(cmd):
"""Call a command in a shell with config-impala.sh."""
if type(cmd) is list:
cmd = " ".join([pipes.quote(arg) for arg in cmd])
cmd = "source {0}/bin/impala-config.sh && {1}".format(IMPALA_HOME, cmd)
return subprocess.check_call(["bash", "-c", cmd])
def load_data(db_to_load, table_formats, scale):
"""Loads a database with a particular scale factor."""
configured_call(["{0}/bin/load-data.py".format(IMPALA_HOME),
"--workloads", db_to_load, "--scale_factor", str(scale),
"--table_formats", "text/none," + table_formats])
for table_format in table_formats.split(","):
suffix = TableFormatInfo.create_from_string(None, table_format).db_suffix()
db_name = db_to_load + scale + suffix
configured_call(["{0}/tests/util/compute_table_stats.py".format(IMPALA_HOME),
"--stop_on_error", "--db_names", db_name])
def get_git_hash_for_name(name):
return sh.git("rev-parse", name).strip()
def build(git_hash, options):
"""Builds Impala in release mode; doesn't build tests."""
sh.git.checkout(git_hash)
buildall = ["{0}/buildall.sh".format(IMPALA_HOME), "-notests", "-release", "-noclean"]
if options.ninja:
buildall += ["-ninja"]
configured_call(buildall)
def start_minicluster():
configured_call(["{0}/bin/create-test-configuration.sh".format(IMPALA_HOME)])
configured_call(["{0}/testdata/bin/run-all.sh".format(IMPALA_HOME)])
def start_impala(num_impalads, options):
configured_call(["{0}/bin/start-impala-cluster.py".format(IMPALA_HOME), "-s",
str(num_impalads), "-c", str(num_impalads)] +
["--impalad_args={0}".format(arg) for arg in options.impalad_args])
def run_workload(base_dir, workloads, options):
"""Runs workload with the given options.
Returns the git hash of the current revision to identify the output file.
"""
git_hash = get_git_hash_for_name("HEAD")
run_workload = ["{0}/bin/run-workload.py".format(IMPALA_HOME)]
impalads = ",".join(["localhost:{0}".format(21000 + i)
for i in range(0, int(options.num_impalads))])
run_workload += ["--workloads={0}".format(workloads),
"--impalads={0}".format(impalads),
"--results_json_file={0}/{1}.json".format(base_dir, git_hash),
"--query_iterations={0}".format(options.iterations),
"--table_formats={0}".format(options.table_formats),
"--plan_first"]
if options.query_names:
run_workload += ["--query_names={0}".format(options.query_names)]
configured_call(run_workload)
def report_benchmark_results(file_a, file_b, description):
"""Wrapper around report_benchmark_result.py."""
result = "{0}/perf_results/latest/performance_result.txt".format(IMPALA_HOME)
with open(result, "w") as f:
subprocess.check_call(
["{0}/tests/benchmark/report_benchmark_results.py".format(IMPALA_HOME),
"--reference_result_file={0}".format(file_a),
"--input_result_file={0}".format(file_b),
'--report_description="{0}"'.format(description)],
stdout=f)
sh.cat(result, _out=sys.stdout)
def compare(base_dir, hash_a, hash_b):
"""Take the results of two performance runs and compare them."""
file_a = os.path.join(base_dir, hash_a + ".json")
file_b = os.path.join(base_dir, hash_b + ".json")
description = "{0} vs {1}".format(hash_a, hash_b)
report_benchmark_results(file_a, file_b, description)
# From the two json files extract the profiles and diff them
generate_profile_file(file_a, hash_a, base_dir)
generate_profile_file(file_b, hash_b, base_dir)
sh.diff("-u",
os.path.join(base_dir, hash_a + "_profile.txt"),
os.path.join(base_dir, hash_b + "_profile.txt"),
_out=os.path.join(IMPALA_HOME, "performance_result_profile_diff.txt"),
_ok_code=[0, 1])
def generate_profile_file(name, hash, base_dir):
"""Extracts runtime profiles from the JSON file 'name'.
Writes the runtime profiles back in a simple text file in the same directory.
"""
with open(name) as fid:
data = json.load(fid)
with open(os.path.join(base_dir, hash + "_profile.txt"), "w+") as out:
# For each query
for key in data:
for iteration in data[key]:
out.write(iteration["runtime_profile"])
out.write("\n\n")
def backup_workloads():
"""Copy the workload folder to a temporary directory and returns its name.
Used to keep workloads from being clobbered by git checkout.
"""
temp_dir = mkdtemp()
sh.cp(os.path.join(IMPALA_HOME, "testdata", "workloads"),
temp_dir, R=True, _out=sys.stdout, _err=sys.stderr)
print "Backed up workloads to {0}".format(temp_dir)
return temp_dir
def restore_workloads(source):
"""Restores the workload directory from source into the Impala tree."""
sh.cp(os.path.join(source, "workloads"), os.path.join(IMPALA_HOME, "testdata"),
R=True, _out=sys.stdout, _err=sys.stderr)
def perf_ab_test(options, args):
"""Does the main work: build, run tests, compare."""
hash_a = get_git_hash_for_name(args[0])
# Create the base directory to store the results in
results_path = os.path.join(IMPALA_HOME, "perf_results")
if not os.access(results_path, os.W_OK):
os.makedirs(results_path)
temp_dir = mkdtemp(dir=results_path, prefix="perf_run_")
latest = os.path.join(results_path, "latest")
if os.path.islink(latest):
os.remove(latest)
os.symlink(os.path.basename(temp_dir), latest)
workload_dir = backup_workloads()
build(hash_a, options)
restore_workloads(workload_dir)
if options.start_minicluster:
start_minicluster()
start_impala(options.num_impalads, options)
workloads = set(options.workloads.split(","))
if options.load:
WORKLOAD_TO_DATASET = {"tpch": "tpch", "tpcds": "tpcds", "targeted-perf": "tpch",
"tpcds-unmodified": "tpcds-unmodified"}
datasets = set([WORKLOAD_TO_DATASET[workload] for workload in workloads])
for dataset in datasets:
load_data(dataset, options.table_formats, options.scale)
workloads = ",".join(["{0}:{1}".format(workload, options.scale)
for workload in workloads])
run_workload(temp_dir, workloads, options)
if len(args) > 1 and args[1]:
hash_b = get_git_hash_for_name(args[1])
# discard any changes created by the previous restore_workloads()
shutil.rmtree("testdata/workloads")
sh.git.checkout("--", "testdata/workloads")
build(hash_b, options)
restore_workloads(workload_dir)
start_impala(options.num_impalads, options)
run_workload(temp_dir, workloads, options)
compare(temp_dir, hash_a, hash_b)
def parse_options():
"""Parse and return the options and positional arguments."""
parser = OptionParser()
parser.add_option("--workloads", default="targeted-perf",
help="comma-separated list of workloads. Choices: tpch, "
"targeted-perf, tpcds. Default: targeted-perf")
parser.add_option("--scale", help="scale factor for the workloads")
parser.add_option("--iterations", default=30, help="number of times to run each query")
parser.add_option("--table_formats", default="parquet/none", help="comma-separated "
"list of table formats. Default: parquet/none")
parser.add_option("--num_impalads", default=1, help="number of impalads. Default: 1")
# Less commonly-used options:
parser.add_option("--query_names",
help="comma-separated list of regular expressions. A query is "
"executed if it matches any regular expression in this list")
parser.add_option("--load", action="store_true",
help="load databases for the chosen workloads")
parser.add_option("--start_minicluster", action="store_true",
help="start a new Hadoop minicluster")
parser.add_option("--ninja", action="store_true",
help = "use ninja, rather than Make, as the build tool")
parser.add_option("--impalad_args", dest="impalad_args", action="append", type="string",
default=[],
help="Additional arguments to pass to each Impalad during startup")
parser.set_usage(textwrap.dedent("""
single_node_perf_run.py [options] git_hash_A [git_hash_B]
When one hash is given, measures the performance on the specified workloads.
When two hashes are given, compares their performance. Output is in
$IMPALA_HOME/perf_results/latest. In the performance_result.txt file,
git_hash_A is referred to as the "Base" result. For example, if you run with
git_hash_A = aBad1dea... and git_hash_B = 8675309... the
performance_result.txt will say at the top:
Run Description: "aBad1dea... vs 8675309..."
The different queries will have their run time statistics in columns
"Avg(s)", "StdDev(%)", "BaseAvg(s)", "Base StdDev(%)". The first two refer
to git_hash_B, the second two refer to git_hash_A. The column "Delta(Avg)"
is negative if git_hash_B is faster and is positive if git_hash_A is faster.
WARNING: This script will run git checkout. You should not touch the tree
while the script is running. You should start the script from a clean git
tree.
WARNING: When --load is used, this script calls load_data.py which can
overwrite your TPC-H and TPC-DS data."""))
options, args = parser.parse_args()
if not 1 <= len(args) <= 2:
parser.print_usage(sys.stderr)
raise Exception("Invalid arguments: either 1 or 2 Git hashes allowed")
return options, args
def main():
"""A thin wrapper around perf_ab_test that restores git state after."""
options, args = parse_options()
os.chdir(IMPALA_HOME)
if sh.git("status", "--porcelain", "--untracked-files=no", _out=None).strip():
sh.git("status", "--porcelain", "--untracked-files=no", _out=sys.stdout)
raise Exception("Working copy is dirty. Consider 'git stash' and try again.")
# Save the current hash to be able to return to this place in the tree when done
current_hash = sh.git("rev-parse", "--abbrev-ref", "HEAD").strip()
if current_hash == "HEAD":
current_hash = get_git_hash_for_name("HEAD")
try:
workloads = backup_workloads()
perf_ab_test(options, args)
finally:
# discard any changes created by the previous restore_workloads()
shutil.rmtree("testdata/workloads")
sh.git.checkout("--", "testdata/workloads")
sh.git.checkout(current_hash)
restore_workloads(workloads)
if __name__ == "__main__":
main()
| 39.719198
| 90
| 0.683523
|
efbdd60f7e7df707454e54362451b8083eb75b85
| 1,855
|
py
|
Python
|
database_connections/SAP_HANA/hana_ml_connection.py
|
ant358/ML_tools
|
9e0d562e12d7253d68dd8081967de9e300b84eda
|
[
"MIT"
] | null | null | null |
database_connections/SAP_HANA/hana_ml_connection.py
|
ant358/ML_tools
|
9e0d562e12d7253d68dd8081967de9e300b84eda
|
[
"MIT"
] | null | null | null |
database_connections/SAP_HANA/hana_ml_connection.py
|
ant358/ML_tools
|
9e0d562e12d7253d68dd8081967de9e300b84eda
|
[
"MIT"
] | null | null | null |
# Connect to the SAP Datawarehouse and upload some tables from our local db
import pandas as pd
import hana_ml.dataframe as dataframe
import sqlalchemy as sq
# Import the Connection details
import Parameters as p
# connect to local data
engine = sq.create_engine('sqlite:///../data/local.db')
# connect to HANA
conn = dataframe.ConnectionContext(
address=p.address,
port=p.port,
user=p.user,
password=p.password,
encrypt=p.encrypt,
sslValidateCertificate=p.sslValidateCertificate,
databaseName=p.databaseName
)
if conn:
print('User connected to HANA successfully')
# check the connection
assert conn.get_current_schema() == 'SPACE#USER', (
"Not connected to the correct schema")
def load_table(schema_name='SPACE#USER',
table_name=None,
local_name=None):
"""Upload a table from local db to SAP HANA
does not return anything a connection to SAP DWC (conn)
and the local db (engine) should be available
Args:
schema_name (str): the schema name to upload to
table_name (str): the table name to upload
local_name (str): the local table name to upload from
Returns:
None
"""
assert table_name is not None, "Input the SAP HANA table name"
assert local_name is not None, "Input the name of the local db table"
# load table from local db
df = pd.read_sql_table(local_name, con=engine)
assert len(df) > 0, "Table did not load correctly"
# Persist the data from the file into a table in HANA
upload = dataframe.create_dataframe_from_pandas(
connection_context=conn,
pandas_df=df,
table_name=table_name,
schema=schema_name,
force=True,
replace=True)
upload = conn.table(table_name, schema=schema_name)
print('Success!\n', upload.head(1).collect())
| 30.409836
| 75
| 0.689488
|
6769efd6b2ee19441eb5cf34b87ac11f35ccc720
| 255
|
py
|
Python
|
proj/migrations/0005_merge_0003_merge_20220131_1826_0004_photo.py
|
StarrFnl/CS_django_2122
|
441adb6df7fba17ccde72f9cf0b7803f8aa2621b
|
[
"MIT"
] | null | null | null |
proj/migrations/0005_merge_0003_merge_20220131_1826_0004_photo.py
|
StarrFnl/CS_django_2122
|
441adb6df7fba17ccde72f9cf0b7803f8aa2621b
|
[
"MIT"
] | 1
|
2022-01-26T08:54:44.000Z
|
2022-01-26T08:54:44.000Z
|
proj/migrations/0005_merge_0003_merge_20220131_1826_0004_photo.py
|
StarrFnl/CS_django_2122
|
441adb6df7fba17ccde72f9cf0b7803f8aa2621b
|
[
"MIT"
] | 3
|
2022-01-20T14:55:02.000Z
|
2022-01-26T11:16:35.000Z
|
# Generated by Django 4.0.2 on 2022-02-07 10:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('proj', '0003_merge_20220131_1826'),
('proj', '0004_photo'),
]
operations = [
]
| 17
| 47
| 0.623529
|
85d0b710b11f59abe099ce066bddcb259859ce54
| 4,041
|
py
|
Python
|
visualisation.py
|
Rubin-ga/pandemics
|
653275ad938d908d191edeb3c362c77b0c968e71
|
[
"BSD-2-Clause"
] | null | null | null |
visualisation.py
|
Rubin-ga/pandemics
|
653275ad938d908d191edeb3c362c77b0c968e71
|
[
"BSD-2-Clause"
] | null | null | null |
visualisation.py
|
Rubin-ga/pandemics
|
653275ad938d908d191edeb3c362c77b0c968e71
|
[
"BSD-2-Clause"
] | null | null | null |
#!/usr/bin/env python
# coding: utf-8
import matplotlib
import matplotlib.pyplot as plt
from IPython import display
import numpy as np
import copy
# Prepares axis for a grid visualisation
def visualisation_setup(ax, model, title=None):
ax.set_title(title)
ax.set_ylim(-0.5, model.grid.height-0.5)
ax.set_xlim(-0.5, model.grid.width-0.5)
ax.set_xticks(np.arange(0, model.grid.width, 2))
ax.set_yticks(np.arange(0, model.grid.height, 2))
# Visualises single feature from profile for all agents
def heatmap_all_agents_profile_feature(ax, cax, model, feature):
visualisation_setup(ax, model, feature)
matrix = np.zeros((model.grid.height, model.grid.width))
for content, x, y in model.grid.coord_iter():
f_sum = 0
for a in content:
f_sum += a.profile[feature]
if content:
f_avg = f_sum/len(content)
matrix[y][x] = f_avg
else:
matrix[y][x] = -1
cmap = copy.copy(plt.cm.get_cmap('seismic'))
cmap.set_under('black')
im = ax.imshow(matrix, vmin=0, vmax=1, cmap=cmap)
ax.set_title(feature)
plt.colorbar(im, ax=ax, cax=cax, orientation="horizontal")
# Visualises safety for all cells
def heatmap_safety_per_cell(ax, cax, model):
visualisation_setup(ax, model, "safety per cell")
im = ax.imshow(model.safety_per_cell, vmin=0, vmax=1, cmap='Blues_r', origin='lower', aspect='auto')
plt.colorbar(im, ax=ax, cax=cax, orientation="horizontal")
# Visualises building types
def visualise_buildings_map(ax, cax, model):
visualisation_setup(ax, model, "building map")
cmap = matplotlib.cm.get_cmap('Blues_r', 100)
cmap.set_under('lightgrey')
im = ax.imshow(model.buildings_map,
vmin=min(model.config.building_tags.values()),
vmax=max(model.config.building_tags.values()),
cmap=cmap, origin='lower', aspect='auto')
plt.colorbar(im, ax=ax, cax=cax, orientation="horizontal")
# Displays single agent position with given color. If `tail` is True
# also show path from previous position.
def visualise_agent_position(ax, model, agent, c='red', tail=False):
visualisation_setup(ax, model, "position")
if agent.prev_pos:
px, py = agent.prev_pos
else:
px, py = agent.pos
x, y = agent.pos
ax.plot([x], [y], color=c, markersize=5, marker='o')
if tail and abs(px-x) <= 1 and abs(py-y) <= 1: # the grid is toroidal
ax.plot([px, x], [py, y], color=c, markersize=5, marker=None)
# Display all agents positions coloring them by colormap
def visualise_all_agents_position(ax, model):
visualisation_setup(ax, model, "position")
cmap = plt.cm.get_cmap('summer')
#normalize item number values to colormap
norm = matplotlib.colors.Normalize(vmin=0, vmax=len(model.schedule.agents))
for a in model.schedule.agents:
visualise_agent_position(ax, model, a, cmap(norm(a.unique_id)), True)
# Maps agent infection state to color
def get_color_for_infection_state(agent):
if agent.is_infected() and not agent.is_infectious():
return "pink"
elif agent.is_infectious() and not agent.is_symptomatic():
return "red"
elif agent.is_infectious() and agent.is_symptomatic():
return "orange"
elif agent.is_immune():
return "green"
return "yellow"
# Displays all agents positions coloring them by COVID status
def visualise_all_agents_position_and_covid_status(ax, model):
visualisation_setup(ax, model, "position and COVID status")
for a in model.schedule.agents:
c = get_color_for_infection_state(a)
visualise_agent_position(ax, model, a, c=c, tail=True)
def plot_agent_feature(ax, model, agent, feature):
all_data = model.datacollector.get_agent_vars_dataframe()
agent_data = all_data.xs(agent.unique_id, level="AgentID")[feature]
agent_data.plot(ax=ax)
ax.set_title(feature)
def plot_all_agents_feature(ax, model, feature):
for a in model.schedule.agents:
plot_agent_feature(ax, model, a, feature)
| 38.485714
| 104
| 0.690176
|
467a1430a761d9e8d7e184058bf6979799f6eb5a
| 2,823
|
py
|
Python
|
test/test_inline_object1.py
|
bsneade/statuspageio-python
|
30526a2984251885381e781b12b5070d46063537
|
[
"Apache-2.0"
] | 2
|
2020-03-02T20:32:32.000Z
|
2020-05-20T16:54:58.000Z
|
test/test_inline_object1.py
|
bsneade/statuspageio-python
|
30526a2984251885381e781b12b5070d46063537
|
[
"Apache-2.0"
] | null | null | null |
test/test_inline_object1.py
|
bsneade/statuspageio-python
|
30526a2984251885381e781b12b5070d46063537
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
"""
Statuspage API
# Code of Conduct Please don't abuse the API, and please report all feature requests and issues to https://help.statuspage.io/help/contact-us-30 # Rate Limiting Each API token is limited to 1 request / second as measured on a 60 second rolling window. To get this limit increased or lifted, please contact us at https://help.statuspage.io/help/contact-us-30 # Basics ## HTTPS It's required ## URL Prefix In order to maintain version integrity into the future, the API is versioned. All calls currently begin with the following prefix: https://api.statuspage.io/v1/ ## RESTful Interface Wherever possible, the API seeks to implement repeatable patterns with logical, representative URLs and descriptive HTTP verbs. Below are some examples and conventions you will see throughout the documentation. * Collections are buckets: https://api.statuspage.io/v1/pages/asdf123/incidents.json * Elements have unique IDs: https://api.statuspage.io/v1/pages/asdf123/incidents/jklm456.json * GET will retrieve information about a collection/element * POST will create an element in a collection * PATCH will update a single element * PUT will replace a single element in a collection (rarely used) * DELETE will destroy a single element ## Sending Data Information can be sent in the body as form urlencoded or JSON, but make sure the Content-Type header matches the body structure or the server gremlins will be angry. All examples are provided in JSON format, however they can easily be converted to form encoding if required. Some examples of how to convert things are below: // JSON { \"incident\": { \"name\": \"test incident\", \"components\": [\"8kbf7d35c070\", \"vtnh60py4yd7\"] } } // Form Encoded (using curl as an example): curl -X POST https://api.statuspage.io/v1/example \\ -d \"incident[name]=test incident\" \\ -d \"incident[components][]=8kbf7d35c070\" \\ -d \"incident[components][]=vtnh60py4yd7\" # Authentication <!-- ReDoc-Inject: <security-definitions> --> # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import spio
from spio.models.inline_object1 import InlineObject1 # noqa: E501
from spio.rest import ApiException
class TestInlineObject1(unittest.TestCase):
"""InlineObject1 unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testInlineObject1(self):
"""Test InlineObject1"""
# FIXME: construct object with mandatory attributes with example values
# model = spio.models.inline_object1.InlineObject1() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| 70.575
| 2,064
| 0.722281
|
f11e2eec27115cb3b26f998073c80da97c2caf32
| 194
|
py
|
Python
|
Voice Robot.py
|
iJARG/Voice-Robot
|
2317162e9f3208e704ffd44fe1b0b534a8015746
|
[
"Apache-2.0"
] | null | null | null |
Voice Robot.py
|
iJARG/Voice-Robot
|
2317162e9f3208e704ffd44fe1b0b534a8015746
|
[
"Apache-2.0"
] | null | null | null |
Voice Robot.py
|
iJARG/Voice-Robot
|
2317162e9f3208e704ffd44fe1b0b534a8015746
|
[
"Apache-2.0"
] | null | null | null |
from gtts import gTTS
import os
mytext = 'write here'
language = 'es'
myobj = gTTS(text=mytext, lang=language, slow=False)
myobj.save("audio.mp3")
os.system("mpg321 audio.mp3")
| 14.923077
| 53
| 0.670103
|
445699713379ac81fd254c6e788cd692789163da
| 2,533
|
py
|
Python
|
tests/executors/crafters/image/test_crop.py
|
phamtrancsek12/jina
|
efa339fd7e19760d9033b51e54a1b5eca60f1c5f
|
[
"Apache-2.0"
] | 2
|
2021-06-18T11:55:15.000Z
|
2021-08-30T20:15:46.000Z
|
tests/executors/crafters/image/test_crop.py
|
phamtrancsek12/jina
|
efa339fd7e19760d9033b51e54a1b5eca60f1c5f
|
[
"Apache-2.0"
] | null | null | null |
tests/executors/crafters/image/test_crop.py
|
phamtrancsek12/jina
|
efa339fd7e19760d9033b51e54a1b5eca60f1c5f
|
[
"Apache-2.0"
] | null | null | null |
import unittest
import numpy as np
from jina.executors.crafters.image.crop import ImageCropper, CenterImageCropper, RandomImageCropper, FiveImageCropper, \
SlidingWindowImageCropper
from tests.executors.crafters.image import JinaImageTestCase
class MyTestCase(JinaImageTestCase):
def test_crop(self):
img_size = 217
img_array = self.create_random_img_array(img_size, img_size)
left = 2
top = 17
width = 20
height = 20
crafter = ImageCropper(left, top, width, height)
crafted_chunk = crafter.craft(img_array, 0, 0)
np.testing.assert_array_equal(
crafted_chunk['blob'], np.asarray(img_array[top:top + height, left:left + width, :]),
'img_array: {}\ntest: {}\ncontrol:{}'.format(
img_array.shape,
crafted_chunk['blob'].shape,
np.asarray(img_array[left:left + width, top:top + height, :]).shape))
def test_center_crop(self):
img_size = 217
img_array = self.create_random_img_array(img_size, img_size)
output_dim = 20
crafter = CenterImageCropper(output_dim)
crafted_chunk = crafter.craft(img_array, 0, 0)
self.assertEqual(crafted_chunk["blob"].shape, (20, 20, 3))
def test_random_crop(self):
img_size = 217
img_array = self.create_random_img_array(img_size, img_size)
output_dim = 20
num_pathes = 20
crafter = RandomImageCropper(output_dim, num_pathes)
crafted_chunk_list = crafter.craft(img_array, 0, 0)
self.assertEqual(len(crafted_chunk_list), num_pathes)
def test_random_crop(self):
img_size = 217
img_array = self.create_random_img_array(img_size, img_size)
output_dim = 20
crafter = FiveImageCropper(output_dim)
crafted_chunk_list = crafter.craft(img_array, 0, 0)
self.assertEqual(len(crafted_chunk_list), 5)
def test_sliding_windows(self):
img_size = 14
img_array = self.create_random_img_array(img_size, img_size)
output_dim = 4
strides = (6, 6)
crafter = SlidingWindowImageCropper(output_dim, strides, 'VALID')
crafted_chunk_list = crafter.craft(img_array, 0, 0)
self.assertEqual(len(crafted_chunk_list), 4)
crafter = SlidingWindowImageCropper(output_dim, strides, 'SAME')
crafted_chunk_list = crafter.craft(img_array, 0, 0)
self.assertEqual(len(crafted_chunk_list), 9)
if __name__ == '__main__':
unittest.main()
| 37.25
| 120
| 0.664824
|
15c651981487e8ff83598eac39f7579e427b7788
| 4,101
|
py
|
Python
|
scraping.py
|
daniel89mk/Mission-to-Mars
|
1fe91f9ed08e1c28da0c79b1b7a56c72f0c3449d
|
[
"MIT"
] | null | null | null |
scraping.py
|
daniel89mk/Mission-to-Mars
|
1fe91f9ed08e1c28da0c79b1b7a56c72f0c3449d
|
[
"MIT"
] | null | null | null |
scraping.py
|
daniel89mk/Mission-to-Mars
|
1fe91f9ed08e1c28da0c79b1b7a56c72f0c3449d
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
# coding: utf-8
# Import Splinter and BeautifulSoup
from splinter import Browser
from bs4 import BeautifulSoup as soup
import pandas as pd
import datetime as dt
from webdriver_manager.chrome import ChromeDriverManager
def scrape_all():
# Initiate headless drvier for deployment
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=True)
news_title, news_p = mars_news(browser)
# hemisphere_image_urls = hemispheres(browser)
# Run all scraping functions and store results in a dictionary
data = {
"news_title": news_title,
"news_paragraph": news_p,
"featured_image": featured_image(browser),
"facts": mars_facts(),
"last_modified": dt.datetime.now(),
"hemispheres": hemispheres(browser)
}
# Stop webdriver and return data
browser.quit()
return data
# Visit the mars nasa news site
def mars_news(browser):
url = 'https://redplanetscience.com'
browser.visit(url)
# Optional delay for loading the page
browser.is_element_present_by_css('div.list_text', wait_time=1)
html = browser.html
news_soup = soup(html, 'html.parser')
try:
slide_elem = news_soup.select_one('div.list_text')
slide_elem.find('div', class_='content_title')
# Use the parent element to find the first `a` tag and save it as `news_title`
news_title = slide_elem.find('div', class_='content_title').get_text()
# Use the parent element to find the paragraph text
news_p = slide_elem.find('div', class_='article_teaser_body').get_text()
except AttributeError:
return None, None
return news_title, news_p
# ### Featured Images
# Visit URL
def featured_image(browser):
url = 'https://spaceimages-mars.com'
browser.visit(url)
# Find and click the full image button
full_image_elem = browser.find_by_tag('button')[1]
full_image_elem.click()
browser.is_element_present_by_text('more info', wait_time=1)
# Parse the resulting html with soup
html = browser.html
img_soup = soup(html, 'html.parser')
try:
# Find the relative image url
img_url_rel = img_soup.find('img', class_='fancybox-image').get('src')
except AttributeError:
return None
# Use the base URL to create an absolute URL
img_url = f'https://spaceimages-mars.com/{img_url_rel}'
return img_url
def mars_facts():
try:
df = pd.read_html('https://galaxyfacts-mars.com')[0]
except BaseException:
return None
df.columns=['Description', 'Mars', 'Earth']
df.set_index('Description', inplace=True)
return df.to_html(classes="table table-striped")
def hemispheres(browser):
url = 'https://marshemispheres.com/'
browser.visit(url)
hemisphere_image_urls =[]
for i in range(4):
hemispheres = {}
browser.find_by_css('a.product-item h3')[i].click()
# hemisphere_data = scrape_hemisphere(browser.html)
# hemisphere_image_urls.append(hemisphere_data)
sample_element = browser.find_link_by_text("Sample").first
hemispheres["img_url"] = sample_element["href"]
hemispheres["title"] = browser.find_by_css("h2.title").text
hemisphere_image_urls.append(hemispheres)
browser.back()
return hemisphere_image_urls
# def scrape_hemisphere(html_text):
# hemisphere_soup = soup(html_text, "html.parser")
# try:
# title_element = hemisphere_soup.find("h2", class_="title").get_text()
# sample_element = hemisphere_soup.find("a",text='Sample').get("href")
# except AttributeError:
# title_element = None
# sample_element = None
# hemispheres_dictionary = {
# "title": title_element,
# "img_url": sample_element
# }
# return hemispheres_dictionary
if __name__ == "__main__":
# If running as script, print scraped data
print(scrape_all())
| 29.503597
| 86
| 0.663009
|
e2bf37401ec162a83d80d12aa563cb18f319ea4d
| 2,564
|
py
|
Python
|
src/data/bdd100k_drivablearea.py
|
hezl1592/deeplabv3-_mobilenetv2
|
cc3134d54bd84f700531c230353228541a7336f5
|
[
"MIT"
] | null | null | null |
src/data/bdd100k_drivablearea.py
|
hezl1592/deeplabv3-_mobilenetv2
|
cc3134d54bd84f700531c230353228541a7336f5
|
[
"MIT"
] | null | null | null |
src/data/bdd100k_drivablearea.py
|
hezl1592/deeplabv3-_mobilenetv2
|
cc3134d54bd84f700531c230353228541a7336f5
|
[
"MIT"
] | null | null | null |
from functools import partial
import numpy as np
from pathlib import Path
import os
import cv2
import torch
from torch.utils.data import DataLoader, Dataset
class BDD100K_Area_Seg(Dataset):
n_classes = 3
void_classes = []
valid_classes = [0, 1, 2]
class_map = dict(zip(valid_classes, range(n_classes)))
def __init__(self, base_dir='./dataset/bdd100k', split='train', target_size=(1280, 720), dataLen=None,
net_type='deeplab', ignore_index=255, debug=False,
affine_augmenter=None, image_augmenter=None):
self.debug = debug
assert os.path.exists(base_dir), "{} is not exists, check.".format(base_dir)
self.base_dir = Path(base_dir)
assert net_type in ['unet', 'deeplab']
self.net_type = net_type
self.ignore_index = ignore_index
self.split = 'val' if split == 'valid' else split
self.img_paths = sorted(self.base_dir.glob(f'images/{self.split}/*.jpg'))[:dataLen]
self.lbl_paths = sorted(self.base_dir.glob(f'labels/{self.split}/*drivable_id.png'))[:dataLen]
assert len(self.img_paths) == len(self.lbl_paths), "image num erro"
# Resize
# print(type(self.size), self.size)
if isinstance(target_size, str):
target_size = eval(target_size)
self.size = target_size
# Augment
if self.split == 'train':
self.affine_augmenter = affine_augmenter
self.image_augmenter = image_augmenter
else:
self.affine_augmenter = None
self.image_augmenter = None
def __len__(self):
return len(self.img_paths)
def __getitem__(self, index):
img_path = self.img_paths[index]
image_source = cv2.imread(str(img_path), -1)
image_source = cv2.resize(image_source, self.size, cv2.INTER_LINEAR)
image_tensor = torch.from_numpy(image_source.transpose((2, 0, 1)))
image_tensor = image_tensor.float().div(255)
image_tensor = image_tensor.sub(0.5).div(0.5)
lbl_path = self.lbl_paths[index]
label_source = cv2.imread(str(lbl_path), -1)
label_source = cv2.resize(label_source, self.size, cv2.INTER_NEAREST)
lbl = self.encode_mask(label_source)
label_tensor = torch.LongTensor(lbl)
return image_tensor, label_tensor
def encode_mask(self, lbl):
for c in self.void_classes:
lbl[lbl == c] = self.ignore_index
for c in self.valid_classes:
lbl[lbl == c] = self.class_map[c]
return lbl
| 36.112676
| 106
| 0.641576
|
605bda600cb2b6485d6487d1cd03550cbb72f9ea
| 3,193
|
py
|
Python
|
terminusdb_client/woql_utils.py
|
pnijhara/terminusdb-client-python
|
bdc3480c21a6c1eb123abae1592e6a2b27b046c1
|
[
"Apache-2.0"
] | null | null | null |
terminusdb_client/woql_utils.py
|
pnijhara/terminusdb-client-python
|
bdc3480c21a6c1eb123abae1592e6a2b27b046c1
|
[
"Apache-2.0"
] | null | null | null |
terminusdb_client/woql_utils.py
|
pnijhara/terminusdb-client-python
|
bdc3480c21a6c1eb123abae1592e6a2b27b046c1
|
[
"Apache-2.0"
] | null | null | null |
import urllib.parse
STANDARD_URLS = {
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"xsd": "http://www.w3.org/2001/XMLSchema#",
"xdd": "http://terminusdb.com/schema/xdd#",
"owl": "http://www.w3.org/2002/07/owl#",
"terminus": "http://terminusdb.com/schema/terminus#",
"vio": "http://terminusdb.com/schema/vio#",
"repo": "http://terminusdb.com/schema/repository#",
"layer": "http://terminusdb.com/schema/layer#",
"woql": "http://terminusdb.com/schema/woql#",
"ref": "http://terminusdb.com/schema/ref#",
}
def encode_uri_component(value):
return urllib.parse.urlencode(value, doseq=True)
def uri_encode_payload(payload):
if isinstance(payload, str):
return encode_uri_component(payload)
payload_arr = []
if isinstance(payload, dict):
for key, value in payload.items():
"""
if dictionary inside dictionary
"""
if isinstance(value, dict):
# for keyElement,valueElement in value.items():
payload_arr.append(encode_uri_component(value))
else:
payload_arr.append(encode_uri_component({key: value}))
return "&".join(payload_arr)
def add_params_to_url(url, payload):
if payload:
params = uri_encode_payload(payload)
if params:
url = "{}?{}".format(url, params)
return url
# below are utils for WOQLQuery
def add_namespaces_to_variable(var):
if var[:2] != "v:":
return "v:" + var
return var
def add_namespaces_to_variables(variables):
nvars = []
for v_item in variables:
nvars.append(add_namespaces_to_variable(v_item))
return nvars
def empty(obj):
""" * is the object empty?
* returns true if the json object is empty
"""
if not obj:
# Assume if it has a length property with a non-zero value
# that that property is correct.
return True
if len(obj) > 0:
return False
if len(obj) == 0:
return True
# Otherwise, does it have any properties of its own?
# if type(obj) == dict:
# for key in obj.keys():
# if hasattr(obj,key):
# return False
return True
def shorten(url, prefixes=None):
prefixes = prefixes if prefixes else STANDARD_URLS
for pref, val in prefixes.items():
short_url = url[: len(val)]
if val == short_url:
return f"{pref}:{short_url}"
return url
def is_data_type(stype):
sh = shorten(stype)
if sh and (sh[:4] == "xsd:" or sh[:4] == "xdd:"):
return True
return False
def valid_url(string):
if string and (string[:7] == "http://" or string[:8] == "https://"):
return True
return False
def url_fraqment(url):
bits = url.split("#")
if len(bits) > 1:
return bits[1]
return url
def label_from_url(url):
nurl = url_fraqment(url)
nurl = nurl if nurl else url
last_char = nurl.rfind("/")
if last_char < len(nurl) - 1:
nurl = nurl[last_char + 1 :]
nurl = nurl.replace("_", " ")
return nurl[0].upper() + nurl[1:]
| 26.38843
| 72
| 0.593799
|
79f97baba816049ba7fa4c7e47c994ee9f7d6a28
| 7,023
|
py
|
Python
|
Python/GoogleTranslator.py
|
Avey777/free-google-translate
|
12a92cd424c620bd9661abcf962205b212d35906
|
[
"MIT"
] | 99
|
2020-04-23T14:24:23.000Z
|
2022-03-27T08:17:25.000Z
|
Python/GoogleTrans2.py
|
leungBH/free-google-translate
|
3d0c1eae8b86c910393a76a73b7b0759a1bb25b1
|
[
"MIT"
] | 6
|
2020-09-22T12:02:17.000Z
|
2021-09-27T10:52:34.000Z
|
Python/GoogleTrans2.py
|
leungBH/free-google-translate
|
3d0c1eae8b86c910393a76a73b7b0759a1bb25b1
|
[
"MIT"
] | 48
|
2020-05-15T14:59:59.000Z
|
2022-03-21T07:36:50.000Z
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# 网友的建议:https://github.com/VictorZhang2014/free-google-translate/issues/6
#
import urllib.parse
import requests
import json
import re
import ssl
import ctypes
ssl._create_default_https_context = ssl._create_unverified_context
class GoogleTrans(object):
def __init__(self):
self.url = 'https://translate.google.cn/translate_a/single'
self.TKK = "434674.96463358" # 随时都有可能需要更新的TKK值
self.header = {
"accept": "*/*",
"accept-language": "zh-CN,zh;q=0.9",
"cookie": "NID=188=M1p_rBfweeI_Z02d1MOSQ5abYsPfZogDrFjKwIUbmAr584bc9GBZkfDwKQ80cQCQC34zwD4ZYHFMUf4F59aDQLSc79_LcmsAihnW0Rsb1MjlzLNElWihv-8KByeDBblR2V1kjTSC8KnVMe32PNSJBQbvBKvgl4CTfzvaIEgkqss",
"referer": "https://translate.google.cn/",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
"x-client-data": "CJK2yQEIpLbJAQjEtskBCKmdygEIqKPKAQi5pcoBCLGnygEI4qjKAQjxqcoBCJetygEIza3KAQ==",
}
self.data = {
"client": "webapp", # 基于网页访问服务器
"sl": "auto", # 源语言,auto表示由谷歌自动识别
"tl": "vi", # 翻译的目标语言
"hl": "zh-CN", # 界面语言选中文,毕竟URL都是cn后缀了,就不装美国人了
"dt": ["at", "bd", "ex", "ld", "md", "qca", "rw", "rm", "ss", "t"], # dt表示要求服务器返回的数据类型
"otf": "2",
"ssel": "0",
"tsel": "0",
"kc": "1",
"tk": "", # 谷歌服务器会核对的token
"q": "" # 待翻译的字符串
}
class JSHackToken():
def rshift(self, val, n): return (val % 0x100000000) >> n
def Number(self, val):
try:
return eval(val, {}, {})
except:
return 0
class Undefined:
def __init__():
pass
class js_array():
def __init__(self, outer, init=[]):
self.outer = outer
self.storage = list(init).copy()
def __getitem__(self, key):
if (type(key).__name__ != 'int'):
if (type(key).__name__ == 'float') and int(key) != key:
return 0
try:
key = int(key)
except:
return 0
if len(self.storage)<=key or key<0:
return 0
return self.storage[key]
def __setitem__(self, key, value):
if (type(key).__name__ != 'int'):
if (type(key).__name__ == 'float') and int(key) != key:
return 0
try:
key = int(key)
except:
return 0
if key<0:
return 0
while key >= len(self.storage):
self.storage.append(0)
self.storage[key] = value
return
def __len__(self):
return len(self.storage)
def __str__(self):
return self.storage.__str__()
def __repr__(self):
return self.storage.__repr__()
def array(self, init = []):
return self.js_array(self, init)
def uo(self, a, b):
for c in range(0, len(b)-2, 3):
d = b[c+2]
if 'a' <= d:
d = ord(d)-87
else:
d = self.Number(d)
if '+' == b[c+1]:
d = self.rshift(a, d)
else:
d = a<<d
if b[c] == "+":
a = a + d & 4294967295
else:
a = a ^ d
return a
def wo(self, a, tkk):
d = self.array(init = tkk.split("."))
b = self.Number(d[0])
e = self.array()
f = 0
g = 0
while g < len(a):
h = ord(a[g])
if 128 > h:
e[f] = h
f += 1
else:
if 2048 > h:
e[f] = h >> 6 | 192
f += 1
else:
if (55296 == (h & 64512)) and (g + 1 < len(a)) and (56320 == (ord(a[g+1]) & 64512)):
h = 65536 + ((h & 1023) << 10) + (ord(a[g+1]) & 1023)
g += 1
e[f] = h >> 18 | 240
f += 1
e[f] = h >> 12 & 63 | 128
f += 1
else:
e[f] = h >> 12 | 224
f += 1
e[f] = h >> 6 & 63 | 128
f += 1
e[f] = h & 63 | 128
f += 1
g += 1
a = b
for f in range(0, len(e)):
a += e[f]
a = ctypes.c_long(a).value
a = self.uo(a, '+-a^+6')
a = self.uo(a, '+-3^+b+-f')
a ^= self.Number(d[1])
if 0 > a:
a = (a & 2147483647)+2147483648
a %= 10**6
return str(a)+'.'+str(a^b)
# 构建完对象以后要同步更新一下TKK值
# self.update_TKK()
def update_TKK(self):
url = "https://translate.google.cn/"
req = requests.get(url, headers=self.header)
page_source = req.text
self.TKK = re.findall(r"tkk:'([0-9]+\.[0-9]+)'", page_source)[0]
def construct_url(self):
base = self.url + '?'
for key in self.data:
if isinstance(self.data[key], list):
base = base + "dt=" + "&dt=".join(self.data[key]) + "&"
else:
base = base + key + '=' + self.data[key] + '&'
base = base[:-1]
return base
def query(self, q, lang_to=''):
self.data['q'] = urllib.parse.quote(q)
self.data['tk'] = self.JSHackToken().wo(q, self.TKK)
self.data['tl'] = lang_to
url = self.construct_url()
robj = requests.post(url)
response = json.loads(robj.text)
targetText = response[0][0][0]
originalText = response[0][0][1]
originalLanguageCode = response[2]
print("翻译前:{},翻译前code:{}".format(originalText, originalLanguageCode))
print("==============================")
print("翻译后:{}, 翻译后code:{}".format(targetText, lang_to))
return originalText, originalLanguageCode, targetText, lang_to
if __name__ == '__main__':
text = "Hello world"
originalText, originalLanguageCode, targetText, targetLanguageCode = GoogleTrans().query(text, lang_to='zh-CN')
print("==============================")
print(originalText, originalLanguageCode, targetText, targetLanguageCode)
| 36.769634
| 204
| 0.427595
|
890cb5da80a7f1c301ca73351f3c8091389e108b
| 144
|
py
|
Python
|
src/keep_awake.py
|
Neelhtak/notion-heroku
|
7a991d520d340ac7055905ebd6e67c3d9532c97d
|
[
"MIT"
] | 39
|
2019-07-18T20:27:06.000Z
|
2022-03-10T03:13:57.000Z
|
src/keep_awake.py
|
Neelhtak/notion-heroku
|
7a991d520d340ac7055905ebd6e67c3d9532c97d
|
[
"MIT"
] | 3
|
2019-12-09T21:56:22.000Z
|
2019-12-11T02:17:05.000Z
|
src/keep_awake.py
|
Neelhtak/notion-heroku
|
7a991d520d340ac7055905ebd6e67c3d9532c97d
|
[
"MIT"
] | 8
|
2019-07-17T03:40:24.000Z
|
2021-03-04T14:33:33.000Z
|
#!/usr/bin/env -S PATH="${PATH}:/usr/local/bin" python3
import requests
def ping():
requests.get('https://notion-heroku.herokuapp.com/')
| 18
| 56
| 0.673611
|
3f9d420bb5e04b42c5071002f4dc7699bf35f32e
| 1,800
|
py
|
Python
|
test.py
|
brucelightyear/text-summarization-tensorflow
|
359191315eb94143b463321426fdea661fdb0284
|
[
"MIT"
] | null | null | null |
test.py
|
brucelightyear/text-summarization-tensorflow
|
359191315eb94143b463321426fdea661fdb0284
|
[
"MIT"
] | null | null | null |
test.py
|
brucelightyear/text-summarization-tensorflow
|
359191315eb94143b463321426fdea661fdb0284
|
[
"MIT"
] | null | null | null |
import tensorflow as tf
import pickle
from model import Model
from utils import build_dict, build_dataset, batch_iter
with open("args.pickle", "rb") as f:
args = pickle.load(f)
print("Loading dictionary...")
word_dict, reversed_dict, article_max_len, summary_max_len = build_dict("valid", args.toy)
print("Loading validation dataset...")
valid_x = build_dataset("valid", word_dict, article_max_len, summary_max_len, args.toy)
valid_x_len = [len([y for y in x if y != 0]) for x in valid_x]
with tf.compat.v1.Session() as sess:
print("Loading saved model...")
model = Model(reversed_dict, article_max_len, summary_max_len, args, forward_only=True)
saver = tf.compat.v1.train.Saver(tf.compat.v1.global_variables())
ckpt = tf.train.get_checkpoint_state("./saved_model/")
saver.restore(sess, ckpt.model_checkpoint_path)
batches = batch_iter(valid_x, [0] * len(valid_x), args.batch_size, 1)
print("Writing summaries to 'result.txt'...")
for batch_x, _ in batches:
batch_x_len = [len([y for y in x if y != 0]) for x in batch_x]
valid_feed_dict = {
model.batch_size: len(batch_x),
model.X: batch_x,
model.X_len: batch_x_len,
}
prediction = sess.run(model.prediction, feed_dict=valid_feed_dict)
prediction_output = [[reversed_dict[y] for y in x] for x in prediction[:, 0, :]]
with open("result.txt", "a") as f:
for line in prediction_output:
summary = list()
for word in line:
if word == "</s>":
break
if word not in summary:
summary.append(word)
print(" ".join(summary), file=f)
print('Summaries are saved to "result.txt"...')
| 37.5
| 91
| 0.626111
|
a561ca4e1a2a7048a2690a184049be424842cb64
| 1,363
|
py
|
Python
|
search_service/proxy/__init__.py
|
mgorsk1/amundsensearchlibrary
|
e61bea51b9df26b382ad8d745861ba05bfbadf65
|
[
"Apache-2.0"
] | 3
|
2021-02-09T13:52:03.000Z
|
2022-02-26T02:36:02.000Z
|
search_service/proxy/__init__.py
|
mgorsk1/amundsensearchlibrary
|
e61bea51b9df26b382ad8d745861ba05bfbadf65
|
[
"Apache-2.0"
] | 1
|
2021-02-08T23:21:04.000Z
|
2021-02-08T23:21:04.000Z
|
search_service/proxy/__init__.py
|
mgorsk1/amundsensearchlibrary
|
e61bea51b9df26b382ad8d745861ba05bfbadf65
|
[
"Apache-2.0"
] | 2
|
2021-02-23T18:23:35.000Z
|
2022-03-18T15:12:25.000Z
|
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
from threading import Lock
from flask import current_app
from search_service import config
from search_service.proxy.base import BaseProxy
from werkzeug.utils import import_string
_proxy_client = None
_proxy_client_lock = Lock()
DEFAULT_PAGE_SIZE = 10
def get_proxy_client() -> BaseProxy:
"""
Provides singleton proxy client based on the config
:return: Proxy instance of any subclass of BaseProxy
"""
global _proxy_client
if _proxy_client:
return _proxy_client
with _proxy_client_lock:
if _proxy_client:
return _proxy_client
else:
obj = current_app.config[config.PROXY_CLIENT_KEY]
# Gather all the configuration to create a Proxy Client
host = current_app.config[config.PROXY_ENDPOINT]
user = current_app.config[config.PROXY_USER]
password = current_app.config[config.PROXY_PASSWORD]
client = import_string(current_app.config[config.PROXY_CLIENT])
# number of results per search page
page_size = current_app.config.get(config.SEARCH_PAGE_SIZE_KEY, DEFAULT_PAGE_SIZE)
_proxy_client = client(host=host, user=user, password=password, client=obj, page_size=page_size)
return _proxy_client
| 29.630435
| 108
| 0.7146
|
3e71109ac878ce791f251495491c42ac225bf98b
| 2,099
|
py
|
Python
|
train/dataloaders/base_loader.py
|
idearibosome/tf_perceptual_eusr
|
2bdd79adcbb7ee55bfc0593879fd5831c9859098
|
[
"Apache-2.0"
] | 45
|
2018-09-12T19:15:18.000Z
|
2021-06-11T13:12:55.000Z
|
dataloaders/base_loader.py
|
idearibosome/tf-sr-attack
|
0fed8bc639449dd1556fb6071658b26e64f68783
|
[
"Apache-2.0"
] | 6
|
2018-10-29T11:04:35.000Z
|
2021-08-24T06:33:36.000Z
|
dataloaders/base_loader.py
|
idearibosome/tf-sr-attack
|
0fed8bc639449dd1556fb6071658b26e64f68783
|
[
"Apache-2.0"
] | 11
|
2018-10-11T05:14:14.000Z
|
2021-03-13T16:09:15.000Z
|
import os
import numpy as np
import tensorflow as tf
FLAGS = tf.flags.FLAGS
def create_loader():
return BaseLoader()
class BaseLoader():
def __init__(self):
pass
def prepare(self):
"""
Prepare the data loader.
"""
raise NotImplementedError
def get_num_images(self):
"""
Get the number of images.
Returns:
The number of images.
"""
raise NotImplementedError
def get_patch_batch(self, batch_size, scale, input_patch_size):
"""
Get a batch of input and ground-truth image patches.
Args:
batch_size: The number of image patches.
scale: Scale of the input image patches.
input_patch_size: Size of the input image patches.
Returns:
input_list: A list of input image patches.
truth_list: A list of ground-truth image patches.
"""
raise NotImplementedError
def get_random_image_patch_pair(self, scale, input_patch_size):
"""
Get a random pair of input and ground-truth image patches.
Args:
scale: Scale of the input image patch.
input_patch_size: Size of the input image patch.
Returns:
A tuple of (input image patch, ground-truth image patch).
"""
raise NotImplementedError
def get_image_patch_pair(self, image_index, scale, input_patch_size):
"""
Get a pair of input and ground-truth image patches for given image index.
Args:
image_index: Index of the image to be retrieved. Should be in [0, get_num_images()-1].
scale: Scale of the input image patch.
input_patch_size: Size of the input image patch.
Returns:
A tuple of (input image patch, ground-truth image patch).
"""
raise NotImplementedError
def get_image_pair(self, image_index, scale):
"""
Get a pair of input and ground-truth images for given image index.
Args:
image_index: Index of the image to be retrieved. Should be in [0, get_num_images()-1].
scale: Scale of the input image.
Returns:
A tuple of (input image, ground-truth image, image_name).
"""
raise NotImplementedError
| 27.986667
| 92
| 0.679371
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.