repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Grunny/zap-cli | zapcli/commands/context.py | context_list | def context_list(zap_helper):
"""List the available contexts."""
contexts = zap_helper.zap.context.context_list
if len(contexts):
console.info('Available contexts: {0}'.format(contexts[1:-1]))
else:
console.info('No contexts available in the current session') | python | def context_list(zap_helper):
"""List the available contexts."""
contexts = zap_helper.zap.context.context_list
if len(contexts):
console.info('Available contexts: {0}'.format(contexts[1:-1]))
else:
console.info('No contexts available in the current session') | [
"def",
"context_list",
"(",
"zap_helper",
")",
":",
"contexts",
"=",
"zap_helper",
".",
"zap",
".",
"context",
".",
"context_list",
"if",
"len",
"(",
"contexts",
")",
":",
"console",
".",
"info",
"(",
"'Available contexts: {0}'",
".",
"format",
"(",
"context... | List the available contexts. | [
"List",
"the",
"available",
"contexts",
"."
] | d58d4850ecfc5467badfac5e5bcc841d064bd419 | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L23-L29 | train | 202,300 |
Grunny/zap-cli | zapcli/commands/context.py | context_new | def context_new(zap_helper, name):
"""Create a new context."""
console.info('Creating context with name: {0}'.format(name))
res = zap_helper.zap.context.new_context(contextname=name)
console.info('Context "{0}" created with ID: {1}'.format(name, res)) | python | def context_new(zap_helper, name):
"""Create a new context."""
console.info('Creating context with name: {0}'.format(name))
res = zap_helper.zap.context.new_context(contextname=name)
console.info('Context "{0}" created with ID: {1}'.format(name, res)) | [
"def",
"context_new",
"(",
"zap_helper",
",",
"name",
")",
":",
"console",
".",
"info",
"(",
"'Creating context with name: {0}'",
".",
"format",
"(",
"name",
")",
")",
"res",
"=",
"zap_helper",
".",
"zap",
".",
"context",
".",
"new_context",
"(",
"contextnam... | Create a new context. | [
"Create",
"a",
"new",
"context",
"."
] | d58d4850ecfc5467badfac5e5bcc841d064bd419 | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L35-L39 | train | 202,301 |
Grunny/zap-cli | zapcli/commands/context.py | context_include | def context_include(zap_helper, name, pattern):
"""Include a pattern in a given context."""
console.info('Including regex {0} in context with name: {1}'.format(pattern, name))
with zap_error_handler():
result = zap_helper.zap.context.include_in_context(contextname=name, regex=pattern)
if result != 'OK':
raise ZAPError('Including regex from context failed: {}'.format(result)) | python | def context_include(zap_helper, name, pattern):
"""Include a pattern in a given context."""
console.info('Including regex {0} in context with name: {1}'.format(pattern, name))
with zap_error_handler():
result = zap_helper.zap.context.include_in_context(contextname=name, regex=pattern)
if result != 'OK':
raise ZAPError('Including regex from context failed: {}'.format(result)) | [
"def",
"context_include",
"(",
"zap_helper",
",",
"name",
",",
"pattern",
")",
":",
"console",
".",
"info",
"(",
"'Including regex {0} in context with name: {1}'",
".",
"format",
"(",
"pattern",
",",
"name",
")",
")",
"with",
"zap_error_handler",
"(",
")",
":",
... | Include a pattern in a given context. | [
"Include",
"a",
"pattern",
"in",
"a",
"given",
"context",
"."
] | d58d4850ecfc5467badfac5e5bcc841d064bd419 | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L48-L55 | train | 202,302 |
Grunny/zap-cli | zapcli/commands/context.py | context_exclude | def context_exclude(zap_helper, name, pattern):
"""Exclude a pattern from a given context."""
console.info('Excluding regex {0} from context with name: {1}'.format(pattern, name))
with zap_error_handler():
result = zap_helper.zap.context.exclude_from_context(contextname=name, regex=pattern)
if result != 'OK':
raise ZAPError('Excluding regex from context failed: {}'.format(result)) | python | def context_exclude(zap_helper, name, pattern):
"""Exclude a pattern from a given context."""
console.info('Excluding regex {0} from context with name: {1}'.format(pattern, name))
with zap_error_handler():
result = zap_helper.zap.context.exclude_from_context(contextname=name, regex=pattern)
if result != 'OK':
raise ZAPError('Excluding regex from context failed: {}'.format(result)) | [
"def",
"context_exclude",
"(",
"zap_helper",
",",
"name",
",",
"pattern",
")",
":",
"console",
".",
"info",
"(",
"'Excluding regex {0} from context with name: {1}'",
".",
"format",
"(",
"pattern",
",",
"name",
")",
")",
"with",
"zap_error_handler",
"(",
")",
":"... | Exclude a pattern from a given context. | [
"Exclude",
"a",
"pattern",
"from",
"a",
"given",
"context",
"."
] | d58d4850ecfc5467badfac5e5bcc841d064bd419 | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L64-L71 | train | 202,303 |
Grunny/zap-cli | zapcli/commands/context.py | context_info | def context_info(zap_helper, context_name):
"""Get info about the given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
console.info('ID: {}'.format(info['id']))
console.info('Name: {}'.format(info['name']))
console.info('Authentication type: {}'.format(info['authType']))
console.info('Included regexes: {}'.format(info['includeRegexs']))
console.info('Excluded regexes: {}'.format(info['excludeRegexs'])) | python | def context_info(zap_helper, context_name):
"""Get info about the given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
console.info('ID: {}'.format(info['id']))
console.info('Name: {}'.format(info['name']))
console.info('Authentication type: {}'.format(info['authType']))
console.info('Included regexes: {}'.format(info['includeRegexs']))
console.info('Excluded regexes: {}'.format(info['excludeRegexs'])) | [
"def",
"context_info",
"(",
"zap_helper",
",",
"context_name",
")",
":",
"with",
"zap_error_handler",
"(",
")",
":",
"info",
"=",
"zap_helper",
".",
"get_context_info",
"(",
"context_name",
")",
"console",
".",
"info",
"(",
"'ID: {}'",
".",
"format",
"(",
"i... | Get info about the given context. | [
"Get",
"info",
"about",
"the",
"given",
"context",
"."
] | d58d4850ecfc5467badfac5e5bcc841d064bd419 | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L77-L86 | train | 202,304 |
Grunny/zap-cli | zapcli/commands/context.py | context_list_users | def context_list_users(zap_helper, context_name):
"""List the users available for a given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
user_list = ', '.join([user['name'] for user in users])
console.info('Available users for the context {0}: {1}'.format(context_name, user_list))
else:
console.info('No users configured for the context {}'.format(context_name)) | python | def context_list_users(zap_helper, context_name):
"""List the users available for a given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
user_list = ', '.join([user['name'] for user in users])
console.info('Available users for the context {0}: {1}'.format(context_name, user_list))
else:
console.info('No users configured for the context {}'.format(context_name)) | [
"def",
"context_list_users",
"(",
"zap_helper",
",",
"context_name",
")",
":",
"with",
"zap_error_handler",
"(",
")",
":",
"info",
"=",
"zap_helper",
".",
"get_context_info",
"(",
"context_name",
")",
"users",
"=",
"zap_helper",
".",
"zap",
".",
"users",
".",
... | List the users available for a given context. | [
"List",
"the",
"users",
"available",
"for",
"a",
"given",
"context",
"."
] | d58d4850ecfc5467badfac5e5bcc841d064bd419 | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L92-L102 | train | 202,305 |
Grunny/zap-cli | zapcli/commands/context.py | context_import | def context_import(zap_helper, file_path):
"""Import a saved context file."""
with zap_error_handler():
result = zap_helper.zap.context.import_context(file_path)
if not result.isdigit():
raise ZAPError('Importing context from file failed: {}'.format(result))
console.info('Imported context from {}'.format(file_path)) | python | def context_import(zap_helper, file_path):
"""Import a saved context file."""
with zap_error_handler():
result = zap_helper.zap.context.import_context(file_path)
if not result.isdigit():
raise ZAPError('Importing context from file failed: {}'.format(result))
console.info('Imported context from {}'.format(file_path)) | [
"def",
"context_import",
"(",
"zap_helper",
",",
"file_path",
")",
":",
"with",
"zap_error_handler",
"(",
")",
":",
"result",
"=",
"zap_helper",
".",
"zap",
".",
"context",
".",
"import_context",
"(",
"file_path",
")",
"if",
"not",
"result",
".",
"isdigit",
... | Import a saved context file. | [
"Import",
"a",
"saved",
"context",
"file",
"."
] | d58d4850ecfc5467badfac5e5bcc841d064bd419 | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L108-L116 | train | 202,306 |
Grunny/zap-cli | zapcli/commands/context.py | context_export | def context_export(zap_helper, name, file_path):
"""Export a given context to a file."""
with zap_error_handler():
result = zap_helper.zap.context.export_context(name, file_path)
if result != 'OK':
raise ZAPError('Exporting context to file failed: {}'.format(result))
console.info('Exported context {0} to {1}'.format(name, file_path)) | python | def context_export(zap_helper, name, file_path):
"""Export a given context to a file."""
with zap_error_handler():
result = zap_helper.zap.context.export_context(name, file_path)
if result != 'OK':
raise ZAPError('Exporting context to file failed: {}'.format(result))
console.info('Exported context {0} to {1}'.format(name, file_path)) | [
"def",
"context_export",
"(",
"zap_helper",
",",
"name",
",",
"file_path",
")",
":",
"with",
"zap_error_handler",
"(",
")",
":",
"result",
"=",
"zap_helper",
".",
"zap",
".",
"context",
".",
"export_context",
"(",
"name",
",",
"file_path",
")",
"if",
"resu... | Export a given context to a file. | [
"Export",
"a",
"given",
"context",
"to",
"a",
"file",
"."
] | d58d4850ecfc5467badfac5e5bcc841d064bd419 | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L125-L133 | train | 202,307 |
marshmallow-code/flask-marshmallow | src/flask_marshmallow/fields.py | _get_value | def _get_value(obj, key, default=missing):
"""Slightly-modified version of marshmallow.utils.get_value.
If a dot-delimited ``key`` is passed and any attribute in the
path is `None`, return `None`.
"""
if "." in key:
return _get_value_for_keys(obj, key.split("."), default)
else:
return _get_value_for_key(obj, key, default) | python | def _get_value(obj, key, default=missing):
"""Slightly-modified version of marshmallow.utils.get_value.
If a dot-delimited ``key`` is passed and any attribute in the
path is `None`, return `None`.
"""
if "." in key:
return _get_value_for_keys(obj, key.split("."), default)
else:
return _get_value_for_key(obj, key, default) | [
"def",
"_get_value",
"(",
"obj",
",",
"key",
",",
"default",
"=",
"missing",
")",
":",
"if",
"\".\"",
"in",
"key",
":",
"return",
"_get_value_for_keys",
"(",
"obj",
",",
"key",
".",
"split",
"(",
"\".\"",
")",
",",
"default",
")",
"else",
":",
"retur... | Slightly-modified version of marshmallow.utils.get_value.
If a dot-delimited ``key`` is passed and any attribute in the
path is `None`, return `None`. | [
"Slightly",
"-",
"modified",
"version",
"of",
"marshmallow",
".",
"utils",
".",
"get_value",
".",
"If",
"a",
"dot",
"-",
"delimited",
"key",
"is",
"passed",
"and",
"any",
"attribute",
"in",
"the",
"path",
"is",
"None",
"return",
"None",
"."
] | 8483fa55cab47f0d0ed23e3fa876b22a1d8e7873 | https://github.com/marshmallow-code/flask-marshmallow/blob/8483fa55cab47f0d0ed23e3fa876b22a1d8e7873/src/flask_marshmallow/fields.py#L33-L41 | train | 202,308 |
marshmallow-code/flask-marshmallow | src/flask_marshmallow/fields.py | _rapply | def _rapply(d, func, *args, **kwargs):
"""Apply a function to all values in a dictionary or list of dictionaries, recursively."""
if isinstance(d, (tuple, list)):
return [_rapply(each, func, *args, **kwargs) for each in d]
if isinstance(d, dict):
return {
key: _rapply(value, func, *args, **kwargs) for key, value in iteritems(d)
}
else:
return func(d, *args, **kwargs) | python | def _rapply(d, func, *args, **kwargs):
"""Apply a function to all values in a dictionary or list of dictionaries, recursively."""
if isinstance(d, (tuple, list)):
return [_rapply(each, func, *args, **kwargs) for each in d]
if isinstance(d, dict):
return {
key: _rapply(value, func, *args, **kwargs) for key, value in iteritems(d)
}
else:
return func(d, *args, **kwargs) | [
"def",
"_rapply",
"(",
"d",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"[",
"_rapply",
"(",
"each",
",",
"func",
",",
"*",
"args",
"... | Apply a function to all values in a dictionary or list of dictionaries, recursively. | [
"Apply",
"a",
"function",
"to",
"all",
"values",
"in",
"a",
"dictionary",
"or",
"list",
"of",
"dictionaries",
"recursively",
"."
] | 8483fa55cab47f0d0ed23e3fa876b22a1d8e7873 | https://github.com/marshmallow-code/flask-marshmallow/blob/8483fa55cab47f0d0ed23e3fa876b22a1d8e7873/src/flask_marshmallow/fields.py#L125-L134 | train | 202,309 |
marshmallow-code/flask-marshmallow | src/flask_marshmallow/fields.py | _url_val | def _url_val(val, key, obj, **kwargs):
"""Function applied by `HyperlinksField` to get the correct value in the
schema.
"""
if isinstance(val, URLFor):
return val.serialize(key, obj, **kwargs)
else:
return val | python | def _url_val(val, key, obj, **kwargs):
"""Function applied by `HyperlinksField` to get the correct value in the
schema.
"""
if isinstance(val, URLFor):
return val.serialize(key, obj, **kwargs)
else:
return val | [
"def",
"_url_val",
"(",
"val",
",",
"key",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"URLFor",
")",
":",
"return",
"val",
".",
"serialize",
"(",
"key",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
"else",
... | Function applied by `HyperlinksField` to get the correct value in the
schema. | [
"Function",
"applied",
"by",
"HyperlinksField",
"to",
"get",
"the",
"correct",
"value",
"in",
"the",
"schema",
"."
] | 8483fa55cab47f0d0ed23e3fa876b22a1d8e7873 | https://github.com/marshmallow-code/flask-marshmallow/blob/8483fa55cab47f0d0ed23e3fa876b22a1d8e7873/src/flask_marshmallow/fields.py#L137-L144 | train | 202,310 |
marshmallow-code/flask-marshmallow | src/flask_marshmallow/__init__.py | _attach_fields | def _attach_fields(obj):
"""Attach all the marshmallow fields classes to ``obj``, including
Flask-Marshmallow's custom fields.
"""
for attr in base_fields.__all__:
if not hasattr(obj, attr):
setattr(obj, attr, getattr(base_fields, attr))
for attr in fields.__all__:
setattr(obj, attr, getattr(fields, attr)) | python | def _attach_fields(obj):
"""Attach all the marshmallow fields classes to ``obj``, including
Flask-Marshmallow's custom fields.
"""
for attr in base_fields.__all__:
if not hasattr(obj, attr):
setattr(obj, attr, getattr(base_fields, attr))
for attr in fields.__all__:
setattr(obj, attr, getattr(fields, attr)) | [
"def",
"_attach_fields",
"(",
"obj",
")",
":",
"for",
"attr",
"in",
"base_fields",
".",
"__all__",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"attr",
")",
":",
"setattr",
"(",
"obj",
",",
"attr",
",",
"getattr",
"(",
"base_fields",
",",
"attr",
")... | Attach all the marshmallow fields classes to ``obj``, including
Flask-Marshmallow's custom fields. | [
"Attach",
"all",
"the",
"marshmallow",
"fields",
"classes",
"to",
"obj",
"including",
"Flask",
"-",
"Marshmallow",
"s",
"custom",
"fields",
"."
] | 8483fa55cab47f0d0ed23e3fa876b22a1d8e7873 | https://github.com/marshmallow-code/flask-marshmallow/blob/8483fa55cab47f0d0ed23e3fa876b22a1d8e7873/src/flask_marshmallow/__init__.py#L40-L48 | train | 202,311 |
marshmallow-code/flask-marshmallow | src/flask_marshmallow/__init__.py | Marshmallow.init_app | def init_app(self, app):
"""Initializes the application with the extension.
:param Flask app: The Flask application object.
"""
app.extensions = getattr(app, "extensions", {})
# If using Flask-SQLAlchemy, attach db.session to ModelSchema
if has_sqla and "sqlalchemy" in app.extensions:
db = app.extensions["sqlalchemy"].db
self.ModelSchema.OPTIONS_CLASS.session = db.session
app.extensions[EXTENSION_NAME] = self | python | def init_app(self, app):
"""Initializes the application with the extension.
:param Flask app: The Flask application object.
"""
app.extensions = getattr(app, "extensions", {})
# If using Flask-SQLAlchemy, attach db.session to ModelSchema
if has_sqla and "sqlalchemy" in app.extensions:
db = app.extensions["sqlalchemy"].db
self.ModelSchema.OPTIONS_CLASS.session = db.session
app.extensions[EXTENSION_NAME] = self | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"extensions",
"=",
"getattr",
"(",
"app",
",",
"\"extensions\"",
",",
"{",
"}",
")",
"# If using Flask-SQLAlchemy, attach db.session to ModelSchema",
"if",
"has_sqla",
"and",
"\"sqlalchemy\"",
"in",... | Initializes the application with the extension.
:param Flask app: The Flask application object. | [
"Initializes",
"the",
"application",
"with",
"the",
"extension",
"."
] | 8483fa55cab47f0d0ed23e3fa876b22a1d8e7873 | https://github.com/marshmallow-code/flask-marshmallow/blob/8483fa55cab47f0d0ed23e3fa876b22a1d8e7873/src/flask_marshmallow/__init__.py#L105-L116 | train | 202,312 |
marshmallow-code/flask-marshmallow | src/flask_marshmallow/schema.py | Schema.jsonify | def jsonify(self, obj, many=sentinel, *args, **kwargs):
"""Return a JSON response containing the serialized data.
:param obj: Object to serialize.
:param bool many: Whether `obj` should be serialized as an instance
or as a collection. If unset, defaults to the value of the
`many` attribute on this Schema.
:param kwargs: Additional keyword arguments passed to `flask.jsonify`.
.. versionchanged:: 0.6.0
Takes the same arguments as `marshmallow.Schema.dump`. Additional
keyword arguments are passed to `flask.jsonify`.
.. versionchanged:: 0.6.3
The `many` argument for this method defaults to the value of
the `many` attribute on the Schema. Previously, the `many`
argument of this method defaulted to False, regardless of the
value of `Schema.many`.
"""
if many is sentinel:
many = self.many
if _MARSHMALLOW_VERSION_INFO[0] >= 3:
data = self.dump(obj, many=many)
else:
data = self.dump(obj, many=many).data
return flask.jsonify(data, *args, **kwargs) | python | def jsonify(self, obj, many=sentinel, *args, **kwargs):
"""Return a JSON response containing the serialized data.
:param obj: Object to serialize.
:param bool many: Whether `obj` should be serialized as an instance
or as a collection. If unset, defaults to the value of the
`many` attribute on this Schema.
:param kwargs: Additional keyword arguments passed to `flask.jsonify`.
.. versionchanged:: 0.6.0
Takes the same arguments as `marshmallow.Schema.dump`. Additional
keyword arguments are passed to `flask.jsonify`.
.. versionchanged:: 0.6.3
The `many` argument for this method defaults to the value of
the `many` attribute on the Schema. Previously, the `many`
argument of this method defaulted to False, regardless of the
value of `Schema.many`.
"""
if many is sentinel:
many = self.many
if _MARSHMALLOW_VERSION_INFO[0] >= 3:
data = self.dump(obj, many=many)
else:
data = self.dump(obj, many=many).data
return flask.jsonify(data, *args, **kwargs) | [
"def",
"jsonify",
"(",
"self",
",",
"obj",
",",
"many",
"=",
"sentinel",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"many",
"is",
"sentinel",
":",
"many",
"=",
"self",
".",
"many",
"if",
"_MARSHMALLOW_VERSION_INFO",
"[",
"0",
"]",
"... | Return a JSON response containing the serialized data.
:param obj: Object to serialize.
:param bool many: Whether `obj` should be serialized as an instance
or as a collection. If unset, defaults to the value of the
`many` attribute on this Schema.
:param kwargs: Additional keyword arguments passed to `flask.jsonify`.
.. versionchanged:: 0.6.0
Takes the same arguments as `marshmallow.Schema.dump`. Additional
keyword arguments are passed to `flask.jsonify`.
.. versionchanged:: 0.6.3
The `many` argument for this method defaults to the value of
the `many` attribute on the Schema. Previously, the `many`
argument of this method defaulted to False, regardless of the
value of `Schema.many`. | [
"Return",
"a",
"JSON",
"response",
"containing",
"the",
"serialized",
"data",
"."
] | 8483fa55cab47f0d0ed23e3fa876b22a1d8e7873 | https://github.com/marshmallow-code/flask-marshmallow/blob/8483fa55cab47f0d0ed23e3fa876b22a1d8e7873/src/flask_marshmallow/schema.py#L16-L42 | train | 202,313 |
nschloe/asciiplotlib | asciiplotlib/table.py | _hjoin_multiline | def _hjoin_multiline(join_char, strings):
"""Horizontal join of multiline strings
"""
cstrings = [string.split("\n") for string in strings]
max_num_lines = max(len(item) for item in cstrings)
pp = []
for k in range(max_num_lines):
p = [cstring[k] for cstring in cstrings]
pp.append(join_char + join_char.join(p) + join_char)
return "\n".join([p.rstrip() for p in pp]) | python | def _hjoin_multiline(join_char, strings):
"""Horizontal join of multiline strings
"""
cstrings = [string.split("\n") for string in strings]
max_num_lines = max(len(item) for item in cstrings)
pp = []
for k in range(max_num_lines):
p = [cstring[k] for cstring in cstrings]
pp.append(join_char + join_char.join(p) + join_char)
return "\n".join([p.rstrip() for p in pp]) | [
"def",
"_hjoin_multiline",
"(",
"join_char",
",",
"strings",
")",
":",
"cstrings",
"=",
"[",
"string",
".",
"split",
"(",
"\"\\n\"",
")",
"for",
"string",
"in",
"strings",
"]",
"max_num_lines",
"=",
"max",
"(",
"len",
"(",
"item",
")",
"for",
"item",
"... | Horizontal join of multiline strings | [
"Horizontal",
"join",
"of",
"multiline",
"strings"
] | 11f4d2584b9b832dc06eb78bab9267f98cb3fdb0 | https://github.com/nschloe/asciiplotlib/blob/11f4d2584b9b832dc06eb78bab9267f98cb3fdb0/asciiplotlib/table.py#L163-L173 | train | 202,314 |
zeth/inputs | inputs.py | chunks | def chunks(raw):
"""Yield successive EVENT_SIZE sized chunks from raw."""
for i in range(0, len(raw), EVENT_SIZE):
yield struct.unpack(EVENT_FORMAT, raw[i:i+EVENT_SIZE]) | python | def chunks(raw):
"""Yield successive EVENT_SIZE sized chunks from raw."""
for i in range(0, len(raw), EVENT_SIZE):
yield struct.unpack(EVENT_FORMAT, raw[i:i+EVENT_SIZE]) | [
"def",
"chunks",
"(",
"raw",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"raw",
")",
",",
"EVENT_SIZE",
")",
":",
"yield",
"struct",
".",
"unpack",
"(",
"EVENT_FORMAT",
",",
"raw",
"[",
"i",
":",
"i",
"+",
"EVENT_SIZE",
"]",
... | Yield successive EVENT_SIZE sized chunks from raw. | [
"Yield",
"successive",
"EVENT_SIZE",
"sized",
"chunks",
"from",
"raw",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L99-L102 | train | 202,315 |
zeth/inputs | inputs.py | convert_timeval | def convert_timeval(seconds_since_epoch):
"""Convert time into C style timeval."""
frac, whole = math.modf(seconds_since_epoch)
microseconds = math.floor(frac * 1000000)
seconds = math.floor(whole)
return seconds, microseconds | python | def convert_timeval(seconds_since_epoch):
"""Convert time into C style timeval."""
frac, whole = math.modf(seconds_since_epoch)
microseconds = math.floor(frac * 1000000)
seconds = math.floor(whole)
return seconds, microseconds | [
"def",
"convert_timeval",
"(",
"seconds_since_epoch",
")",
":",
"frac",
",",
"whole",
"=",
"math",
".",
"modf",
"(",
"seconds_since_epoch",
")",
"microseconds",
"=",
"math",
".",
"floor",
"(",
"frac",
"*",
"1000000",
")",
"seconds",
"=",
"math",
".",
"floo... | Convert time into C style timeval. | [
"Convert",
"time",
"into",
"C",
"style",
"timeval",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L115-L120 | train | 202,316 |
zeth/inputs | inputs.py | quartz_mouse_process | def quartz_mouse_process(pipe):
"""Single subprocess for reading mouse events on Mac using newer Quartz."""
# Quartz only on the mac, so don't warn about Quartz
# pylint: disable=import-error
import Quartz
# pylint: disable=no-member
class QuartzMouseListener(QuartzMouseBaseListener):
"""Loosely emulate Evdev mouse behaviour on the Macs.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Constants below listed at:
https://developer.apple.com/documentation/coregraphics/
cgeventtype?language=objc#topics
"""
# Keep Mac Names to make it easy to find the documentation
# pylint: disable=invalid-name
NSMachPort = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionDefault,
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventMouseMoved) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventScrollWheel) |
Quartz.CGEventMaskBit(Quartz.kCGEventTabletPointer) |
Quartz.CGEventMaskBit(Quartz.kCGEventTabletProximity) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDragged),
self.handle_input,
None)
CFRunLoopSourceRef = Quartz.CFMachPortCreateRunLoopSource(
None,
NSMachPort,
0)
CFRunLoopRef = Quartz.CFRunLoopGetCurrent()
Quartz.CFRunLoopAddSource(
CFRunLoopRef,
CFRunLoopSourceRef,
Quartz.kCFRunLoopDefaultMode)
Quartz.CGEventTapEnable(
NSMachPort,
True)
def listen(self):
"""Listen for quartz events."""
while self.active:
Quartz.CFRunLoopRunInMode(
Quartz.kCFRunLoopDefaultMode, 5, False)
def uninstall_handle_input(self):
self.active = False
def _get_mouse_button_number(self, event):
"""Get the mouse button number from an event."""
return Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventButtonNumber)
def _get_click_state(self, event):
"""The click state from an event."""
return Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventClickState)
def _get_scroll(self, event):
"""The scroll values from an event."""
scroll_y = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGScrollWheelEventDeltaAxis1)
scroll_x = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGScrollWheelEventDeltaAxis2)
return scroll_x, scroll_y
def _get_absolute(self, event):
"""Get abolute cursor location."""
return Quartz.CGEventGetLocation(event)
def _get_relative(self, event):
"""Get the relative mouse movement."""
delta_x = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventDeltaX)
delta_y = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventDeltaY)
return delta_x, delta_y
mouse = QuartzMouseListener(pipe)
mouse.listen() | python | def quartz_mouse_process(pipe):
"""Single subprocess for reading mouse events on Mac using newer Quartz."""
# Quartz only on the mac, so don't warn about Quartz
# pylint: disable=import-error
import Quartz
# pylint: disable=no-member
class QuartzMouseListener(QuartzMouseBaseListener):
"""Loosely emulate Evdev mouse behaviour on the Macs.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Constants below listed at:
https://developer.apple.com/documentation/coregraphics/
cgeventtype?language=objc#topics
"""
# Keep Mac Names to make it easy to find the documentation
# pylint: disable=invalid-name
NSMachPort = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionDefault,
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventMouseMoved) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventScrollWheel) |
Quartz.CGEventMaskBit(Quartz.kCGEventTabletPointer) |
Quartz.CGEventMaskBit(Quartz.kCGEventTabletProximity) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDragged),
self.handle_input,
None)
CFRunLoopSourceRef = Quartz.CFMachPortCreateRunLoopSource(
None,
NSMachPort,
0)
CFRunLoopRef = Quartz.CFRunLoopGetCurrent()
Quartz.CFRunLoopAddSource(
CFRunLoopRef,
CFRunLoopSourceRef,
Quartz.kCFRunLoopDefaultMode)
Quartz.CGEventTapEnable(
NSMachPort,
True)
def listen(self):
"""Listen for quartz events."""
while self.active:
Quartz.CFRunLoopRunInMode(
Quartz.kCFRunLoopDefaultMode, 5, False)
def uninstall_handle_input(self):
self.active = False
def _get_mouse_button_number(self, event):
"""Get the mouse button number from an event."""
return Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventButtonNumber)
def _get_click_state(self, event):
"""The click state from an event."""
return Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventClickState)
def _get_scroll(self, event):
"""The scroll values from an event."""
scroll_y = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGScrollWheelEventDeltaAxis1)
scroll_x = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGScrollWheelEventDeltaAxis2)
return scroll_x, scroll_y
def _get_absolute(self, event):
"""Get abolute cursor location."""
return Quartz.CGEventGetLocation(event)
def _get_relative(self, event):
"""Get the relative mouse movement."""
delta_x = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventDeltaX)
delta_y = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventDeltaY)
return delta_x, delta_y
mouse = QuartzMouseListener(pipe)
mouse.listen() | [
"def",
"quartz_mouse_process",
"(",
"pipe",
")",
":",
"# Quartz only on the mac, so don't warn about Quartz",
"# pylint: disable=import-error",
"import",
"Quartz",
"# pylint: disable=no-member",
"class",
"QuartzMouseListener",
"(",
"QuartzMouseBaseListener",
")",
":",
"\"\"\"Loosel... | Single subprocess for reading mouse events on Mac using newer Quartz. | [
"Single",
"subprocess",
"for",
"reading",
"mouse",
"events",
"on",
"Mac",
"using",
"newer",
"Quartz",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1964-L2056 | train | 202,317 |
zeth/inputs | inputs.py | appkit_mouse_process | def appkit_mouse_process(pipe):
"""Single subprocess for reading mouse events on Mac using older AppKit."""
# pylint: disable=import-error,too-many-locals
# Note Objective C does not support a Unix style fork.
# So these imports have to be inside the child subprocess since
# otherwise the child process cannot use them.
# pylint: disable=no-member, no-name-in-module
from Foundation import NSObject
from AppKit import NSApplication, NSApp
from Cocoa import (NSEvent, NSLeftMouseDownMask,
NSLeftMouseUpMask, NSRightMouseDownMask,
NSRightMouseUpMask, NSMouseMovedMask,
NSLeftMouseDraggedMask,
NSRightMouseDraggedMask, NSMouseEnteredMask,
NSMouseExitedMask, NSScrollWheelMask,
NSOtherMouseDownMask, NSOtherMouseUpMask)
from PyObjCTools import AppHelper
import objc
class MacMouseSetup(NSObject):
"""Setup the handler."""
@objc.python_method
def init_with_handler(self, handler):
"""
Init method that receives the write end of the pipe.
"""
# ALWAYS call the super's designated initializer.
# Also, make sure to re-bind "self" just in case it
# returns something else!
# pylint: disable=self-cls-assignment
self = super(MacMouseSetup, self).init()
self.handler = handler
# Unlike Python's __init__, initializers MUST return self,
# because they are allowed to return any object!
return self
# pylint: disable=invalid-name, unused-argument
def applicationDidFinishLaunching_(self, notification):
"""Bind the listen method as the handler for mouse events."""
mask = (NSLeftMouseDownMask | NSLeftMouseUpMask |
NSRightMouseDownMask | NSRightMouseUpMask |
NSMouseMovedMask | NSLeftMouseDraggedMask |
NSRightMouseDraggedMask | NSScrollWheelMask |
NSMouseEnteredMask | NSMouseExitedMask |
NSOtherMouseDownMask | NSOtherMouseUpMask)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
mask, self.handler)
class MacMouseListener(AppKitMouseBaseListener):
"""Loosely emulate Evdev mouse behaviour on the Macs.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Install the hook."""
self.app = NSApplication.sharedApplication()
# pylint: disable=no-member
delegate = MacMouseSetup.alloc().init_with_handler(
self.handle_input)
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
def __del__(self):
"""Stop the listener on deletion."""
AppHelper.stopEventLoop()
# pylint: disable=unused-variable
mouse = MacMouseListener(pipe, events=[]) | python | def appkit_mouse_process(pipe):
"""Single subprocess for reading mouse events on Mac using older AppKit."""
# pylint: disable=import-error,too-many-locals
# Note Objective C does not support a Unix style fork.
# So these imports have to be inside the child subprocess since
# otherwise the child process cannot use them.
# pylint: disable=no-member, no-name-in-module
from Foundation import NSObject
from AppKit import NSApplication, NSApp
from Cocoa import (NSEvent, NSLeftMouseDownMask,
NSLeftMouseUpMask, NSRightMouseDownMask,
NSRightMouseUpMask, NSMouseMovedMask,
NSLeftMouseDraggedMask,
NSRightMouseDraggedMask, NSMouseEnteredMask,
NSMouseExitedMask, NSScrollWheelMask,
NSOtherMouseDownMask, NSOtherMouseUpMask)
from PyObjCTools import AppHelper
import objc
class MacMouseSetup(NSObject):
"""Setup the handler."""
@objc.python_method
def init_with_handler(self, handler):
"""
Init method that receives the write end of the pipe.
"""
# ALWAYS call the super's designated initializer.
# Also, make sure to re-bind "self" just in case it
# returns something else!
# pylint: disable=self-cls-assignment
self = super(MacMouseSetup, self).init()
self.handler = handler
# Unlike Python's __init__, initializers MUST return self,
# because they are allowed to return any object!
return self
# pylint: disable=invalid-name, unused-argument
def applicationDidFinishLaunching_(self, notification):
"""Bind the listen method as the handler for mouse events."""
mask = (NSLeftMouseDownMask | NSLeftMouseUpMask |
NSRightMouseDownMask | NSRightMouseUpMask |
NSMouseMovedMask | NSLeftMouseDraggedMask |
NSRightMouseDraggedMask | NSScrollWheelMask |
NSMouseEnteredMask | NSMouseExitedMask |
NSOtherMouseDownMask | NSOtherMouseUpMask)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
mask, self.handler)
class MacMouseListener(AppKitMouseBaseListener):
"""Loosely emulate Evdev mouse behaviour on the Macs.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Install the hook."""
self.app = NSApplication.sharedApplication()
# pylint: disable=no-member
delegate = MacMouseSetup.alloc().init_with_handler(
self.handle_input)
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
def __del__(self):
"""Stop the listener on deletion."""
AppHelper.stopEventLoop()
# pylint: disable=unused-variable
mouse = MacMouseListener(pipe, events=[]) | [
"def",
"appkit_mouse_process",
"(",
"pipe",
")",
":",
"# pylint: disable=import-error,too-many-locals",
"# Note Objective C does not support a Unix style fork.",
"# So these imports have to be inside the child subprocess since",
"# otherwise the child process cannot use them.",
"# pylint: disabl... | Single subprocess for reading mouse events on Mac using older AppKit. | [
"Single",
"subprocess",
"for",
"reading",
"mouse",
"events",
"on",
"Mac",
"using",
"older",
"AppKit",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2169-L2238 | train | 202,318 |
zeth/inputs | inputs.py | mac_keyboard_process | def mac_keyboard_process(pipe):
"""Single subprocesses for reading keyboard on Mac."""
# pylint: disable=import-error,too-many-locals
# Note Objective C does not support a Unix style fork.
# So these imports have to be inside the child subprocess since
# otherwise the child process cannot use them.
# pylint: disable=no-member, no-name-in-module
from AppKit import NSApplication, NSApp
from Foundation import NSObject
from Cocoa import (NSEvent, NSKeyDownMask, NSKeyUpMask,
NSFlagsChangedMask)
from PyObjCTools import AppHelper
import objc
class MacKeyboardSetup(NSObject):
"""Setup the handler."""
@objc.python_method
def init_with_handler(self, handler):
"""
Init method that receives the write end of the pipe.
"""
# ALWAYS call the super's designated initializer.
# Also, make sure to re-bind "self" just in case it
# returns something else!
# pylint: disable=self-cls-assignment
self = super(MacKeyboardSetup, self).init()
self.handler = handler
# Unlike Python's __init__, initializers MUST return self,
# because they are allowed to return any object!
return self
# pylint: disable=invalid-name, unused-argument
def applicationDidFinishLaunching_(self, notification):
"""Bind the handler to listen to keyboard events."""
mask = NSKeyDownMask | NSKeyUpMask | NSFlagsChangedMask
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
mask, self.handler)
class MacKeyboardListener(AppKitKeyboardListener):
"""Loosely emulate Evdev keyboard behaviour on the Mac.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Install the hook."""
self.app = NSApplication.sharedApplication()
# pylint: disable=no-member
delegate = MacKeyboardSetup.alloc().init_with_handler(
self.handle_input)
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
def __del__(self):
"""Stop the listener on deletion."""
AppHelper.stopEventLoop()
# pylint: disable=unused-variable
keyboard = MacKeyboardListener(pipe) | python | def mac_keyboard_process(pipe):
"""Single subprocesses for reading keyboard on Mac."""
# pylint: disable=import-error,too-many-locals
# Note Objective C does not support a Unix style fork.
# So these imports have to be inside the child subprocess since
# otherwise the child process cannot use them.
# pylint: disable=no-member, no-name-in-module
from AppKit import NSApplication, NSApp
from Foundation import NSObject
from Cocoa import (NSEvent, NSKeyDownMask, NSKeyUpMask,
NSFlagsChangedMask)
from PyObjCTools import AppHelper
import objc
class MacKeyboardSetup(NSObject):
"""Setup the handler."""
@objc.python_method
def init_with_handler(self, handler):
"""
Init method that receives the write end of the pipe.
"""
# ALWAYS call the super's designated initializer.
# Also, make sure to re-bind "self" just in case it
# returns something else!
# pylint: disable=self-cls-assignment
self = super(MacKeyboardSetup, self).init()
self.handler = handler
# Unlike Python's __init__, initializers MUST return self,
# because they are allowed to return any object!
return self
# pylint: disable=invalid-name, unused-argument
def applicationDidFinishLaunching_(self, notification):
"""Bind the handler to listen to keyboard events."""
mask = NSKeyDownMask | NSKeyUpMask | NSFlagsChangedMask
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
mask, self.handler)
class MacKeyboardListener(AppKitKeyboardListener):
"""Loosely emulate Evdev keyboard behaviour on the Mac.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Install the hook."""
self.app = NSApplication.sharedApplication()
# pylint: disable=no-member
delegate = MacKeyboardSetup.alloc().init_with_handler(
self.handle_input)
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
def __del__(self):
"""Stop the listener on deletion."""
AppHelper.stopEventLoop()
# pylint: disable=unused-variable
keyboard = MacKeyboardListener(pipe) | [
"def",
"mac_keyboard_process",
"(",
"pipe",
")",
":",
"# pylint: disable=import-error,too-many-locals",
"# Note Objective C does not support a Unix style fork.",
"# So these imports have to be inside the child subprocess since",
"# otherwise the child process cannot use them.",
"# pylint: disabl... | Single subprocesses for reading keyboard on Mac. | [
"Single",
"subprocesses",
"for",
"reading",
"keyboard",
"on",
"Mac",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2303-L2364 | train | 202,319 |
zeth/inputs | inputs.py | delay_and_stop | def delay_and_stop(duration, dll, device_number):
"""Stop vibration aka force feedback aka rumble on
Windows after duration miliseconds."""
xinput = getattr(ctypes.windll, dll)
time.sleep(duration/1000)
xinput_set_state = xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
vibration = XinputVibration(0, 0)
xinput_set_state(device_number, ctypes.byref(vibration)) | python | def delay_and_stop(duration, dll, device_number):
"""Stop vibration aka force feedback aka rumble on
Windows after duration miliseconds."""
xinput = getattr(ctypes.windll, dll)
time.sleep(duration/1000)
xinput_set_state = xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
vibration = XinputVibration(0, 0)
xinput_set_state(device_number, ctypes.byref(vibration)) | [
"def",
"delay_and_stop",
"(",
"duration",
",",
"dll",
",",
"device_number",
")",
":",
"xinput",
"=",
"getattr",
"(",
"ctypes",
".",
"windll",
",",
"dll",
")",
"time",
".",
"sleep",
"(",
"duration",
"/",
"1000",
")",
"xinput_set_state",
"=",
"xinput",
"."... | Stop vibration aka force feedback aka rumble on
Windows after duration miliseconds. | [
"Stop",
"vibration",
"aka",
"force",
"feedback",
"aka",
"rumble",
"on",
"Windows",
"after",
"duration",
"miliseconds",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2627-L2637 | train | 202,320 |
zeth/inputs | inputs.py | BaseListener.create_event_object | def create_event_object(self,
event_type,
code,
value,
timeval=None):
"""Create an evdev style structure."""
if not timeval:
self.update_timeval()
timeval = self.timeval
try:
event_code = self.type_codes[event_type]
except KeyError:
raise UnknownEventType(
"We don't know what kind of event a %s is." % event_type)
event = struct.pack(EVENT_FORMAT,
timeval[0],
timeval[1],
event_code,
code,
value)
return event | python | def create_event_object(self,
event_type,
code,
value,
timeval=None):
"""Create an evdev style structure."""
if not timeval:
self.update_timeval()
timeval = self.timeval
try:
event_code = self.type_codes[event_type]
except KeyError:
raise UnknownEventType(
"We don't know what kind of event a %s is." % event_type)
event = struct.pack(EVENT_FORMAT,
timeval[0],
timeval[1],
event_code,
code,
value)
return event | [
"def",
"create_event_object",
"(",
"self",
",",
"event_type",
",",
"code",
",",
"value",
",",
"timeval",
"=",
"None",
")",
":",
"if",
"not",
"timeval",
":",
"self",
".",
"update_timeval",
"(",
")",
"timeval",
"=",
"self",
".",
"timeval",
"try",
":",
"e... | Create an evdev style structure. | [
"Create",
"an",
"evdev",
"style",
"structure",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1498-L1519 | train | 202,321 |
zeth/inputs | inputs.py | BaseListener.emulate_wheel | def emulate_wheel(self, data, direction, timeval):
"""Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scroll
wheels found on the vast majority of mice. It also works on
the analogue ball on the top of the Apple mouse.
What do the analogue scroll wheels found on 200 quid high end
gaming mice do? If the lowest unit is 120 then we are okay. If
they report changes of less than 120 units Windows, then this
might be an unacceptable loss of precision. Needless to say, I
don't have such a mouse to test one way or the other.
"""
if direction == 'x':
code = 0x06
elif direction == 'z':
# Not enitely sure if this exists
code = 0x07
else:
code = 0x08
if WIN:
data = data // 120
return self.create_event_object(
"Relative",
code,
data,
timeval) | python | def emulate_wheel(self, data, direction, timeval):
"""Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scroll
wheels found on the vast majority of mice. It also works on
the analogue ball on the top of the Apple mouse.
What do the analogue scroll wheels found on 200 quid high end
gaming mice do? If the lowest unit is 120 then we are okay. If
they report changes of less than 120 units Windows, then this
might be an unacceptable loss of precision. Needless to say, I
don't have such a mouse to test one way or the other.
"""
if direction == 'x':
code = 0x06
elif direction == 'z':
# Not enitely sure if this exists
code = 0x07
else:
code = 0x08
if WIN:
data = data // 120
return self.create_event_object(
"Relative",
code,
data,
timeval) | [
"def",
"emulate_wheel",
"(",
"self",
",",
"data",
",",
"direction",
",",
"timeval",
")",
":",
"if",
"direction",
"==",
"'x'",
":",
"code",
"=",
"0x06",
"elif",
"direction",
"==",
"'z'",
":",
"# Not enitely sure if this exists",
"code",
"=",
"0x07",
"else",
... | Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scroll
wheels found on the vast majority of mice. It also works on
the analogue ball on the top of the Apple mouse.
What do the analogue scroll wheels found on 200 quid high end
gaming mice do? If the lowest unit is 120 then we are okay. If
they report changes of less than 120 units Windows, then this
might be an unacceptable loss of precision. Needless to say, I
don't have such a mouse to test one way or the other. | [
"Emulate",
"rel",
"values",
"for",
"the",
"mouse",
"wheel",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1525-L1556 | train | 202,322 |
zeth/inputs | inputs.py | BaseListener.emulate_rel | def emulate_rel(self, key_code, value, timeval):
"""Emulate the relative changes of the mouse cursor."""
return self.create_event_object(
"Relative",
key_code,
value,
timeval) | python | def emulate_rel(self, key_code, value, timeval):
"""Emulate the relative changes of the mouse cursor."""
return self.create_event_object(
"Relative",
key_code,
value,
timeval) | [
"def",
"emulate_rel",
"(",
"self",
",",
"key_code",
",",
"value",
",",
"timeval",
")",
":",
"return",
"self",
".",
"create_event_object",
"(",
"\"Relative\"",
",",
"key_code",
",",
"value",
",",
"timeval",
")"
] | Emulate the relative changes of the mouse cursor. | [
"Emulate",
"the",
"relative",
"changes",
"of",
"the",
"mouse",
"cursor",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1558-L1564 | train | 202,323 |
zeth/inputs | inputs.py | BaseListener.emulate_press | def emulate_press(self, key_code, scan_code, value, timeval):
"""Emulate a button press.
Currently supports 5 buttons.
The Microsoft documentation does not define what happens with
a mouse with more than five buttons, and I don't have such a
mouse.
From reading the Linux sources, I guess evdev can support up
to 255 buttons.
Therefore, I guess we could support more buttons quite easily,
if we had any useful hardware.
"""
scan_event = self.create_event_object(
"Misc",
0x04,
scan_code,
timeval)
key_event = self.create_event_object(
"Key",
key_code,
value,
timeval)
return scan_event, key_event | python | def emulate_press(self, key_code, scan_code, value, timeval):
"""Emulate a button press.
Currently supports 5 buttons.
The Microsoft documentation does not define what happens with
a mouse with more than five buttons, and I don't have such a
mouse.
From reading the Linux sources, I guess evdev can support up
to 255 buttons.
Therefore, I guess we could support more buttons quite easily,
if we had any useful hardware.
"""
scan_event = self.create_event_object(
"Misc",
0x04,
scan_code,
timeval)
key_event = self.create_event_object(
"Key",
key_code,
value,
timeval)
return scan_event, key_event | [
"def",
"emulate_press",
"(",
"self",
",",
"key_code",
",",
"scan_code",
",",
"value",
",",
"timeval",
")",
":",
"scan_event",
"=",
"self",
".",
"create_event_object",
"(",
"\"Misc\"",
",",
"0x04",
",",
"scan_code",
",",
"timeval",
")",
"key_event",
"=",
"s... | Emulate a button press.
Currently supports 5 buttons.
The Microsoft documentation does not define what happens with
a mouse with more than five buttons, and I don't have such a
mouse.
From reading the Linux sources, I guess evdev can support up
to 255 buttons.
Therefore, I guess we could support more buttons quite easily,
if we had any useful hardware. | [
"Emulate",
"a",
"button",
"press",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1566-L1591 | train | 202,324 |
zeth/inputs | inputs.py | BaseListener.emulate_abs | def emulate_abs(self, x_val, y_val, timeval):
"""Emulate the absolute co-ordinates of the mouse cursor."""
x_event = self.create_event_object(
"Absolute",
0x00,
x_val,
timeval)
y_event = self.create_event_object(
"Absolute",
0x01,
y_val,
timeval)
return x_event, y_event | python | def emulate_abs(self, x_val, y_val, timeval):
"""Emulate the absolute co-ordinates of the mouse cursor."""
x_event = self.create_event_object(
"Absolute",
0x00,
x_val,
timeval)
y_event = self.create_event_object(
"Absolute",
0x01,
y_val,
timeval)
return x_event, y_event | [
"def",
"emulate_abs",
"(",
"self",
",",
"x_val",
",",
"y_val",
",",
"timeval",
")",
":",
"x_event",
"=",
"self",
".",
"create_event_object",
"(",
"\"Absolute\"",
",",
"0x00",
",",
"x_val",
",",
"timeval",
")",
"y_event",
"=",
"self",
".",
"create_event_obj... | Emulate the absolute co-ordinates of the mouse cursor. | [
"Emulate",
"the",
"absolute",
"co",
"-",
"ordinates",
"of",
"the",
"mouse",
"cursor",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1610-L1622 | train | 202,325 |
zeth/inputs | inputs.py | WindowsKeyboardListener.listen | def listen():
"""Listen for keyboard input."""
msg = MSG()
ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0) | python | def listen():
"""Listen for keyboard input."""
msg = MSG()
ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0) | [
"def",
"listen",
"(",
")",
":",
"msg",
"=",
"MSG",
"(",
")",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetMessageA",
"(",
"ctypes",
".",
"byref",
"(",
"msg",
")",
",",
"0",
",",
"0",
",",
"0",
")"
] | Listen for keyboard input. | [
"Listen",
"for",
"keyboard",
"input",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1636-L1639 | train | 202,326 |
zeth/inputs | inputs.py | WindowsKeyboardListener.get_fptr | def get_fptr(self):
"""Get the function pointer."""
cmpfunc = ctypes.CFUNCTYPE(ctypes.c_int,
WPARAM,
LPARAM,
ctypes.POINTER(KBDLLHookStruct))
return cmpfunc(self.handle_input) | python | def get_fptr(self):
"""Get the function pointer."""
cmpfunc = ctypes.CFUNCTYPE(ctypes.c_int,
WPARAM,
LPARAM,
ctypes.POINTER(KBDLLHookStruct))
return cmpfunc(self.handle_input) | [
"def",
"get_fptr",
"(",
"self",
")",
":",
"cmpfunc",
"=",
"ctypes",
".",
"CFUNCTYPE",
"(",
"ctypes",
".",
"c_int",
",",
"WPARAM",
",",
"LPARAM",
",",
"ctypes",
".",
"POINTER",
"(",
"KBDLLHookStruct",
")",
")",
"return",
"cmpfunc",
"(",
"self",
".",
"ha... | Get the function pointer. | [
"Get",
"the",
"function",
"pointer",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1641-L1647 | train | 202,327 |
zeth/inputs | inputs.py | WindowsKeyboardListener.install_handle_input | def install_handle_input(self):
"""Install the hook."""
self.pointer = self.get_fptr()
self.hooked = ctypes.windll.user32.SetWindowsHookExA(
13,
self.pointer,
ctypes.windll.kernel32.GetModuleHandleW(None),
0
)
if not self.hooked:
return False
return True | python | def install_handle_input(self):
"""Install the hook."""
self.pointer = self.get_fptr()
self.hooked = ctypes.windll.user32.SetWindowsHookExA(
13,
self.pointer,
ctypes.windll.kernel32.GetModuleHandleW(None),
0
)
if not self.hooked:
return False
return True | [
"def",
"install_handle_input",
"(",
"self",
")",
":",
"self",
".",
"pointer",
"=",
"self",
".",
"get_fptr",
"(",
")",
"self",
".",
"hooked",
"=",
"ctypes",
".",
"windll",
".",
"user32",
".",
"SetWindowsHookExA",
"(",
"13",
",",
"self",
".",
"pointer",
... | Install the hook. | [
"Install",
"the",
"hook",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1649-L1661 | train | 202,328 |
zeth/inputs | inputs.py | WindowsKeyboardListener.uninstall_handle_input | def uninstall_handle_input(self):
"""Remove the hook."""
if self.hooked is None:
return
ctypes.windll.user32.UnhookWindowsHookEx(self.hooked)
self.hooked = None | python | def uninstall_handle_input(self):
"""Remove the hook."""
if self.hooked is None:
return
ctypes.windll.user32.UnhookWindowsHookEx(self.hooked)
self.hooked = None | [
"def",
"uninstall_handle_input",
"(",
"self",
")",
":",
"if",
"self",
".",
"hooked",
"is",
"None",
":",
"return",
"ctypes",
".",
"windll",
".",
"user32",
".",
"UnhookWindowsHookEx",
"(",
"self",
".",
"hooked",
")",
"self",
".",
"hooked",
"=",
"None"
] | Remove the hook. | [
"Remove",
"the",
"hook",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1663-L1668 | train | 202,329 |
zeth/inputs | inputs.py | WindowsMouseListener.emulate_mouse | def emulate_mouse(self, key_code, x_val, y_val, data):
"""Emulate the ev codes using the data Windows has given us.
Note that by default in Windows, to recognise a double click,
you just notice two clicks in a row within a reasonablely
short time period.
However, if the application developer sets the application
window's class style to CS_DBLCLKS, the operating system will
notice the four button events (down, up, down, up), intercept
them and then send a single key code instead.
There are no such special double click codes on other
platforms, so not obvious what to do with them. It might be
best to just convert them back to four events.
Currently we do nothing.
((0x0203, 'WM_LBUTTONDBLCLK'),
(0x0206, 'WM_RBUTTONDBLCLK'),
(0x0209, 'WM_MBUTTONDBLCLK'),
(0x020D, 'WM_XBUTTONDBLCLK'))
"""
# Once again ignore Windows' relative time (since system
# startup) and use the absolute time (since epoch i.e. 1st Jan
# 1970).
self.update_timeval()
events = []
if key_code == 0x0200:
# We have a mouse move alone.
# So just pass through to below
pass
elif key_code == 0x020A:
# We have a vertical mouse wheel turn
events.append(self.emulate_wheel(data, 'y', self.timeval))
elif key_code == 0x020E:
# We have a horizontal mouse wheel turn
# https://msdn.microsoft.com/en-us/library/windows/desktop/
# ms645614%28v=vs.85%29.aspx
events.append(self.emulate_wheel(data, 'x', self.timeval))
else:
# We have a button press.
# Distinguish the second extra button
if key_code == 0x020B and data == 2:
key_code = 0x020B2
elif key_code == 0x020C and data == 2:
key_code = 0x020C2
# Get the mouse codes
code, value, scan_code = self.mouse_codes[key_code]
# Add in the press events
scan_event, key_event = self.emulate_press(
code, scan_code, value, self.timeval)
events.append(scan_event)
events.append(key_event)
# Add in the absolute position of the mouse cursor
x_event, y_event = self.emulate_abs(x_val, y_val, self.timeval)
events.append(x_event)
events.append(y_event)
# End with a sync marker
events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(events) | python | def emulate_mouse(self, key_code, x_val, y_val, data):
"""Emulate the ev codes using the data Windows has given us.
Note that by default in Windows, to recognise a double click,
you just notice two clicks in a row within a reasonablely
short time period.
However, if the application developer sets the application
window's class style to CS_DBLCLKS, the operating system will
notice the four button events (down, up, down, up), intercept
them and then send a single key code instead.
There are no such special double click codes on other
platforms, so not obvious what to do with them. It might be
best to just convert them back to four events.
Currently we do nothing.
((0x0203, 'WM_LBUTTONDBLCLK'),
(0x0206, 'WM_RBUTTONDBLCLK'),
(0x0209, 'WM_MBUTTONDBLCLK'),
(0x020D, 'WM_XBUTTONDBLCLK'))
"""
# Once again ignore Windows' relative time (since system
# startup) and use the absolute time (since epoch i.e. 1st Jan
# 1970).
self.update_timeval()
events = []
if key_code == 0x0200:
# We have a mouse move alone.
# So just pass through to below
pass
elif key_code == 0x020A:
# We have a vertical mouse wheel turn
events.append(self.emulate_wheel(data, 'y', self.timeval))
elif key_code == 0x020E:
# We have a horizontal mouse wheel turn
# https://msdn.microsoft.com/en-us/library/windows/desktop/
# ms645614%28v=vs.85%29.aspx
events.append(self.emulate_wheel(data, 'x', self.timeval))
else:
# We have a button press.
# Distinguish the second extra button
if key_code == 0x020B and data == 2:
key_code = 0x020B2
elif key_code == 0x020C and data == 2:
key_code = 0x020C2
# Get the mouse codes
code, value, scan_code = self.mouse_codes[key_code]
# Add in the press events
scan_event, key_event = self.emulate_press(
code, scan_code, value, self.timeval)
events.append(scan_event)
events.append(key_event)
# Add in the absolute position of the mouse cursor
x_event, y_event = self.emulate_abs(x_val, y_val, self.timeval)
events.append(x_event)
events.append(y_event)
# End with a sync marker
events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(events) | [
"def",
"emulate_mouse",
"(",
"self",
",",
"key_code",
",",
"x_val",
",",
"y_val",
",",
"data",
")",
":",
"# Once again ignore Windows' relative time (since system",
"# startup) and use the absolute time (since epoch i.e. 1st Jan",
"# 1970).",
"self",
".",
"update_timeval",
"(... | Emulate the ev codes using the data Windows has given us.
Note that by default in Windows, to recognise a double click,
you just notice two clicks in a row within a reasonablely
short time period.
However, if the application developer sets the application
window's class style to CS_DBLCLKS, the operating system will
notice the four button events (down, up, down, up), intercept
them and then send a single key code instead.
There are no such special double click codes on other
platforms, so not obvious what to do with them. It might be
best to just convert them back to four events.
Currently we do nothing.
((0x0203, 'WM_LBUTTONDBLCLK'),
(0x0206, 'WM_RBUTTONDBLCLK'),
(0x0209, 'WM_MBUTTONDBLCLK'),
(0x020D, 'WM_XBUTTONDBLCLK')) | [
"Emulate",
"the",
"ev",
"codes",
"using",
"the",
"data",
"Windows",
"has",
"given",
"us",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1769-L1838 | train | 202,330 |
zeth/inputs | inputs.py | QuartzMouseBaseListener.handle_button | def handle_button(self, event, event_type):
"""Convert the button information from quartz into evdev format."""
# 0 for left
# 1 for right
# 2 for middle/center
# 3 for side
mouse_button_number = self._get_mouse_button_number(event)
# Identify buttons 3,4,5
if event_type in (25, 26):
event_type = event_type + (mouse_button_number * 0.1)
# Add buttons to events
event_type_string, event_code, value, scan = self.codes[event_type]
if event_type_string == "Key":
scan_event, key_event = self.emulate_press(
event_code, scan, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event)
# doubleclick/n-click of button
click_state = self._get_click_state(event)
repeat = self.emulate_repeat(click_state, self.timeval)
self.events.append(repeat) | python | def handle_button(self, event, event_type):
"""Convert the button information from quartz into evdev format."""
# 0 for left
# 1 for right
# 2 for middle/center
# 3 for side
mouse_button_number = self._get_mouse_button_number(event)
# Identify buttons 3,4,5
if event_type in (25, 26):
event_type = event_type + (mouse_button_number * 0.1)
# Add buttons to events
event_type_string, event_code, value, scan = self.codes[event_type]
if event_type_string == "Key":
scan_event, key_event = self.emulate_press(
event_code, scan, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event)
# doubleclick/n-click of button
click_state = self._get_click_state(event)
repeat = self.emulate_repeat(click_state, self.timeval)
self.events.append(repeat) | [
"def",
"handle_button",
"(",
"self",
",",
"event",
",",
"event_type",
")",
":",
"# 0 for left",
"# 1 for right",
"# 2 for middle/center",
"# 3 for side",
"mouse_button_number",
"=",
"self",
".",
"_get_mouse_button_number",
"(",
"event",
")",
"# Identify buttons 3,4,5",
... | Convert the button information from quartz into evdev format. | [
"Convert",
"the",
"button",
"information",
"from",
"quartz",
"into",
"evdev",
"format",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1876-L1900 | train | 202,331 |
zeth/inputs | inputs.py | QuartzMouseBaseListener.handle_relative | def handle_relative(self, event):
"""Relative mouse movement."""
delta_x, delta_y = self._get_relative(event)
if delta_x:
self.events.append(
self.emulate_rel(0x00,
delta_x,
self.timeval))
if delta_y:
self.events.append(
self.emulate_rel(0x01,
delta_y,
self.timeval)) | python | def handle_relative(self, event):
"""Relative mouse movement."""
delta_x, delta_y = self._get_relative(event)
if delta_x:
self.events.append(
self.emulate_rel(0x00,
delta_x,
self.timeval))
if delta_y:
self.events.append(
self.emulate_rel(0x01,
delta_y,
self.timeval)) | [
"def",
"handle_relative",
"(",
"self",
",",
"event",
")",
":",
"delta_x",
",",
"delta_y",
"=",
"self",
".",
"_get_relative",
"(",
"event",
")",
"if",
"delta_x",
":",
"self",
".",
"events",
".",
"append",
"(",
"self",
".",
"emulate_rel",
"(",
"0x00",
",... | Relative mouse movement. | [
"Relative",
"mouse",
"movement",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1925-L1937 | train | 202,332 |
zeth/inputs | inputs.py | QuartzMouseBaseListener.handle_input | def handle_input(self, proxy, event_type, event, refcon):
"""Handle an input event."""
self.update_timeval()
self.events = []
if event_type in (1, 2, 3, 4, 25, 26, 27):
self.handle_button(event, event_type)
if event_type == 22:
self.handle_scrollwheel(event)
# Add in the absolute position of the mouse cursor
self.handle_absolute(event)
# Add in the relative position of the mouse cursor
self.handle_relative(event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) | python | def handle_input(self, proxy, event_type, event, refcon):
"""Handle an input event."""
self.update_timeval()
self.events = []
if event_type in (1, 2, 3, 4, 25, 26, 27):
self.handle_button(event, event_type)
if event_type == 22:
self.handle_scrollwheel(event)
# Add in the absolute position of the mouse cursor
self.handle_absolute(event)
# Add in the relative position of the mouse cursor
self.handle_relative(event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) | [
"def",
"handle_input",
"(",
"self",
",",
"proxy",
",",
"event_type",
",",
"event",
",",
"refcon",
")",
":",
"self",
".",
"update_timeval",
"(",
")",
"self",
".",
"events",
"=",
"[",
"]",
"if",
"event_type",
"in",
"(",
"1",
",",
"2",
",",
"3",
",",
... | Handle an input event. | [
"Handle",
"an",
"input",
"event",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1940-L1961 | train | 202,333 |
zeth/inputs | inputs.py | AppKitMouseBaseListener._get_deltas | def _get_deltas(event):
"""Get the changes from the appkit event."""
delta_x = round(event.deltaX())
delta_y = round(event.deltaY())
delta_z = round(event.deltaZ())
return delta_x, delta_y, delta_z | python | def _get_deltas(event):
"""Get the changes from the appkit event."""
delta_x = round(event.deltaX())
delta_y = round(event.deltaY())
delta_z = round(event.deltaZ())
return delta_x, delta_y, delta_z | [
"def",
"_get_deltas",
"(",
"event",
")",
":",
"delta_x",
"=",
"round",
"(",
"event",
".",
"deltaX",
"(",
")",
")",
"delta_y",
"=",
"round",
"(",
"event",
".",
"deltaY",
"(",
")",
")",
"delta_z",
"=",
"round",
"(",
"event",
".",
"deltaZ",
"(",
")",
... | Get the changes from the appkit event. | [
"Get",
"the",
"changes",
"from",
"the",
"appkit",
"event",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2081-L2086 | train | 202,334 |
zeth/inputs | inputs.py | AppKitMouseBaseListener.handle_button | def handle_button(self, event, event_type):
"""Handle mouse click."""
mouse_button_number = self._get_mouse_button_number(event)
# Identify buttons 3,4,5
if event_type in (25, 26):
event_type = event_type + (mouse_button_number * 0.1)
# Add buttons to events
event_type_name, event_code, value, scan = self.codes[event_type]
if event_type_name == "Key":
scan_event, key_event = self.emulate_press(
event_code, scan, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event) | python | def handle_button(self, event, event_type):
"""Handle mouse click."""
mouse_button_number = self._get_mouse_button_number(event)
# Identify buttons 3,4,5
if event_type in (25, 26):
event_type = event_type + (mouse_button_number * 0.1)
# Add buttons to events
event_type_name, event_code, value, scan = self.codes[event_type]
if event_type_name == "Key":
scan_event, key_event = self.emulate_press(
event_code, scan, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event) | [
"def",
"handle_button",
"(",
"self",
",",
"event",
",",
"event_type",
")",
":",
"mouse_button_number",
"=",
"self",
".",
"_get_mouse_button_number",
"(",
"event",
")",
"# Identify buttons 3,4,5",
"if",
"event_type",
"in",
"(",
"25",
",",
"26",
")",
":",
"event... | Handle mouse click. | [
"Handle",
"mouse",
"click",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2088-L2100 | train | 202,335 |
zeth/inputs | inputs.py | AppKitMouseBaseListener.handle_scrollwheel | def handle_scrollwheel(self, event):
"""Make endev from appkit scroll wheel event."""
delta_x, delta_y, delta_z = self._get_deltas(event)
if delta_x:
self.events.append(
self.emulate_wheel(delta_x, 'x', self.timeval))
if delta_y:
self.events.append(
self.emulate_wheel(delta_y, 'y', self.timeval))
if delta_z:
self.events.append(
self.emulate_wheel(delta_z, 'z', self.timeval)) | python | def handle_scrollwheel(self, event):
"""Make endev from appkit scroll wheel event."""
delta_x, delta_y, delta_z = self._get_deltas(event)
if delta_x:
self.events.append(
self.emulate_wheel(delta_x, 'x', self.timeval))
if delta_y:
self.events.append(
self.emulate_wheel(delta_y, 'y', self.timeval))
if delta_z:
self.events.append(
self.emulate_wheel(delta_z, 'z', self.timeval)) | [
"def",
"handle_scrollwheel",
"(",
"self",
",",
"event",
")",
":",
"delta_x",
",",
"delta_y",
",",
"delta_z",
"=",
"self",
".",
"_get_deltas",
"(",
"event",
")",
"if",
"delta_x",
":",
"self",
".",
"events",
".",
"append",
"(",
"self",
".",
"emulate_wheel"... | Make endev from appkit scroll wheel event. | [
"Make",
"endev",
"from",
"appkit",
"scroll",
"wheel",
"event",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2111-L2122 | train | 202,336 |
zeth/inputs | inputs.py | AppKitMouseBaseListener.handle_relative | def handle_relative(self, event):
"""Get the position of the mouse on the screen."""
delta_x, delta_y, delta_z = self._get_deltas(event)
if delta_x:
self.events.append(
self.emulate_rel(0x00,
delta_x,
self.timeval))
if delta_y:
self.events.append(
self.emulate_rel(0x01,
delta_y,
self.timeval))
if delta_z:
self.events.append(
self.emulate_rel(0x02,
delta_z,
self.timeval)) | python | def handle_relative(self, event):
"""Get the position of the mouse on the screen."""
delta_x, delta_y, delta_z = self._get_deltas(event)
if delta_x:
self.events.append(
self.emulate_rel(0x00,
delta_x,
self.timeval))
if delta_y:
self.events.append(
self.emulate_rel(0x01,
delta_y,
self.timeval))
if delta_z:
self.events.append(
self.emulate_rel(0x02,
delta_z,
self.timeval)) | [
"def",
"handle_relative",
"(",
"self",
",",
"event",
")",
":",
"delta_x",
",",
"delta_y",
",",
"delta_z",
"=",
"self",
".",
"_get_deltas",
"(",
"event",
")",
"if",
"delta_x",
":",
"self",
".",
"events",
".",
"append",
"(",
"self",
".",
"emulate_rel",
"... | Get the position of the mouse on the screen. | [
"Get",
"the",
"position",
"of",
"the",
"mouse",
"on",
"the",
"screen",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2124-L2141 | train | 202,337 |
zeth/inputs | inputs.py | AppKitMouseBaseListener.handle_input | def handle_input(self, event):
"""Process the mouse event."""
self.update_timeval()
self.events = []
code = self._get_event_type(event)
# Deal with buttons
self.handle_button(event, code)
# Mouse wheel
if code == 22:
self.handle_scrollwheel(event)
# Other relative mouse movements
else:
self.handle_relative(event)
# Add in the absolute position of the mouse cursor
self.handle_absolute(event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) | python | def handle_input(self, event):
"""Process the mouse event."""
self.update_timeval()
self.events = []
code = self._get_event_type(event)
# Deal with buttons
self.handle_button(event, code)
# Mouse wheel
if code == 22:
self.handle_scrollwheel(event)
# Other relative mouse movements
else:
self.handle_relative(event)
# Add in the absolute position of the mouse cursor
self.handle_absolute(event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) | [
"def",
"handle_input",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"update_timeval",
"(",
")",
"self",
".",
"events",
"=",
"[",
"]",
"code",
"=",
"self",
".",
"_get_event_type",
"(",
"event",
")",
"# Deal with buttons",
"self",
".",
"handle_button",
... | Process the mouse event. | [
"Process",
"the",
"mouse",
"event",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2143-L2166 | train | 202,338 |
zeth/inputs | inputs.py | AppKitKeyboardListener._get_key_value | def _get_key_value(self, event, event_type):
"""Get the key value."""
if event_type == 10:
value = 1
elif event_type == 11:
value = 0
elif event_type == 12:
value = self._get_flag_value(event)
else:
value = -1
return value | python | def _get_key_value(self, event, event_type):
"""Get the key value."""
if event_type == 10:
value = 1
elif event_type == 11:
value = 0
elif event_type == 12:
value = self._get_flag_value(event)
else:
value = -1
return value | [
"def",
"_get_key_value",
"(",
"self",
",",
"event",
",",
"event_type",
")",
":",
"if",
"event_type",
"==",
"10",
":",
"value",
"=",
"1",
"elif",
"event_type",
"==",
"11",
":",
"value",
"=",
"0",
"elif",
"event_type",
"==",
"12",
":",
"value",
"=",
"s... | Get the key value. | [
"Get",
"the",
"key",
"value",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2268-L2278 | train | 202,339 |
zeth/inputs | inputs.py | AppKitKeyboardListener.handle_input | def handle_input(self, event):
"""Process they keyboard input."""
self.update_timeval()
self.events = []
code = self._get_event_key_code(event)
if code in self.codes:
new_code = self.codes[code]
else:
new_code = 0
event_type = self._get_event_type(event)
value = self._get_key_value(event, event_type)
scan_event, key_event = self.emulate_press(
new_code, code, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) | python | def handle_input(self, event):
"""Process they keyboard input."""
self.update_timeval()
self.events = []
code = self._get_event_key_code(event)
if code in self.codes:
new_code = self.codes[code]
else:
new_code = 0
event_type = self._get_event_type(event)
value = self._get_key_value(event, event_type)
scan_event, key_event = self.emulate_press(
new_code, code, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) | [
"def",
"handle_input",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"update_timeval",
"(",
")",
"self",
".",
"events",
"=",
"[",
"]",
"code",
"=",
"self",
".",
"_get_event_key_code",
"(",
"event",
")",
"if",
"code",
"in",
"self",
".",
"codes",
"... | Process they keyboard input. | [
"Process",
"they",
"keyboard",
"input",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2280-L2300 | train | 202,340 |
zeth/inputs | inputs.py | InputDevice._get_path_infomation | def _get_path_infomation(self):
"""Get useful infomation from the device path."""
long_identifier = self._device_path.split('/')[4]
protocol, remainder = long_identifier.split('-', 1)
identifier, _, device_type = remainder.rsplit('-', 2)
return (protocol, identifier, device_type) | python | def _get_path_infomation(self):
"""Get useful infomation from the device path."""
long_identifier = self._device_path.split('/')[4]
protocol, remainder = long_identifier.split('-', 1)
identifier, _, device_type = remainder.rsplit('-', 2)
return (protocol, identifier, device_type) | [
"def",
"_get_path_infomation",
"(",
"self",
")",
":",
"long_identifier",
"=",
"self",
".",
"_device_path",
".",
"split",
"(",
"'/'",
")",
"[",
"4",
"]",
"protocol",
",",
"remainder",
"=",
"long_identifier",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"ident... | Get useful infomation from the device path. | [
"Get",
"useful",
"infomation",
"from",
"the",
"device",
"path",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2421-L2426 | train | 202,341 |
zeth/inputs | inputs.py | InputDevice._get_total_read_size | def _get_total_read_size(self):
"""How much event data to process at once."""
if self.read_size:
read_size = EVENT_SIZE * self.read_size
else:
read_size = EVENT_SIZE
return read_size | python | def _get_total_read_size(self):
"""How much event data to process at once."""
if self.read_size:
read_size = EVENT_SIZE * self.read_size
else:
read_size = EVENT_SIZE
return read_size | [
"def",
"_get_total_read_size",
"(",
"self",
")",
":",
"if",
"self",
".",
"read_size",
":",
"read_size",
"=",
"EVENT_SIZE",
"*",
"self",
".",
"read_size",
"else",
":",
"read_size",
"=",
"EVENT_SIZE",
"return",
"read_size"
] | How much event data to process at once. | [
"How",
"much",
"event",
"data",
"to",
"process",
"at",
"once",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2485-L2491 | train | 202,342 |
zeth/inputs | inputs.py | InputDevice._make_event | def _make_event(self, tv_sec, tv_usec, ev_type, code, value):
"""Create a friendly Python object from an evdev style event."""
event_type = self.manager.get_event_type(ev_type)
eventinfo = {
"ev_type": event_type,
"state": value,
"timestamp": tv_sec + (tv_usec / 1000000),
"code": self.manager.get_event_string(event_type, code)
}
return InputEvent(self, eventinfo) | python | def _make_event(self, tv_sec, tv_usec, ev_type, code, value):
"""Create a friendly Python object from an evdev style event."""
event_type = self.manager.get_event_type(ev_type)
eventinfo = {
"ev_type": event_type,
"state": value,
"timestamp": tv_sec + (tv_usec / 1000000),
"code": self.manager.get_event_string(event_type, code)
}
return InputEvent(self, eventinfo) | [
"def",
"_make_event",
"(",
"self",
",",
"tv_sec",
",",
"tv_usec",
",",
"ev_type",
",",
"code",
",",
"value",
")",
":",
"event_type",
"=",
"self",
".",
"manager",
".",
"get_event_type",
"(",
"ev_type",
")",
"eventinfo",
"=",
"{",
"\"ev_type\"",
":",
"even... | Create a friendly Python object from an evdev style event. | [
"Create",
"a",
"friendly",
"Python",
"object",
"from",
"an",
"evdev",
"style",
"event",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2503-L2513 | train | 202,343 |
zeth/inputs | inputs.py | InputDevice._pipe | def _pipe(self):
"""On Windows we use a pipe to emulate a Linux style character
buffer."""
if self._evdev:
return None
if not self.__pipe:
target_function = self._get_target_function()
if not target_function:
return None
self.__pipe, child_conn = Pipe(duplex=False)
self._listener = Process(target=target_function,
args=(child_conn,), daemon=True)
self._listener.start()
return self.__pipe | python | def _pipe(self):
"""On Windows we use a pipe to emulate a Linux style character
buffer."""
if self._evdev:
return None
if not self.__pipe:
target_function = self._get_target_function()
if not target_function:
return None
self.__pipe, child_conn = Pipe(duplex=False)
self._listener = Process(target=target_function,
args=(child_conn,), daemon=True)
self._listener.start()
return self.__pipe | [
"def",
"_pipe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_evdev",
":",
"return",
"None",
"if",
"not",
"self",
".",
"__pipe",
":",
"target_function",
"=",
"self",
".",
"_get_target_function",
"(",
")",
"if",
"not",
"target_function",
":",
"return",
"Non... | On Windows we use a pipe to emulate a Linux style character
buffer. | [
"On",
"Windows",
"we",
"use",
"a",
"pipe",
"to",
"emulate",
"a",
"Linux",
"style",
"character",
"buffer",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2520-L2535 | train | 202,344 |
zeth/inputs | inputs.py | GamePad._number_xpad | def _number_xpad(self):
"""Get the number of the joystick."""
js_path = self._device_path.replace('-event', '')
js_chardev = os.path.realpath(js_path)
try:
number_text = js_chardev.split('js')[1]
except IndexError:
return
try:
number = int(number_text)
except ValueError:
return
self.__device_number = number | python | def _number_xpad(self):
"""Get the number of the joystick."""
js_path = self._device_path.replace('-event', '')
js_chardev = os.path.realpath(js_path)
try:
number_text = js_chardev.split('js')[1]
except IndexError:
return
try:
number = int(number_text)
except ValueError:
return
self.__device_number = number | [
"def",
"_number_xpad",
"(",
"self",
")",
":",
"js_path",
"=",
"self",
".",
"_device_path",
".",
"replace",
"(",
"'-event'",
",",
"''",
")",
"js_chardev",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"js_path",
")",
"try",
":",
"number_text",
"=",
"js_... | Get the number of the joystick. | [
"Get",
"the",
"number",
"of",
"the",
"joystick",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2665-L2677 | train | 202,345 |
zeth/inputs | inputs.py | GamePad.__check_state | def __check_state(self):
"""On Windows, check the state and fill the event character device."""
state = self.__read_device()
if not state:
raise UnpluggedError(
"Gamepad %d is not connected" % self.__device_number)
if state.packet_number != self.__last_state.packet_number:
# state has changed, handle the change
self.__handle_changed_state(state)
self.__last_state = state | python | def __check_state(self):
"""On Windows, check the state and fill the event character device."""
state = self.__read_device()
if not state:
raise UnpluggedError(
"Gamepad %d is not connected" % self.__device_number)
if state.packet_number != self.__last_state.packet_number:
# state has changed, handle the change
self.__handle_changed_state(state)
self.__last_state = state | [
"def",
"__check_state",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"__read_device",
"(",
")",
"if",
"not",
"state",
":",
"raise",
"UnpluggedError",
"(",
"\"Gamepad %d is not connected\"",
"%",
"self",
".",
"__device_number",
")",
"if",
"state",
".",
"... | On Windows, check the state and fill the event character device. | [
"On",
"Windows",
"check",
"the",
"state",
"and",
"fill",
"the",
"event",
"character",
"device",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2691-L2700 | train | 202,346 |
zeth/inputs | inputs.py | GamePad.create_event_object | def create_event_object(self,
event_type,
code,
value,
timeval=None):
"""Create an evdev style object."""
if not timeval:
timeval = self.__get_timeval()
try:
event_code = self.manager.codes['type_codes'][event_type]
except KeyError:
raise UnknownEventType(
"We don't know what kind of event a %s is." % event_type)
event = struct.pack(EVENT_FORMAT,
timeval[0],
timeval[1],
event_code,
code,
value)
return event | python | def create_event_object(self,
event_type,
code,
value,
timeval=None):
"""Create an evdev style object."""
if not timeval:
timeval = self.__get_timeval()
try:
event_code = self.manager.codes['type_codes'][event_type]
except KeyError:
raise UnknownEventType(
"We don't know what kind of event a %s is." % event_type)
event = struct.pack(EVENT_FORMAT,
timeval[0],
timeval[1],
event_code,
code,
value)
return event | [
"def",
"create_event_object",
"(",
"self",
",",
"event_type",
",",
"code",
",",
"value",
",",
"timeval",
"=",
"None",
")",
":",
"if",
"not",
"timeval",
":",
"timeval",
"=",
"self",
".",
"__get_timeval",
"(",
")",
"try",
":",
"event_code",
"=",
"self",
... | Create an evdev style object. | [
"Create",
"an",
"evdev",
"style",
"object",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2707-L2726 | train | 202,347 |
zeth/inputs | inputs.py | GamePad.__write_to_character_device | def __write_to_character_device(self, event_list, timeval=None):
"""Emulate the Linux character device on other platforms such as
Windows."""
# Remember the position of the stream
pos = self._character_device.tell()
# Go to the end of the stream
self._character_device.seek(0, 2)
# Write the new data to the end
for event in event_list:
self._character_device.write(event)
# Add a sync marker
sync = self.create_event_object("Sync", 0, 0, timeval)
self._character_device.write(sync)
# Put the stream back to its original position
self._character_device.seek(pos) | python | def __write_to_character_device(self, event_list, timeval=None):
"""Emulate the Linux character device on other platforms such as
Windows."""
# Remember the position of the stream
pos = self._character_device.tell()
# Go to the end of the stream
self._character_device.seek(0, 2)
# Write the new data to the end
for event in event_list:
self._character_device.write(event)
# Add a sync marker
sync = self.create_event_object("Sync", 0, 0, timeval)
self._character_device.write(sync)
# Put the stream back to its original position
self._character_device.seek(pos) | [
"def",
"__write_to_character_device",
"(",
"self",
",",
"event_list",
",",
"timeval",
"=",
"None",
")",
":",
"# Remember the position of the stream",
"pos",
"=",
"self",
".",
"_character_device",
".",
"tell",
"(",
")",
"# Go to the end of the stream",
"self",
".",
"... | Emulate the Linux character device on other platforms such as
Windows. | [
"Emulate",
"the",
"Linux",
"character",
"device",
"on",
"other",
"platforms",
"such",
"as",
"Windows",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2728-L2742 | train | 202,348 |
zeth/inputs | inputs.py | GamePad.__get_button_events | def __get_button_events(self, state, timeval=None):
"""Get the button events from xinput."""
changed_buttons = self.__detect_button_events(state)
events = self.__emulate_buttons(changed_buttons, timeval)
return events | python | def __get_button_events(self, state, timeval=None):
"""Get the button events from xinput."""
changed_buttons = self.__detect_button_events(state)
events = self.__emulate_buttons(changed_buttons, timeval)
return events | [
"def",
"__get_button_events",
"(",
"self",
",",
"state",
",",
"timeval",
"=",
"None",
")",
":",
"changed_buttons",
"=",
"self",
".",
"__detect_button_events",
"(",
"state",
")",
"events",
"=",
"self",
".",
"__emulate_buttons",
"(",
"changed_buttons",
",",
"tim... | Get the button events from xinput. | [
"Get",
"the",
"button",
"events",
"from",
"xinput",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2785-L2789 | train | 202,349 |
zeth/inputs | inputs.py | GamePad.__get_axis_events | def __get_axis_events(self, state, timeval=None):
"""Get the stick events from xinput."""
axis_changes = self.__detect_axis_events(state)
events = self.__emulate_axis(axis_changes, timeval)
return events | python | def __get_axis_events(self, state, timeval=None):
"""Get the stick events from xinput."""
axis_changes = self.__detect_axis_events(state)
events = self.__emulate_axis(axis_changes, timeval)
return events | [
"def",
"__get_axis_events",
"(",
"self",
",",
"state",
",",
"timeval",
"=",
"None",
")",
":",
"axis_changes",
"=",
"self",
".",
"__detect_axis_events",
"(",
"state",
")",
"events",
"=",
"self",
".",
"__emulate_axis",
"(",
"axis_changes",
",",
"timeval",
")",... | Get the stick events from xinput. | [
"Get",
"the",
"stick",
"events",
"from",
"xinput",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2791-L2795 | train | 202,350 |
zeth/inputs | inputs.py | GamePad.__emulate_axis | def __emulate_axis(self, axis_changes, timeval=None):
"""Make the axis events use the Linux style format."""
events = []
for axis in axis_changes:
code, value = self.__map_axis(axis)
event = self.create_event_object(
"Absolute",
code,
value,
timeval=timeval)
events.append(event)
return events | python | def __emulate_axis(self, axis_changes, timeval=None):
"""Make the axis events use the Linux style format."""
events = []
for axis in axis_changes:
code, value = self.__map_axis(axis)
event = self.create_event_object(
"Absolute",
code,
value,
timeval=timeval)
events.append(event)
return events | [
"def",
"__emulate_axis",
"(",
"self",
",",
"axis_changes",
",",
"timeval",
"=",
"None",
")",
":",
"events",
"=",
"[",
"]",
"for",
"axis",
"in",
"axis_changes",
":",
"code",
",",
"value",
"=",
"self",
".",
"__map_axis",
"(",
"axis",
")",
"event",
"=",
... | Make the axis events use the Linux style format. | [
"Make",
"the",
"axis",
"events",
"use",
"the",
"Linux",
"style",
"format",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2797-L2808 | train | 202,351 |
zeth/inputs | inputs.py | GamePad.__emulate_buttons | def __emulate_buttons(self, changed_buttons, timeval=None):
"""Make the button events use the Linux style format."""
events = []
for button in changed_buttons:
code, value, ev_type = self.__map_button(button)
event = self.create_event_object(
ev_type,
code,
value,
timeval=timeval)
events.append(event)
return events | python | def __emulate_buttons(self, changed_buttons, timeval=None):
"""Make the button events use the Linux style format."""
events = []
for button in changed_buttons:
code, value, ev_type = self.__map_button(button)
event = self.create_event_object(
ev_type,
code,
value,
timeval=timeval)
events.append(event)
return events | [
"def",
"__emulate_buttons",
"(",
"self",
",",
"changed_buttons",
",",
"timeval",
"=",
"None",
")",
":",
"events",
"=",
"[",
"]",
"for",
"button",
"in",
"changed_buttons",
":",
"code",
",",
"value",
",",
"ev_type",
"=",
"self",
".",
"__map_button",
"(",
"... | Make the button events use the Linux style format. | [
"Make",
"the",
"button",
"events",
"use",
"the",
"Linux",
"style",
"format",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2810-L2821 | train | 202,352 |
zeth/inputs | inputs.py | GamePad.__get_bit_values | def __get_bit_values(self, number, size=32):
"""Get bit values as a list for a given number
>>> get_bit_values(1) == [0]*31 + [1]
True
>>> get_bit_values(0xDEADBEEF)
[1L, 1L, 0L, 1L, 1L, 1L, 1L,
0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,
1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L]
You may override the default word size of 32-bits to match your actual
application.
>>> get_bit_values(0x3, 2)
[1L, 1L]
>>> get_bit_values(0x3, 4)
[0L, 0L, 1L, 1L]
"""
res = list(self.__gen_bit_values(number))
res.reverse()
# 0-pad the most significant bit
res = [0] * (size - len(res)) + res
return res | python | def __get_bit_values(self, number, size=32):
"""Get bit values as a list for a given number
>>> get_bit_values(1) == [0]*31 + [1]
True
>>> get_bit_values(0xDEADBEEF)
[1L, 1L, 0L, 1L, 1L, 1L, 1L,
0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,
1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L]
You may override the default word size of 32-bits to match your actual
application.
>>> get_bit_values(0x3, 2)
[1L, 1L]
>>> get_bit_values(0x3, 4)
[0L, 0L, 1L, 1L]
"""
res = list(self.__gen_bit_values(number))
res.reverse()
# 0-pad the most significant bit
res = [0] * (size - len(res)) + res
return res | [
"def",
"__get_bit_values",
"(",
"self",
",",
"number",
",",
"size",
"=",
"32",
")",
":",
"res",
"=",
"list",
"(",
"self",
".",
"__gen_bit_values",
"(",
"number",
")",
")",
"res",
".",
"reverse",
"(",
")",
"# 0-pad the most significant bit",
"res",
"=",
"... | Get bit values as a list for a given number
>>> get_bit_values(1) == [0]*31 + [1]
True
>>> get_bit_values(0xDEADBEEF)
[1L, 1L, 0L, 1L, 1L, 1L, 1L,
0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,
1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L]
You may override the default word size of 32-bits to match your actual
application.
>>> get_bit_values(0x3, 2)
[1L, 1L]
>>> get_bit_values(0x3, 4)
[0L, 0L, 1L, 1L] | [
"Get",
"bit",
"values",
"as",
"a",
"list",
"for",
"a",
"given",
"number"
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2834-L2858 | train | 202,353 |
zeth/inputs | inputs.py | GamePad.__read_device | def __read_device(self):
"""Read the state of the gamepad."""
state = XinputState()
res = self.manager.xinput.XInputGetState(
self.__device_number, ctypes.byref(state))
if res == XINPUT_ERROR_SUCCESS:
return state
if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:
raise RuntimeError(
"Unknown error %d attempting to get state of device %d" % (
res, self.__device_number))
# else (device is not connected)
return None | python | def __read_device(self):
"""Read the state of the gamepad."""
state = XinputState()
res = self.manager.xinput.XInputGetState(
self.__device_number, ctypes.byref(state))
if res == XINPUT_ERROR_SUCCESS:
return state
if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:
raise RuntimeError(
"Unknown error %d attempting to get state of device %d" % (
res, self.__device_number))
# else (device is not connected)
return None | [
"def",
"__read_device",
"(",
"self",
")",
":",
"state",
"=",
"XinputState",
"(",
")",
"res",
"=",
"self",
".",
"manager",
".",
"xinput",
".",
"XInputGetState",
"(",
"self",
".",
"__device_number",
",",
"ctypes",
".",
"byref",
"(",
"state",
")",
")",
"i... | Read the state of the gamepad. | [
"Read",
"the",
"state",
"of",
"the",
"gamepad",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2891-L2903 | train | 202,354 |
zeth/inputs | inputs.py | GamePad._start_vibration_win | def _start_vibration_win(self, left_motor, right_motor):
"""Start the vibration, which will run until stopped."""
xinput_set_state = self.manager.xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
vibration = XinputVibration(
int(left_motor * 65535), int(right_motor * 65535))
xinput_set_state(self.__device_number, ctypes.byref(vibration)) | python | def _start_vibration_win(self, left_motor, right_motor):
"""Start the vibration, which will run until stopped."""
xinput_set_state = self.manager.xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
vibration = XinputVibration(
int(left_motor * 65535), int(right_motor * 65535))
xinput_set_state(self.__device_number, ctypes.byref(vibration)) | [
"def",
"_start_vibration_win",
"(",
"self",
",",
"left_motor",
",",
"right_motor",
")",
":",
"xinput_set_state",
"=",
"self",
".",
"manager",
".",
"xinput",
".",
"XInputSetState",
"xinput_set_state",
".",
"argtypes",
"=",
"[",
"ctypes",
".",
"c_uint",
",",
"ct... | Start the vibration, which will run until stopped. | [
"Start",
"the",
"vibration",
"which",
"will",
"run",
"until",
"stopped",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2925-L2933 | train | 202,355 |
zeth/inputs | inputs.py | GamePad._stop_vibration_win | def _stop_vibration_win(self):
"""Stop the vibration."""
xinput_set_state = self.manager.xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
stop_vibration = ctypes.byref(XinputVibration(0, 0))
xinput_set_state(self.__device_number, stop_vibration) | python | def _stop_vibration_win(self):
"""Stop the vibration."""
xinput_set_state = self.manager.xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
stop_vibration = ctypes.byref(XinputVibration(0, 0))
xinput_set_state(self.__device_number, stop_vibration) | [
"def",
"_stop_vibration_win",
"(",
"self",
")",
":",
"xinput_set_state",
"=",
"self",
".",
"manager",
".",
"xinput",
".",
"XInputSetState",
"xinput_set_state",
".",
"argtypes",
"=",
"[",
"ctypes",
".",
"c_uint",
",",
"ctypes",
".",
"POINTER",
"(",
"XinputVibra... | Stop the vibration. | [
"Stop",
"the",
"vibration",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2935-L2942 | train | 202,356 |
zeth/inputs | inputs.py | GamePad._set_vibration_win | def _set_vibration_win(self, left_motor, right_motor, duration):
"""Control the motors on Windows."""
self._start_vibration_win(left_motor, right_motor)
stop_process = Process(target=delay_and_stop,
args=(duration,
self.manager.xinput_dll,
self.__device_number))
stop_process.start() | python | def _set_vibration_win(self, left_motor, right_motor, duration):
"""Control the motors on Windows."""
self._start_vibration_win(left_motor, right_motor)
stop_process = Process(target=delay_and_stop,
args=(duration,
self.manager.xinput_dll,
self.__device_number))
stop_process.start() | [
"def",
"_set_vibration_win",
"(",
"self",
",",
"left_motor",
",",
"right_motor",
",",
"duration",
")",
":",
"self",
".",
"_start_vibration_win",
"(",
"left_motor",
",",
"right_motor",
")",
"stop_process",
"=",
"Process",
"(",
"target",
"=",
"delay_and_stop",
","... | Control the motors on Windows. | [
"Control",
"the",
"motors",
"on",
"Windows",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2944-L2951 | train | 202,357 |
zeth/inputs | inputs.py | GamePad.__get_vibration_code | def __get_vibration_code(self, left_motor, right_motor, duration):
"""This is some crazy voodoo, if you can simplify it, please do."""
inner_event = struct.pack(
'2h6x2h2x2H28x',
0x50,
-1,
duration,
0,
int(left_motor * 65535),
int(right_motor * 65535))
buf_conts = ioctl(self._write_device, 1076905344, inner_event)
return int(codecs.encode(buf_conts[1:3], 'hex'), 16) | python | def __get_vibration_code(self, left_motor, right_motor, duration):
"""This is some crazy voodoo, if you can simplify it, please do."""
inner_event = struct.pack(
'2h6x2h2x2H28x',
0x50,
-1,
duration,
0,
int(left_motor * 65535),
int(right_motor * 65535))
buf_conts = ioctl(self._write_device, 1076905344, inner_event)
return int(codecs.encode(buf_conts[1:3], 'hex'), 16) | [
"def",
"__get_vibration_code",
"(",
"self",
",",
"left_motor",
",",
"right_motor",
",",
"duration",
")",
":",
"inner_event",
"=",
"struct",
".",
"pack",
"(",
"'2h6x2h2x2H28x'",
",",
"0x50",
",",
"-",
"1",
",",
"duration",
",",
"0",
",",
"int",
"(",
"left... | This is some crazy voodoo, if you can simplify it, please do. | [
"This",
"is",
"some",
"crazy",
"voodoo",
"if",
"you",
"can",
"simplify",
"it",
"please",
"do",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2953-L2964 | train | 202,358 |
zeth/inputs | inputs.py | GamePad._set_vibration_nix | def _set_vibration_nix(self, left_motor, right_motor, duration):
"""Control the motors on Linux.
Duration is in miliseconds."""
code = self.__get_vibration_code(left_motor, right_motor, duration)
secs, msecs = convert_timeval(time.time())
outer_event = struct.pack(EVENT_FORMAT, secs, msecs, 0x15, code, 1)
self._write_device.write(outer_event)
self._write_device.flush() | python | def _set_vibration_nix(self, left_motor, right_motor, duration):
"""Control the motors on Linux.
Duration is in miliseconds."""
code = self.__get_vibration_code(left_motor, right_motor, duration)
secs, msecs = convert_timeval(time.time())
outer_event = struct.pack(EVENT_FORMAT, secs, msecs, 0x15, code, 1)
self._write_device.write(outer_event)
self._write_device.flush() | [
"def",
"_set_vibration_nix",
"(",
"self",
",",
"left_motor",
",",
"right_motor",
",",
"duration",
")",
":",
"code",
"=",
"self",
".",
"__get_vibration_code",
"(",
"left_motor",
",",
"right_motor",
",",
"duration",
")",
"secs",
",",
"msecs",
"=",
"convert_timev... | Control the motors on Linux.
Duration is in miliseconds. | [
"Control",
"the",
"motors",
"on",
"Linux",
".",
"Duration",
"is",
"in",
"miliseconds",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2966-L2973 | train | 202,359 |
zeth/inputs | inputs.py | LED.max_brightness | def max_brightness(self):
"""Get the device's maximum brightness level."""
status_filename = os.path.join(self.path, 'max_brightness')
with open(status_filename) as status_fp:
result = status_fp.read()
status_text = result.strip()
try:
status = int(status_text)
except ValueError:
return status_text
return status | python | def max_brightness(self):
"""Get the device's maximum brightness level."""
status_filename = os.path.join(self.path, 'max_brightness')
with open(status_filename) as status_fp:
result = status_fp.read()
status_text = result.strip()
try:
status = int(status_text)
except ValueError:
return status_text
return status | [
"def",
"max_brightness",
"(",
"self",
")",
":",
"status_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'max_brightness'",
")",
"with",
"open",
"(",
"status_filename",
")",
"as",
"status_fp",
":",
"result",
"=",
"status_fp",... | Get the device's maximum brightness level. | [
"Get",
"the",
"device",
"s",
"maximum",
"brightness",
"level",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3030-L3040 | train | 202,360 |
zeth/inputs | inputs.py | LED._write_device | def _write_device(self):
"""The output device."""
if not self._write_file:
if not NIX:
return None
try:
self._write_file = io.open(
self._character_device_path, 'wb')
except PermissionError:
# Python 3
raise PermissionError(PERMISSIONS_ERROR_TEXT)
except IOError as err:
# Python 2 only
if err.errno == 13: # pragma: no cover
raise PermissionError(PERMISSIONS_ERROR_TEXT)
else:
raise
return self._write_file | python | def _write_device(self):
"""The output device."""
if not self._write_file:
if not NIX:
return None
try:
self._write_file = io.open(
self._character_device_path, 'wb')
except PermissionError:
# Python 3
raise PermissionError(PERMISSIONS_ERROR_TEXT)
except IOError as err:
# Python 2 only
if err.errno == 13: # pragma: no cover
raise PermissionError(PERMISSIONS_ERROR_TEXT)
else:
raise
return self._write_file | [
"def",
"_write_device",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_write_file",
":",
"if",
"not",
"NIX",
":",
"return",
"None",
"try",
":",
"self",
".",
"_write_file",
"=",
"io",
".",
"open",
"(",
"self",
".",
"_character_device_path",
",",
"'w... | The output device. | [
"The",
"output",
"device",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3043-L3061 | train | 202,361 |
zeth/inputs | inputs.py | SystemLED._post_init | def _post_init(self):
"""Set up the device path and type code."""
self._led_type_code = self.manager.get_typecode('LED')
self.device_path = os.path.realpath(os.path.join(self.path, 'device'))
if '::' in self.name:
chardev, code_name = self.name.split('::')
if code_name in self.manager.codes['LED_type_codes']:
self.code = self.manager.codes['LED_type_codes'][code_name]
try:
event_number = chardev.split('input')[1]
except IndexError:
print("Failed with", self.name)
raise
else:
self._character_device_path = '/dev/input/event' + event_number
self._match_device() | python | def _post_init(self):
"""Set up the device path and type code."""
self._led_type_code = self.manager.get_typecode('LED')
self.device_path = os.path.realpath(os.path.join(self.path, 'device'))
if '::' in self.name:
chardev, code_name = self.name.split('::')
if code_name in self.manager.codes['LED_type_codes']:
self.code = self.manager.codes['LED_type_codes'][code_name]
try:
event_number = chardev.split('input')[1]
except IndexError:
print("Failed with", self.name)
raise
else:
self._character_device_path = '/dev/input/event' + event_number
self._match_device() | [
"def",
"_post_init",
"(",
"self",
")",
":",
"self",
".",
"_led_type_code",
"=",
"self",
".",
"manager",
".",
"get_typecode",
"(",
"'LED'",
")",
"self",
".",
"device_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
... | Set up the device path and type code. | [
"Set",
"up",
"the",
"device",
"path",
"and",
"type",
"code",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3084-L3099 | train | 202,362 |
zeth/inputs | inputs.py | SystemLED._match_device | def _match_device(self):
"""If the LED is connected to an input device,
associate the objects."""
for device in self.manager.all_devices:
if (device.get_char_device_path() ==
self._character_device_path):
self.device = device
device.leds.append(self)
break | python | def _match_device(self):
"""If the LED is connected to an input device,
associate the objects."""
for device in self.manager.all_devices:
if (device.get_char_device_path() ==
self._character_device_path):
self.device = device
device.leds.append(self)
break | [
"def",
"_match_device",
"(",
"self",
")",
":",
"for",
"device",
"in",
"self",
".",
"manager",
".",
"all_devices",
":",
"if",
"(",
"device",
".",
"get_char_device_path",
"(",
")",
"==",
"self",
".",
"_character_device_path",
")",
":",
"self",
".",
"device",... | If the LED is connected to an input device,
associate the objects. | [
"If",
"the",
"LED",
"is",
"connected",
"to",
"an",
"input",
"device",
"associate",
"the",
"objects",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3116-L3124 | train | 202,363 |
zeth/inputs | inputs.py | DeviceManager._post_init | def _post_init(self):
"""Call the find devices method for the relevant platform."""
if WIN:
self._find_devices_win()
elif MAC:
self._find_devices_mac()
else:
self._find_devices()
self._update_all_devices()
if NIX:
self._find_leds() | python | def _post_init(self):
"""Call the find devices method for the relevant platform."""
if WIN:
self._find_devices_win()
elif MAC:
self._find_devices_mac()
else:
self._find_devices()
self._update_all_devices()
if NIX:
self._find_leds() | [
"def",
"_post_init",
"(",
"self",
")",
":",
"if",
"WIN",
":",
"self",
".",
"_find_devices_win",
"(",
")",
"elif",
"MAC",
":",
"self",
".",
"_find_devices_mac",
"(",
")",
"else",
":",
"self",
".",
"_find_devices",
"(",
")",
"self",
".",
"_update_all_devic... | Call the find devices method for the relevant platform. | [
"Call",
"the",
"find",
"devices",
"method",
"for",
"the",
"relevant",
"platform",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3190-L3200 | train | 202,364 |
zeth/inputs | inputs.py | DeviceManager._update_all_devices | def _update_all_devices(self):
"""Update the all_devices list."""
self.all_devices = []
self.all_devices.extend(self.keyboards)
self.all_devices.extend(self.mice)
self.all_devices.extend(self.gamepads)
self.all_devices.extend(self.other_devices) | python | def _update_all_devices(self):
"""Update the all_devices list."""
self.all_devices = []
self.all_devices.extend(self.keyboards)
self.all_devices.extend(self.mice)
self.all_devices.extend(self.gamepads)
self.all_devices.extend(self.other_devices) | [
"def",
"_update_all_devices",
"(",
"self",
")",
":",
"self",
".",
"all_devices",
"=",
"[",
"]",
"self",
".",
"all_devices",
".",
"extend",
"(",
"self",
".",
"keyboards",
")",
"self",
".",
"all_devices",
".",
"extend",
"(",
"self",
".",
"mice",
")",
"se... | Update the all_devices list. | [
"Update",
"the",
"all_devices",
"list",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3202-L3208 | train | 202,365 |
zeth/inputs | inputs.py | DeviceManager._parse_device_path | def _parse_device_path(self, device_path, char_path_override=None):
"""Parse each device and add to the approriate list."""
# 1. Make sure that we can parse the device path.
try:
device_type = device_path.rsplit('-', 1)[1]
except IndexError:
warn("The following device path was skipped as it could "
"not be parsed: %s" % device_path, RuntimeWarning)
return
# 2. Make sure each device is only added once.
realpath = os.path.realpath(device_path)
if realpath in self._raw:
return
self._raw.append(realpath)
# 3. All seems good, append the device to the relevant list.
if device_type == 'kbd':
self.keyboards.append(Keyboard(self, device_path,
char_path_override))
elif device_type == 'mouse':
self.mice.append(Mouse(self, device_path,
char_path_override))
elif device_type == 'joystick':
self.gamepads.append(GamePad(self,
device_path,
char_path_override))
else:
self.other_devices.append(OtherDevice(self,
device_path,
char_path_override)) | python | def _parse_device_path(self, device_path, char_path_override=None):
"""Parse each device and add to the approriate list."""
# 1. Make sure that we can parse the device path.
try:
device_type = device_path.rsplit('-', 1)[1]
except IndexError:
warn("The following device path was skipped as it could "
"not be parsed: %s" % device_path, RuntimeWarning)
return
# 2. Make sure each device is only added once.
realpath = os.path.realpath(device_path)
if realpath in self._raw:
return
self._raw.append(realpath)
# 3. All seems good, append the device to the relevant list.
if device_type == 'kbd':
self.keyboards.append(Keyboard(self, device_path,
char_path_override))
elif device_type == 'mouse':
self.mice.append(Mouse(self, device_path,
char_path_override))
elif device_type == 'joystick':
self.gamepads.append(GamePad(self,
device_path,
char_path_override))
else:
self.other_devices.append(OtherDevice(self,
device_path,
char_path_override)) | [
"def",
"_parse_device_path",
"(",
"self",
",",
"device_path",
",",
"char_path_override",
"=",
"None",
")",
":",
"# 1. Make sure that we can parse the device path.",
"try",
":",
"device_type",
"=",
"device_path",
".",
"rsplit",
"(",
"'-'",
",",
"1",
")",
"[",
"1",
... | Parse each device and add to the approriate list. | [
"Parse",
"each",
"device",
"and",
"add",
"to",
"the",
"approriate",
"list",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3210-L3241 | train | 202,366 |
zeth/inputs | inputs.py | DeviceManager._find_xinput | def _find_xinput(self):
"""Find most recent xinput library."""
for dll in XINPUT_DLL_NAMES:
try:
self.xinput = getattr(ctypes.windll, dll)
except OSError:
pass
else:
# We found an xinput driver
self.xinput_dll = dll
break
else:
# We didn't find an xinput library
warn(
"No xinput driver dll found, gamepads not supported.",
RuntimeWarning) | python | def _find_xinput(self):
"""Find most recent xinput library."""
for dll in XINPUT_DLL_NAMES:
try:
self.xinput = getattr(ctypes.windll, dll)
except OSError:
pass
else:
# We found an xinput driver
self.xinput_dll = dll
break
else:
# We didn't find an xinput library
warn(
"No xinput driver dll found, gamepads not supported.",
RuntimeWarning) | [
"def",
"_find_xinput",
"(",
"self",
")",
":",
"for",
"dll",
"in",
"XINPUT_DLL_NAMES",
":",
"try",
":",
"self",
".",
"xinput",
"=",
"getattr",
"(",
"ctypes",
".",
"windll",
",",
"dll",
")",
"except",
"OSError",
":",
"pass",
"else",
":",
"# We found an xin... | Find most recent xinput library. | [
"Find",
"most",
"recent",
"xinput",
"library",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3243-L3258 | train | 202,367 |
zeth/inputs | inputs.py | DeviceManager._find_devices_win | def _find_devices_win(self):
"""Find devices on Windows."""
self._find_xinput()
self._detect_gamepads()
self._count_devices()
if self._raw_device_counts['keyboards'] > 0:
self.keyboards.append(Keyboard(
self,
"/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd"))
if self._raw_device_counts['mice'] > 0:
self.mice.append(Mouse(
self,
"/dev/input/by-id/usb-A_Nice_Mouse_called_Arthur-event-mouse")) | python | def _find_devices_win(self):
"""Find devices on Windows."""
self._find_xinput()
self._detect_gamepads()
self._count_devices()
if self._raw_device_counts['keyboards'] > 0:
self.keyboards.append(Keyboard(
self,
"/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd"))
if self._raw_device_counts['mice'] > 0:
self.mice.append(Mouse(
self,
"/dev/input/by-id/usb-A_Nice_Mouse_called_Arthur-event-mouse")) | [
"def",
"_find_devices_win",
"(",
"self",
")",
":",
"self",
".",
"_find_xinput",
"(",
")",
"self",
".",
"_detect_gamepads",
"(",
")",
"self",
".",
"_count_devices",
"(",
")",
"if",
"self",
".",
"_raw_device_counts",
"[",
"'keyboards'",
"]",
">",
"0",
":",
... | Find devices on Windows. | [
"Find",
"devices",
"on",
"Windows",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3260-L3273 | train | 202,368 |
zeth/inputs | inputs.py | DeviceManager._find_devices_mac | def _find_devices_mac(self):
"""Find devices on Mac."""
self.keyboards.append(Keyboard(self))
self.mice.append(MightyMouse(self))
self.mice.append(Mouse(self)) | python | def _find_devices_mac(self):
"""Find devices on Mac."""
self.keyboards.append(Keyboard(self))
self.mice.append(MightyMouse(self))
self.mice.append(Mouse(self)) | [
"def",
"_find_devices_mac",
"(",
"self",
")",
":",
"self",
".",
"keyboards",
".",
"append",
"(",
"Keyboard",
"(",
"self",
")",
")",
"self",
".",
"mice",
".",
"append",
"(",
"MightyMouse",
"(",
"self",
")",
")",
"self",
".",
"mice",
".",
"append",
"("... | Find devices on Mac. | [
"Find",
"devices",
"on",
"Mac",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3275-L3279 | train | 202,369 |
zeth/inputs | inputs.py | DeviceManager._detect_gamepads | def _detect_gamepads(self):
"""Find gamepads."""
state = XinputState()
# Windows allows up to 4 gamepads.
for device_number in range(4):
res = self.xinput.XInputGetState(
device_number, ctypes.byref(state))
if res == XINPUT_ERROR_SUCCESS:
# We found a gamepad
device_path = (
"/dev/input/by_id/" +
"usb-Microsoft_Corporation_Controller_%s-event-joystick"
% device_number)
self.gamepads.append(GamePad(self, device_path))
continue
if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:
raise RuntimeError(
"Unknown error %d attempting to get state of device %d"
% (res, device_number)) | python | def _detect_gamepads(self):
"""Find gamepads."""
state = XinputState()
# Windows allows up to 4 gamepads.
for device_number in range(4):
res = self.xinput.XInputGetState(
device_number, ctypes.byref(state))
if res == XINPUT_ERROR_SUCCESS:
# We found a gamepad
device_path = (
"/dev/input/by_id/" +
"usb-Microsoft_Corporation_Controller_%s-event-joystick"
% device_number)
self.gamepads.append(GamePad(self, device_path))
continue
if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:
raise RuntimeError(
"Unknown error %d attempting to get state of device %d"
% (res, device_number)) | [
"def",
"_detect_gamepads",
"(",
"self",
")",
":",
"state",
"=",
"XinputState",
"(",
")",
"# Windows allows up to 4 gamepads.",
"for",
"device_number",
"in",
"range",
"(",
"4",
")",
":",
"res",
"=",
"self",
".",
"xinput",
".",
"XInputGetState",
"(",
"device_num... | Find gamepads. | [
"Find",
"gamepads",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3281-L3299 | train | 202,370 |
zeth/inputs | inputs.py | DeviceManager._count_devices | def _count_devices(self):
"""See what Windows' GetRawInputDeviceList wants to tell us.
For now, we are just seeing if there is at least one keyboard
and/or mouse attached.
GetRawInputDeviceList could be used to help distinguish between
different keyboards and mice on the system in the way Linux
can. However, Roma uno die non est condita.
"""
number_of_devices = ctypes.c_uint()
if ctypes.windll.user32.GetRawInputDeviceList(
ctypes.POINTER(ctypes.c_int)(),
ctypes.byref(number_of_devices),
ctypes.sizeof(RawInputDeviceList)) == -1:
warn("Call to GetRawInputDeviceList was unsuccessful."
"We have no idea if a mouse or keyboard is attached.",
RuntimeWarning)
return
devices_found = (RawInputDeviceList * number_of_devices.value)()
if ctypes.windll.user32.GetRawInputDeviceList(
devices_found,
ctypes.byref(number_of_devices),
ctypes.sizeof(RawInputDeviceList)) == -1:
warn("Call to GetRawInputDeviceList was unsuccessful."
"We have no idea if a mouse or keyboard is attached.",
RuntimeWarning)
return
for device in devices_found:
if device.dwType == 0:
self._raw_device_counts['mice'] += 1
elif device.dwType == 1:
self._raw_device_counts['keyboards'] += 1
elif device.dwType == 2:
self._raw_device_counts['otherhid'] += 1
else:
self._raw_device_counts['unknown'] += 1 | python | def _count_devices(self):
"""See what Windows' GetRawInputDeviceList wants to tell us.
For now, we are just seeing if there is at least one keyboard
and/or mouse attached.
GetRawInputDeviceList could be used to help distinguish between
different keyboards and mice on the system in the way Linux
can. However, Roma uno die non est condita.
"""
number_of_devices = ctypes.c_uint()
if ctypes.windll.user32.GetRawInputDeviceList(
ctypes.POINTER(ctypes.c_int)(),
ctypes.byref(number_of_devices),
ctypes.sizeof(RawInputDeviceList)) == -1:
warn("Call to GetRawInputDeviceList was unsuccessful."
"We have no idea if a mouse or keyboard is attached.",
RuntimeWarning)
return
devices_found = (RawInputDeviceList * number_of_devices.value)()
if ctypes.windll.user32.GetRawInputDeviceList(
devices_found,
ctypes.byref(number_of_devices),
ctypes.sizeof(RawInputDeviceList)) == -1:
warn("Call to GetRawInputDeviceList was unsuccessful."
"We have no idea if a mouse or keyboard is attached.",
RuntimeWarning)
return
for device in devices_found:
if device.dwType == 0:
self._raw_device_counts['mice'] += 1
elif device.dwType == 1:
self._raw_device_counts['keyboards'] += 1
elif device.dwType == 2:
self._raw_device_counts['otherhid'] += 1
else:
self._raw_device_counts['unknown'] += 1 | [
"def",
"_count_devices",
"(",
"self",
")",
":",
"number_of_devices",
"=",
"ctypes",
".",
"c_uint",
"(",
")",
"if",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetRawInputDeviceList",
"(",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_int",
")",
"(",
... | See what Windows' GetRawInputDeviceList wants to tell us.
For now, we are just seeing if there is at least one keyboard
and/or mouse attached.
GetRawInputDeviceList could be used to help distinguish between
different keyboards and mice on the system in the way Linux
can. However, Roma uno die non est condita. | [
"See",
"what",
"Windows",
"GetRawInputDeviceList",
"wants",
"to",
"tell",
"us",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3301-L3342 | train | 202,371 |
zeth/inputs | inputs.py | DeviceManager._find_by | def _find_by(self, key):
"""Find devices."""
by_path = glob.glob('/dev/input/by-{key}/*-event-*'.format(key=key))
for device_path in by_path:
self._parse_device_path(device_path) | python | def _find_by(self, key):
"""Find devices."""
by_path = glob.glob('/dev/input/by-{key}/*-event-*'.format(key=key))
for device_path in by_path:
self._parse_device_path(device_path) | [
"def",
"_find_by",
"(",
"self",
",",
"key",
")",
":",
"by_path",
"=",
"glob",
".",
"glob",
"(",
"'/dev/input/by-{key}/*-event-*'",
".",
"format",
"(",
"key",
"=",
"key",
")",
")",
"for",
"device_path",
"in",
"by_path",
":",
"self",
".",
"_parse_device_path... | Find devices. | [
"Find",
"devices",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3350-L3354 | train | 202,372 |
zeth/inputs | inputs.py | DeviceManager._find_special | def _find_special(self):
"""Look for special devices."""
charnames = self._get_char_names()
for eventdir in glob.glob('/sys/class/input/event*'):
char_name = os.path.split(eventdir)[1]
if char_name in charnames:
continue
name_file = os.path.join(eventdir, 'device', 'name')
with open(name_file) as name_file:
device_name = name_file.read().strip()
if device_name in self.codes['specials']:
self._parse_device_path(
self.codes['specials'][device_name],
os.path.join('/dev/input', char_name)) | python | def _find_special(self):
"""Look for special devices."""
charnames = self._get_char_names()
for eventdir in glob.glob('/sys/class/input/event*'):
char_name = os.path.split(eventdir)[1]
if char_name in charnames:
continue
name_file = os.path.join(eventdir, 'device', 'name')
with open(name_file) as name_file:
device_name = name_file.read().strip()
if device_name in self.codes['specials']:
self._parse_device_path(
self.codes['specials'][device_name],
os.path.join('/dev/input', char_name)) | [
"def",
"_find_special",
"(",
"self",
")",
":",
"charnames",
"=",
"self",
".",
"_get_char_names",
"(",
")",
"for",
"eventdir",
"in",
"glob",
".",
"glob",
"(",
"'/sys/class/input/event*'",
")",
":",
"char_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"... | Look for special devices. | [
"Look",
"for",
"special",
"devices",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3375-L3388 | train | 202,373 |
zeth/inputs | inputs.py | DeviceManager.get_event_string | def get_event_string(self, evtype, code):
"""Get the string name of the event."""
if WIN and evtype == 'Key':
# If we can map the code to a common one then do it
try:
code = self.codes['wincodes'][code]
except KeyError:
pass
try:
return self.codes[evtype][code]
except KeyError:
raise UnknownEventCode("We don't know this event.", evtype, code) | python | def get_event_string(self, evtype, code):
"""Get the string name of the event."""
if WIN and evtype == 'Key':
# If we can map the code to a common one then do it
try:
code = self.codes['wincodes'][code]
except KeyError:
pass
try:
return self.codes[evtype][code]
except KeyError:
raise UnknownEventCode("We don't know this event.", evtype, code) | [
"def",
"get_event_string",
"(",
"self",
",",
"evtype",
",",
"code",
")",
":",
"if",
"WIN",
"and",
"evtype",
"==",
"'Key'",
":",
"# If we can map the code to a common one then do it",
"try",
":",
"code",
"=",
"self",
".",
"codes",
"[",
"'wincodes'",
"]",
"[",
... | Get the string name of the event. | [
"Get",
"the",
"string",
"name",
"of",
"the",
"event",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3406-L3417 | train | 202,374 |
zeth/inputs | inputs.py | DeviceManager.detect_microbit | def detect_microbit(self):
"""Detect a microbit."""
try:
gpad = MicroBitPad(self)
except ModuleNotFoundError:
warn(
"The microbit library could not be found in the pythonpath. \n"
"For more information, please visit \n"
"https://inputs.readthedocs.io/en/latest/user/microbit.html",
RuntimeWarning)
else:
self.microbits.append(gpad)
self.gamepads.append(gpad) | python | def detect_microbit(self):
"""Detect a microbit."""
try:
gpad = MicroBitPad(self)
except ModuleNotFoundError:
warn(
"The microbit library could not be found in the pythonpath. \n"
"For more information, please visit \n"
"https://inputs.readthedocs.io/en/latest/user/microbit.html",
RuntimeWarning)
else:
self.microbits.append(gpad)
self.gamepads.append(gpad) | [
"def",
"detect_microbit",
"(",
"self",
")",
":",
"try",
":",
"gpad",
"=",
"MicroBitPad",
"(",
"self",
")",
"except",
"ModuleNotFoundError",
":",
"warn",
"(",
"\"The microbit library could not be found in the pythonpath. \\n\"",
"\"For more information, please visit \\n\"",
... | Detect a microbit. | [
"Detect",
"a",
"microbit",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3423-L3435 | train | 202,375 |
zeth/inputs | inputs.py | MicroBitPad.set_display | def set_display(self, index=None):
"""Show an image on the display."""
# pylint: disable=no-member
if index:
image = self.microbit.Image.STD_IMAGES[index]
else:
image = self.default_image
self.microbit.display.show(image) | python | def set_display(self, index=None):
"""Show an image on the display."""
# pylint: disable=no-member
if index:
image = self.microbit.Image.STD_IMAGES[index]
else:
image = self.default_image
self.microbit.display.show(image) | [
"def",
"set_display",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"# pylint: disable=no-member",
"if",
"index",
":",
"image",
"=",
"self",
".",
"microbit",
".",
"Image",
".",
"STD_IMAGES",
"[",
"index",
"]",
"else",
":",
"image",
"=",
"self",
".",
... | Show an image on the display. | [
"Show",
"an",
"image",
"on",
"the",
"display",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3465-L3472 | train | 202,376 |
zeth/inputs | inputs.py | MicroBitPad._setup_rumble | def _setup_rumble(self):
"""Setup the three animations which simulate a rumble."""
self.left_rumble = self._get_ready_to('99500')
self.right_rumble = self._get_ready_to('00599')
self.double_rumble = self._get_ready_to('99599') | python | def _setup_rumble(self):
"""Setup the three animations which simulate a rumble."""
self.left_rumble = self._get_ready_to('99500')
self.right_rumble = self._get_ready_to('00599')
self.double_rumble = self._get_ready_to('99599') | [
"def",
"_setup_rumble",
"(",
"self",
")",
":",
"self",
".",
"left_rumble",
"=",
"self",
".",
"_get_ready_to",
"(",
"'99500'",
")",
"self",
".",
"right_rumble",
"=",
"self",
".",
"_get_ready_to",
"(",
"'00599'",
")",
"self",
".",
"double_rumble",
"=",
"self... | Setup the three animations which simulate a rumble. | [
"Setup",
"the",
"three",
"animations",
"which",
"simulate",
"a",
"rumble",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3474-L3478 | train | 202,377 |
zeth/inputs | inputs.py | MicroBitPad._get_ready_to | def _get_ready_to(self, rumble):
"""Watch us wreck the mike!
PSYCHE!"""
# pylint: disable=no-member
return [self.microbit.Image(':'.join(
[rumble if char == '1' else '00500'
for char in code])) for code in SPIN_UP_MOTOR] | python | def _get_ready_to(self, rumble):
"""Watch us wreck the mike!
PSYCHE!"""
# pylint: disable=no-member
return [self.microbit.Image(':'.join(
[rumble if char == '1' else '00500'
for char in code])) for code in SPIN_UP_MOTOR] | [
"def",
"_get_ready_to",
"(",
"self",
",",
"rumble",
")",
":",
"# pylint: disable=no-member",
"return",
"[",
"self",
".",
"microbit",
".",
"Image",
"(",
"':'",
".",
"join",
"(",
"[",
"rumble",
"if",
"char",
"==",
"'1'",
"else",
"'00500'",
"for",
"char",
"... | Watch us wreck the mike!
PSYCHE! | [
"Watch",
"us",
"wreck",
"the",
"mike!",
"PSYCHE!"
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3494-L3500 | train | 202,378 |
zeth/inputs | inputs.py | MicroBitPad._full_speed_rumble | def _full_speed_rumble(self, images, duration):
"""Simulate the motors running at full."""
while duration > 0:
self.microbit.display.show(images[0]) # pylint: disable=no-member
time.sleep(0.04)
self.microbit.display.show(images[1]) # pylint: disable=no-member
time.sleep(0.04)
duration -= 0.08 | python | def _full_speed_rumble(self, images, duration):
"""Simulate the motors running at full."""
while duration > 0:
self.microbit.display.show(images[0]) # pylint: disable=no-member
time.sleep(0.04)
self.microbit.display.show(images[1]) # pylint: disable=no-member
time.sleep(0.04)
duration -= 0.08 | [
"def",
"_full_speed_rumble",
"(",
"self",
",",
"images",
",",
"duration",
")",
":",
"while",
"duration",
">",
"0",
":",
"self",
".",
"microbit",
".",
"display",
".",
"show",
"(",
"images",
"[",
"0",
"]",
")",
"# pylint: disable=no-member",
"time",
".",
"... | Simulate the motors running at full. | [
"Simulate",
"the",
"motors",
"running",
"at",
"full",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3502-L3509 | train | 202,379 |
zeth/inputs | inputs.py | MicroBitPad._spin_up | def _spin_up(self, images, duration):
"""Simulate the motors getting warmed up."""
total = 0
# pylint: disable=no-member
for image in images:
self.microbit.display.show(image)
time.sleep(0.05)
total += 0.05
if total >= duration:
return
remaining = duration - total
self._full_speed_rumble(images[-2:], remaining)
self.set_display() | python | def _spin_up(self, images, duration):
"""Simulate the motors getting warmed up."""
total = 0
# pylint: disable=no-member
for image in images:
self.microbit.display.show(image)
time.sleep(0.05)
total += 0.05
if total >= duration:
return
remaining = duration - total
self._full_speed_rumble(images[-2:], remaining)
self.set_display() | [
"def",
"_spin_up",
"(",
"self",
",",
"images",
",",
"duration",
")",
":",
"total",
"=",
"0",
"# pylint: disable=no-member",
"for",
"image",
"in",
"images",
":",
"self",
".",
"microbit",
".",
"display",
".",
"show",
"(",
"image",
")",
"time",
".",
"sleep"... | Simulate the motors getting warmed up. | [
"Simulate",
"the",
"motors",
"getting",
"warmed",
"up",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3511-L3524 | train | 202,380 |
zeth/inputs | inputs.py | MicroBitListener.handle_new_events | def handle_new_events(self, events):
"""Add each new events to the event queue."""
for event in events:
self.events.append(
self.create_event_object(
event[0],
event[1],
int(event[2]))) | python | def handle_new_events(self, events):
"""Add each new events to the event queue."""
for event in events:
self.events.append(
self.create_event_object(
event[0],
event[1],
int(event[2]))) | [
"def",
"handle_new_events",
"(",
"self",
",",
"events",
")",
":",
"for",
"event",
"in",
"events",
":",
"self",
".",
"events",
".",
"append",
"(",
"self",
".",
"create_event_object",
"(",
"event",
"[",
"0",
"]",
",",
"event",
"[",
"1",
"]",
",",
"int"... | Add each new events to the event queue. | [
"Add",
"each",
"new",
"events",
"to",
"the",
"event",
"queue",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3578-L3585 | train | 202,381 |
zeth/inputs | inputs.py | MicroBitListener.handle_abs | def handle_abs(self):
"""Gets the state as the raw abolute numbers."""
# pylint: disable=no-member
x_raw = self.microbit.accelerometer.get_x()
y_raw = self.microbit.accelerometer.get_y()
x_abs = ('Absolute', 0x00, x_raw)
y_abs = ('Absolute', 0x01, y_raw)
return x_abs, y_abs | python | def handle_abs(self):
"""Gets the state as the raw abolute numbers."""
# pylint: disable=no-member
x_raw = self.microbit.accelerometer.get_x()
y_raw = self.microbit.accelerometer.get_y()
x_abs = ('Absolute', 0x00, x_raw)
y_abs = ('Absolute', 0x01, y_raw)
return x_abs, y_abs | [
"def",
"handle_abs",
"(",
"self",
")",
":",
"# pylint: disable=no-member",
"x_raw",
"=",
"self",
".",
"microbit",
".",
"accelerometer",
".",
"get_x",
"(",
")",
"y_raw",
"=",
"self",
".",
"microbit",
".",
"accelerometer",
".",
"get_y",
"(",
")",
"x_abs",
"=... | Gets the state as the raw abolute numbers. | [
"Gets",
"the",
"state",
"as",
"the",
"raw",
"abolute",
"numbers",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3587-L3594 | train | 202,382 |
zeth/inputs | inputs.py | MicroBitListener.handle_dpad | def handle_dpad(self):
"""Gets the state of the virtual dpad."""
# pylint: disable=no-member
x_raw = self.microbit.accelerometer.get_x()
y_raw = self.microbit.accelerometer.get_y()
minus_sens = self.sensitivity * -1
if x_raw < minus_sens:
x_state = ('Absolute', 0x10, -1)
elif x_raw > self.sensitivity:
x_state = ('Absolute', 0x10, 1)
else:
x_state = ('Absolute', 0x10, 0)
if y_raw < minus_sens:
y_state = ('Absolute', 0x11, -1)
elif y_raw > self.sensitivity:
y_state = ('Absolute', 0x11, 1)
else:
y_state = ('Absolute', 0x11, 1)
return x_state, y_state | python | def handle_dpad(self):
"""Gets the state of the virtual dpad."""
# pylint: disable=no-member
x_raw = self.microbit.accelerometer.get_x()
y_raw = self.microbit.accelerometer.get_y()
minus_sens = self.sensitivity * -1
if x_raw < minus_sens:
x_state = ('Absolute', 0x10, -1)
elif x_raw > self.sensitivity:
x_state = ('Absolute', 0x10, 1)
else:
x_state = ('Absolute', 0x10, 0)
if y_raw < minus_sens:
y_state = ('Absolute', 0x11, -1)
elif y_raw > self.sensitivity:
y_state = ('Absolute', 0x11, 1)
else:
y_state = ('Absolute', 0x11, 1)
return x_state, y_state | [
"def",
"handle_dpad",
"(",
"self",
")",
":",
"# pylint: disable=no-member",
"x_raw",
"=",
"self",
".",
"microbit",
".",
"accelerometer",
".",
"get_x",
"(",
")",
"y_raw",
"=",
"self",
".",
"microbit",
".",
"accelerometer",
".",
"get_y",
"(",
")",
"minus_sens"... | Gets the state of the virtual dpad. | [
"Gets",
"the",
"state",
"of",
"the",
"virtual",
"dpad",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3596-L3616 | train | 202,383 |
zeth/inputs | inputs.py | MicroBitListener.check_state | def check_state(self):
"""Tracks differences in the device state."""
if self.dpad:
x_state, y_state = self.handle_dpad()
else:
x_state, y_state = self.handle_abs()
# pylint: disable=no-member
new_state = set((
x_state,
y_state,
('Key', 0x130, int(self.microbit.button_a.is_pressed())),
('Key', 0x131, int(self.microbit.button_b.is_pressed())),
('Key', 0x13a, int(self.microbit.pin0.is_touched())),
('Key', 0x133, int(self.microbit.pin1.is_touched())),
('Key', 0x134, int(self.microbit.pin2.is_touched())),
))
events = new_state - self.state
self.state = new_state
return events | python | def check_state(self):
"""Tracks differences in the device state."""
if self.dpad:
x_state, y_state = self.handle_dpad()
else:
x_state, y_state = self.handle_abs()
# pylint: disable=no-member
new_state = set((
x_state,
y_state,
('Key', 0x130, int(self.microbit.button_a.is_pressed())),
('Key', 0x131, int(self.microbit.button_b.is_pressed())),
('Key', 0x13a, int(self.microbit.pin0.is_touched())),
('Key', 0x133, int(self.microbit.pin1.is_touched())),
('Key', 0x134, int(self.microbit.pin2.is_touched())),
))
events = new_state - self.state
self.state = new_state
return events | [
"def",
"check_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"dpad",
":",
"x_state",
",",
"y_state",
"=",
"self",
".",
"handle_dpad",
"(",
")",
"else",
":",
"x_state",
",",
"y_state",
"=",
"self",
".",
"handle_abs",
"(",
")",
"# pylint: disable=no-mem... | Tracks differences in the device state. | [
"Tracks",
"differences",
"in",
"the",
"device",
"state",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3618-L3637 | train | 202,384 |
zeth/inputs | inputs.py | MicroBitListener.handle_input | def handle_input(self):
"""Sends differences in the device state to the MicroBitPad
as events."""
difference = self.check_state()
if not difference:
return
self.events = []
self.handle_new_events(difference)
self.update_timeval()
self.events.append(self.sync_marker(self.timeval))
self.write_to_pipe(self.events) | python | def handle_input(self):
"""Sends differences in the device state to the MicroBitPad
as events."""
difference = self.check_state()
if not difference:
return
self.events = []
self.handle_new_events(difference)
self.update_timeval()
self.events.append(self.sync_marker(self.timeval))
self.write_to_pipe(self.events) | [
"def",
"handle_input",
"(",
"self",
")",
":",
"difference",
"=",
"self",
".",
"check_state",
"(",
")",
"if",
"not",
"difference",
":",
"return",
"self",
".",
"events",
"=",
"[",
"]",
"self",
".",
"handle_new_events",
"(",
"difference",
")",
"self",
".",
... | Sends differences in the device state to the MicroBitPad
as events. | [
"Sends",
"differences",
"in",
"the",
"device",
"state",
"to",
"the",
"MicroBitPad",
"as",
"events",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3639-L3649 | train | 202,385 |
zeth/inputs | examples/mouse_example.py | main | def main():
"""Just print out some event infomation when the mouse is used."""
while 1:
events = get_mouse()
for event in events:
print(event.ev_type, event.code, event.state) | python | def main():
"""Just print out some event infomation when the mouse is used."""
while 1:
events = get_mouse()
for event in events:
print(event.ev_type, event.code, event.state) | [
"def",
"main",
"(",
")",
":",
"while",
"1",
":",
"events",
"=",
"get_mouse",
"(",
")",
"for",
"event",
"in",
"events",
":",
"print",
"(",
"event",
".",
"ev_type",
",",
"event",
".",
"code",
",",
"event",
".",
"state",
")"
] | Just print out some event infomation when the mouse is used. | [
"Just",
"print",
"out",
"some",
"event",
"infomation",
"when",
"the",
"mouse",
"is",
"used",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/examples/mouse_example.py#L9-L14 | train | 202,386 |
zeth/inputs | examples/keyboard_example.py | main | def main():
"""Just print out some event infomation when keys are pressed."""
while 1:
events = get_key()
if events:
for event in events:
print(event.ev_type, event.code, event.state) | python | def main():
"""Just print out some event infomation when keys are pressed."""
while 1:
events = get_key()
if events:
for event in events:
print(event.ev_type, event.code, event.state) | [
"def",
"main",
"(",
")",
":",
"while",
"1",
":",
"events",
"=",
"get_key",
"(",
")",
"if",
"events",
":",
"for",
"event",
"in",
"events",
":",
"print",
"(",
"event",
".",
"ev_type",
",",
"event",
".",
"code",
",",
"event",
".",
"state",
")"
] | Just print out some event infomation when keys are pressed. | [
"Just",
"print",
"out",
"some",
"event",
"infomation",
"when",
"keys",
"are",
"pressed",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/examples/keyboard_example.py#L8-L14 | train | 202,387 |
zeth/inputs | examples/gamepad_example.py | main | def main():
"""Just print out some event infomation when the gamepad is used."""
while 1:
events = get_gamepad()
for event in events:
print(event.ev_type, event.code, event.state) | python | def main():
"""Just print out some event infomation when the gamepad is used."""
while 1:
events = get_gamepad()
for event in events:
print(event.ev_type, event.code, event.state) | [
"def",
"main",
"(",
")",
":",
"while",
"1",
":",
"events",
"=",
"get_gamepad",
"(",
")",
"for",
"event",
"in",
"events",
":",
"print",
"(",
"event",
".",
"ev_type",
",",
"event",
".",
"code",
",",
"event",
".",
"state",
")"
] | Just print out some event infomation when the gamepad is used. | [
"Just",
"print",
"out",
"some",
"event",
"infomation",
"when",
"the",
"gamepad",
"is",
"used",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/examples/gamepad_example.py#L9-L14 | train | 202,388 |
zeth/inputs | examples/vibrate_example.py | main | def main(gamepad=None):
"""Vibrate the gamepad."""
if not gamepad:
gamepad = inputs.devices.gamepads[0]
# Vibrate left
gamepad.set_vibration(1, 0, 1000)
time.sleep(2)
# Vibrate right
gamepad.set_vibration(0, 1, 1000)
time.sleep(2)
# Vibrate Both
gamepad.set_vibration(1, 1, 2000)
time.sleep(2) | python | def main(gamepad=None):
"""Vibrate the gamepad."""
if not gamepad:
gamepad = inputs.devices.gamepads[0]
# Vibrate left
gamepad.set_vibration(1, 0, 1000)
time.sleep(2)
# Vibrate right
gamepad.set_vibration(0, 1, 1000)
time.sleep(2)
# Vibrate Both
gamepad.set_vibration(1, 1, 2000)
time.sleep(2) | [
"def",
"main",
"(",
"gamepad",
"=",
"None",
")",
":",
"if",
"not",
"gamepad",
":",
"gamepad",
"=",
"inputs",
".",
"devices",
".",
"gamepads",
"[",
"0",
"]",
"# Vibrate left",
"gamepad",
".",
"set_vibration",
"(",
"1",
",",
"0",
",",
"1000",
")",
"tim... | Vibrate the gamepad. | [
"Vibrate",
"the",
"gamepad",
"."
] | a46681dbf77d6ab07834f550e5855c1f50701f99 | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/examples/vibrate_example.py#L9-L25 | train | 202,389 |
23andMe/Yamale | yamale/validators/base.py | Validator.validate | def validate(self, value):
"""
Check if ``value`` is valid.
:returns: [errors] If ``value`` is invalid, otherwise [].
"""
errors = []
# Make sure the type validates first.
valid = self._is_valid(value)
if not valid:
errors.append(self.fail(value))
return errors
# Then validate all the constraints second.
for constraint in self._constraints_inst:
error = constraint.is_valid(value)
if error:
errors.append(error)
return errors | python | def validate(self, value):
"""
Check if ``value`` is valid.
:returns: [errors] If ``value`` is invalid, otherwise [].
"""
errors = []
# Make sure the type validates first.
valid = self._is_valid(value)
if not valid:
errors.append(self.fail(value))
return errors
# Then validate all the constraints second.
for constraint in self._constraints_inst:
error = constraint.is_valid(value)
if error:
errors.append(error)
return errors | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"errors",
"=",
"[",
"]",
"# Make sure the type validates first.",
"valid",
"=",
"self",
".",
"_is_valid",
"(",
"value",
")",
"if",
"not",
"valid",
":",
"errors",
".",
"append",
"(",
"self",
".",
"fa... | Check if ``value`` is valid.
:returns: [errors] If ``value`` is invalid, otherwise []. | [
"Check",
"if",
"value",
"is",
"valid",
"."
] | 0a75b4205624d9bccc52bda03efaf0d58c143c76 | https://github.com/23andMe/Yamale/blob/0a75b4205624d9bccc52bda03efaf0d58c143c76/yamale/validators/base.py#L47-L67 | train | 202,390 |
23andMe/Yamale | yamale/schema/schema.py | Schema._process_schema | def _process_schema(self, schema_dict, validators):
"""
Go through a schema and construct validators.
"""
schema_flat = util.flatten(schema_dict)
for key, expression in schema_flat.items():
try:
schema_flat[key] = syntax.parse(expression, validators)
except SyntaxError as e:
# Tack on some more context and rethrow.
error = str(e) + ' at node \'%s\'' % key
raise SyntaxError(error)
return schema_flat | python | def _process_schema(self, schema_dict, validators):
"""
Go through a schema and construct validators.
"""
schema_flat = util.flatten(schema_dict)
for key, expression in schema_flat.items():
try:
schema_flat[key] = syntax.parse(expression, validators)
except SyntaxError as e:
# Tack on some more context and rethrow.
error = str(e) + ' at node \'%s\'' % key
raise SyntaxError(error)
return schema_flat | [
"def",
"_process_schema",
"(",
"self",
",",
"schema_dict",
",",
"validators",
")",
":",
"schema_flat",
"=",
"util",
".",
"flatten",
"(",
"schema_dict",
")",
"for",
"key",
",",
"expression",
"in",
"schema_flat",
".",
"items",
"(",
")",
":",
"try",
":",
"s... | Go through a schema and construct validators. | [
"Go",
"through",
"a",
"schema",
"and",
"construct",
"validators",
"."
] | 0a75b4205624d9bccc52bda03efaf0d58c143c76 | https://github.com/23andMe/Yamale/blob/0a75b4205624d9bccc52bda03efaf0d58c143c76/yamale/schema/schema.py#L30-L43 | train | 202,391 |
23andMe/Yamale | yamale/schema/schema.py | Schema._validate | def _validate(self, validator, data, key, position=None, includes=None):
"""
Run through a schema and a data structure,
validating along the way.
Ignores fields that are in the data structure, but not in the schema.
Returns an array of errors.
"""
errors = []
if position:
position = '%s.%s' % (position, key)
else:
position = key
try: # Pull value out of data. Data can be a map or a list/sequence
data_item = util.get_value(data, key)
except KeyError: # Oops, that field didn't exist.
if validator.is_optional: # Optional? Who cares.
return errors
# SHUT DOWN EVERTYHING
errors.append('%s: Required field missing' % position)
return errors
return self._validate_item(validator, data_item, position, includes) | python | def _validate(self, validator, data, key, position=None, includes=None):
"""
Run through a schema and a data structure,
validating along the way.
Ignores fields that are in the data structure, but not in the schema.
Returns an array of errors.
"""
errors = []
if position:
position = '%s.%s' % (position, key)
else:
position = key
try: # Pull value out of data. Data can be a map or a list/sequence
data_item = util.get_value(data, key)
except KeyError: # Oops, that field didn't exist.
if validator.is_optional: # Optional? Who cares.
return errors
# SHUT DOWN EVERTYHING
errors.append('%s: Required field missing' % position)
return errors
return self._validate_item(validator, data_item, position, includes) | [
"def",
"_validate",
"(",
"self",
",",
"validator",
",",
"data",
",",
"key",
",",
"position",
"=",
"None",
",",
"includes",
"=",
"None",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"position",
":",
"position",
"=",
"'%s.%s'",
"%",
"(",
"position",
",",
... | Run through a schema and a data structure,
validating along the way.
Ignores fields that are in the data structure, but not in the schema.
Returns an array of errors. | [
"Run",
"through",
"a",
"schema",
"and",
"a",
"data",
"structure",
"validating",
"along",
"the",
"way",
"."
] | 0a75b4205624d9bccc52bda03efaf0d58c143c76 | https://github.com/23andMe/Yamale/blob/0a75b4205624d9bccc52bda03efaf0d58c143c76/yamale/schema/schema.py#L58-L83 | train | 202,392 |
23andMe/Yamale | yamale/schema/schema.py | Schema._validate_item | def _validate_item(self, validator, data_item, position, includes):
"""
Validates a single data item against validator.
Returns an array of errors.
"""
errors = []
# Optional field with optional value? Who cares.
if data_item is None and validator.is_optional and validator.can_be_none:
return errors
errors += self._validate_primitive(validator, data_item, position)
if errors:
return errors
if isinstance(validator, val.Include):
errors += self._validate_include(validator, data_item,
includes, position)
elif isinstance(validator, (val.Map, val.List)):
errors += self._validate_map_list(validator, data_item,
includes, position)
elif isinstance(validator, val.Any):
errors += self._validate_any(validator, data_item,
includes, position)
return errors | python | def _validate_item(self, validator, data_item, position, includes):
"""
Validates a single data item against validator.
Returns an array of errors.
"""
errors = []
# Optional field with optional value? Who cares.
if data_item is None and validator.is_optional and validator.can_be_none:
return errors
errors += self._validate_primitive(validator, data_item, position)
if errors:
return errors
if isinstance(validator, val.Include):
errors += self._validate_include(validator, data_item,
includes, position)
elif isinstance(validator, (val.Map, val.List)):
errors += self._validate_map_list(validator, data_item,
includes, position)
elif isinstance(validator, val.Any):
errors += self._validate_any(validator, data_item,
includes, position)
return errors | [
"def",
"_validate_item",
"(",
"self",
",",
"validator",
",",
"data_item",
",",
"position",
",",
"includes",
")",
":",
"errors",
"=",
"[",
"]",
"# Optional field with optional value? Who cares.",
"if",
"data_item",
"is",
"None",
"and",
"validator",
".",
"is_optiona... | Validates a single data item against validator.
Returns an array of errors. | [
"Validates",
"a",
"single",
"data",
"item",
"against",
"validator",
"."
] | 0a75b4205624d9bccc52bda03efaf0d58c143c76 | https://github.com/23andMe/Yamale/blob/0a75b4205624d9bccc52bda03efaf0d58c143c76/yamale/schema/schema.py#L85-L114 | train | 202,393 |
23andMe/Yamale | yamale/command_line.py | _find_data_path_schema | def _find_data_path_schema(data_path, schema_name):
""" Starts in the data file folder and recursively looks
in parents for `schema_name` """
if not data_path or data_path == '/' or data_path == '.':
return None
directory = os.path.dirname(data_path)
path = glob.glob(os.path.join(directory, schema_name))
if not path:
return _find_schema(directory, schema_name)
return path[0] | python | def _find_data_path_schema(data_path, schema_name):
""" Starts in the data file folder and recursively looks
in parents for `schema_name` """
if not data_path or data_path == '/' or data_path == '.':
return None
directory = os.path.dirname(data_path)
path = glob.glob(os.path.join(directory, schema_name))
if not path:
return _find_schema(directory, schema_name)
return path[0] | [
"def",
"_find_data_path_schema",
"(",
"data_path",
",",
"schema_name",
")",
":",
"if",
"not",
"data_path",
"or",
"data_path",
"==",
"'/'",
"or",
"data_path",
"==",
"'.'",
":",
"return",
"None",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dat... | Starts in the data file folder and recursively looks
in parents for `schema_name` | [
"Starts",
"in",
"the",
"data",
"file",
"folder",
"and",
"recursively",
"looks",
"in",
"parents",
"for",
"schema_name"
] | 0a75b4205624d9bccc52bda03efaf0d58c143c76 | https://github.com/23andMe/Yamale/blob/0a75b4205624d9bccc52bda03efaf0d58c143c76/yamale/command_line.py#L39-L48 | train | 202,394 |
23andMe/Yamale | yamale/command_line.py | _find_schema | def _find_schema(data_path, schema_name):
""" Checks if `schema_name` is a valid file, if not
searches in `data_path` for it. """
path = glob.glob(schema_name)
for p in path:
if os.path.isfile(p):
return p
return _find_data_path_schema(data_path, schema_name) | python | def _find_schema(data_path, schema_name):
""" Checks if `schema_name` is a valid file, if not
searches in `data_path` for it. """
path = glob.glob(schema_name)
for p in path:
if os.path.isfile(p):
return p
return _find_data_path_schema(data_path, schema_name) | [
"def",
"_find_schema",
"(",
"data_path",
",",
"schema_name",
")",
":",
"path",
"=",
"glob",
".",
"glob",
"(",
"schema_name",
")",
"for",
"p",
"in",
"path",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"p",
")",
":",
"return",
"p",
"return",
"_... | Checks if `schema_name` is a valid file, if not
searches in `data_path` for it. | [
"Checks",
"if",
"schema_name",
"is",
"a",
"valid",
"file",
"if",
"not",
"searches",
"in",
"data_path",
"for",
"it",
"."
] | 0a75b4205624d9bccc52bda03efaf0d58c143c76 | https://github.com/23andMe/Yamale/blob/0a75b4205624d9bccc52bda03efaf0d58c143c76/yamale/command_line.py#L51-L60 | train | 202,395 |
23andMe/Yamale | yamale/util.py | flatten | def flatten(dic, keep_iter=False, position=None):
"""
Returns a flattened dictionary from a dictionary of nested dictionaries and lists.
`keep_iter` will treat iterables as valid values, while also flattening them.
"""
child = {}
if not dic:
return {}
for k, v in get_iter(dic):
if isstr(k):
k = k.replace('.', '_')
if position:
item_position = '%s.%s' % (position, k)
else:
item_position = '%s' % k
if is_iter(v):
child.update(flatten(dic[k], keep_iter, item_position))
if keep_iter:
child[item_position] = v
else:
child[item_position] = v
return child | python | def flatten(dic, keep_iter=False, position=None):
"""
Returns a flattened dictionary from a dictionary of nested dictionaries and lists.
`keep_iter` will treat iterables as valid values, while also flattening them.
"""
child = {}
if not dic:
return {}
for k, v in get_iter(dic):
if isstr(k):
k = k.replace('.', '_')
if position:
item_position = '%s.%s' % (position, k)
else:
item_position = '%s' % k
if is_iter(v):
child.update(flatten(dic[k], keep_iter, item_position))
if keep_iter:
child[item_position] = v
else:
child[item_position] = v
return child | [
"def",
"flatten",
"(",
"dic",
",",
"keep_iter",
"=",
"False",
",",
"position",
"=",
"None",
")",
":",
"child",
"=",
"{",
"}",
"if",
"not",
"dic",
":",
"return",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"get_iter",
"(",
"dic",
")",
":",
"if",
"isst... | Returns a flattened dictionary from a dictionary of nested dictionaries and lists.
`keep_iter` will treat iterables as valid values, while also flattening them. | [
"Returns",
"a",
"flattened",
"dictionary",
"from",
"a",
"dictionary",
"of",
"nested",
"dictionaries",
"and",
"lists",
".",
"keep_iter",
"will",
"treat",
"iterables",
"as",
"valid",
"values",
"while",
"also",
"flattening",
"them",
"."
] | 0a75b4205624d9bccc52bda03efaf0d58c143c76 | https://github.com/23andMe/Yamale/blob/0a75b4205624d9bccc52bda03efaf0d58c143c76/yamale/util.py#L30-L54 | train | 202,396 |
umutbozkurt/django-rest-framework-mongoengine | rest_framework_mongoengine/fields.py | DocumentField.to_representation | def to_representation(self, obj):
""" convert value to representation.
DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.
This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe types intact.
NB: The argument is whole object, instead of attribute value. This is upstream feature.
Probably because the field can be represented by a complicated method with nontrivial way to extract data.
"""
value = self.model_field.__get__(obj, None)
return smart_text(value, strings_only=True) | python | def to_representation(self, obj):
""" convert value to representation.
DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.
This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe types intact.
NB: The argument is whole object, instead of attribute value. This is upstream feature.
Probably because the field can be represented by a complicated method with nontrivial way to extract data.
"""
value = self.model_field.__get__(obj, None)
return smart_text(value, strings_only=True) | [
"def",
"to_representation",
"(",
"self",
",",
"obj",
")",
":",
"value",
"=",
"self",
".",
"model_field",
".",
"__get__",
"(",
"obj",
",",
"None",
")",
"return",
"smart_text",
"(",
"value",
",",
"strings_only",
"=",
"True",
")"
] | convert value to representation.
DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.
This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe types intact.
NB: The argument is whole object, instead of attribute value. This is upstream feature.
Probably because the field can be represented by a complicated method with nontrivial way to extract data. | [
"convert",
"value",
"to",
"representation",
"."
] | 2fe6de53907b31a5e8b742e4c6b728942b5fa4f0 | https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/2fe6de53907b31a5e8b742e4c6b728942b5fa4f0/rest_framework_mongoengine/fields.py#L58-L69 | train | 202,397 |
umutbozkurt/django-rest-framework-mongoengine | rest_framework_mongoengine/fields.py | DocumentField.run_validators | def run_validators(self, value):
""" validate value.
Uses document field's ``validate()``
"""
try:
self.model_field.validate(value)
except MongoValidationError as e:
raise ValidationError(e.message)
super(DocumentField, self).run_validators(value) | python | def run_validators(self, value):
""" validate value.
Uses document field's ``validate()``
"""
try:
self.model_field.validate(value)
except MongoValidationError as e:
raise ValidationError(e.message)
super(DocumentField, self).run_validators(value) | [
"def",
"run_validators",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"self",
".",
"model_field",
".",
"validate",
"(",
"value",
")",
"except",
"MongoValidationError",
"as",
"e",
":",
"raise",
"ValidationError",
"(",
"e",
".",
"message",
")",
"super",
... | validate value.
Uses document field's ``validate()`` | [
"validate",
"value",
"."
] | 2fe6de53907b31a5e8b742e4c6b728942b5fa4f0 | https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/2fe6de53907b31a5e8b742e4c6b728942b5fa4f0/rest_framework_mongoengine/fields.py#L71-L80 | train | 202,398 |
umutbozkurt/django-rest-framework-mongoengine | rest_framework_mongoengine/generics.py | get_object_or_404 | def get_object_or_404(queryset, *args, **kwargs):
""" replacement of rest_framework.generics and django.shrtcuts analogues """
try:
return queryset.get(*args, **kwargs)
except (ValueError, TypeError, DoesNotExist, ValidationError):
raise Http404() | python | def get_object_or_404(queryset, *args, **kwargs):
""" replacement of rest_framework.generics and django.shrtcuts analogues """
try:
return queryset.get(*args, **kwargs)
except (ValueError, TypeError, DoesNotExist, ValidationError):
raise Http404() | [
"def",
"get_object_or_404",
"(",
"queryset",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"queryset",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"DoesN... | replacement of rest_framework.generics and django.shrtcuts analogues | [
"replacement",
"of",
"rest_framework",
".",
"generics",
"and",
"django",
".",
"shrtcuts",
"analogues"
] | 2fe6de53907b31a5e8b742e4c6b728942b5fa4f0 | https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/2fe6de53907b31a5e8b742e4c6b728942b5fa4f0/rest_framework_mongoengine/generics.py#L8-L13 | train | 202,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.