repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
datacamp/protowhat | protowhat/checks/check_simple.py | has_chosen | python | def has_chosen(state, correct, msgs):
ctxt = {}
exec(state.student_code, globals(), ctxt)
sel_indx = ctxt["selected_option"]
if sel_indx != correct:
state.report(Feedback(msgs[sel_indx - 1]))
else:
state.reporter.success_msg = msgs[correct - 1]
return state | Verify exercises of the type MultipleChoiceExercise
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
correct: index of correct option, where 1 is the first option.
msgs : list of feedback messages corresponding to each option.
... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_simple.py#L4-L27 | [
"def report(self, feedback: Feedback):\n if feedback.highlight is None and self is not getattr(self, \"root_state\", None):\n feedback.highlight = self.student_ast\n test = Fail(feedback)\n\n return self.do_test(test)\n"
] | from protowhat.Feedback import Feedback
def success_msg(state, msg):
"""
Changes the success message to display if submission passes.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
msg : feedback message if student and solution ASTs d... |
datacamp/protowhat | protowhat/checks/check_logic.py | multi | python | def multi(state, *tests):
for test in iter_tests(tests):
# assume test is function needing a state argument
# partial state so reporter can test
state.do_test(partial(test, state))
# return original state, so can be chained
return state | Run multiple subtests. Return original state (for chaining).
This function could be thought as an AND statement, since all tests it runs must pass
Args:
state: State instance describing student and solution code, can be omitted if used with Ex()
tests: one or more sub-SCTs to run.
:Examp... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_logic.py#L8-L36 | [
"def iter_tests(tests):\n for arg in tests:\n if arg is None:\n continue\n\n # when input is a single test, make iterable\n if callable(arg):\n arg = [arg]\n\n for test in arg:\n yield test\n"
] | from protowhat.Feedback import Feedback
from protowhat.Test import TestFail
from functools import partial
from protowhat.utils import legacy_signature
@legacy_signature(incorrect_msg='msg')
def check_not(state, *tests, msg):
"""Run multiple subtests that should fail. If all subtests fail, returns original state... |
datacamp/protowhat | protowhat/checks/check_logic.py | check_not | python | def check_not(state, *tests, msg):
for test in iter_tests(tests):
try:
test(state)
except TestFail:
# it fails, as expected, off to next one
continue
return state.report(Feedback(msg))
# return original state, so can be chained
return state | Run multiple subtests that should fail. If all subtests fail, returns original state (for chaining)
- This function is currently only tested in working with ``has_code()`` in the subtests.
- This function can be thought as a ``NOT(x OR y OR ...)`` statement, since all tests it runs must fail
- This functio... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_logic.py#L40-L74 | [
"def iter_tests(tests):\n for arg in tests:\n if arg is None:\n continue\n\n # when input is a single test, make iterable\n if callable(arg):\n arg = [arg]\n\n for test in arg:\n yield test\n"
] | from protowhat.Feedback import Feedback
from protowhat.Test import TestFail
from functools import partial
from protowhat.utils import legacy_signature
def multi(state, *tests):
"""Run multiple subtests. Return original state (for chaining).
This function could be thought as an AND statement, since all tests... |
datacamp/protowhat | protowhat/checks/check_logic.py | check_or | python | def check_or(state, *tests):
success = False
first_feedback = None
for test in iter_tests(tests):
try:
multi(state, test)
success = True
except TestFail as e:
if not first_feedback:
first_feedback = e.feedback
if success:
... | Test whether at least one SCT passes.
If all of the tests fail, the feedback of the first test will be presented to the student.
Args:
state: State instance describing student and solution code, can be omitted if used with Ex()
tests: one or more sub-SCTs to run
:Example:
The SCT ... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_logic.py#L77-L114 | [
"def multi(state, *tests):\n \"\"\"Run multiple subtests. Return original state (for chaining).\n\n This function could be thought as an AND statement, since all tests it runs must pass\n\n Args:\n state: State instance describing student and solution code, can be omitted if used with Ex()\n ... | from protowhat.Feedback import Feedback
from protowhat.Test import TestFail
from functools import partial
from protowhat.utils import legacy_signature
def multi(state, *tests):
"""Run multiple subtests. Return original state (for chaining).
This function could be thought as an AND statement, since all tests... |
datacamp/protowhat | protowhat/checks/check_logic.py | check_correct | python | def check_correct(state, check, diagnose):
feedback = None
try:
multi(state, check)
except TestFail as e:
feedback = e.feedback
# todo: let if from except wrap try-except
# only once teach uses force_diagnose
try:
multi(state, diagnose)
except TestFail as e:
... | Allows feedback from a diagnostic SCT, only if a check SCT fails.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
check: An sct chain that must succeed.
diagnose: An sct chain to run if the check fails.
:Example:
The SCT below... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_logic.py#L117-L151 | [
"def multi(state, *tests):\n \"\"\"Run multiple subtests. Return original state (for chaining).\n\n This function could be thought as an AND statement, since all tests it runs must pass\n\n Args:\n state: State instance describing student and solution code, can be omitted if used with Ex()\n ... | from protowhat.Feedback import Feedback
from protowhat.Test import TestFail
from functools import partial
from protowhat.utils import legacy_signature
def multi(state, *tests):
"""Run multiple subtests. Return original state (for chaining).
This function could be thought as an AND statement, since all tests... |
datacamp/protowhat | protowhat/checks/check_logic.py | fail | python | def fail(state, msg="fail"):
_msg = state.build_message(msg)
state.report(Feedback(_msg, state))
return state | Always fails the SCT, with an optional msg.
This function takes a single argument, ``msg``, that is the feedback given to the student.
Note that this would be a terrible idea for grading submissions, but may be useful while writing SCTs.
For example, failing a test will highlight the code as if the previou... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_logic.py#L175-L185 | null | from protowhat.Feedback import Feedback
from protowhat.Test import TestFail
from functools import partial
from protowhat.utils import legacy_signature
def multi(state, *tests):
"""Run multiple subtests. Return original state (for chaining).
This function could be thought as an AND statement, since all tests... |
datacamp/protowhat | protowhat/checks/check_funcs.py | check_node | python | def check_node(
state,
name,
index=0,
missing_msg="Check the {ast_path}. Could not find the {index}{node_name}.",
priority=None,
):
df = partial(state.ast_dispatcher, name, priority=priority)
sol_stmt_list = df(state.solution_ast)
try:
sol_stmt = sol_stmt_list[index]
except ... | Select a node from abstract syntax tree (AST), using its name and index position.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
name : the name of the abstract syntax tree node to find.
index: the position of that node (see below for det... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_funcs.py#L37-L101 | null | from functools import partial, wraps
from protowhat.Feedback import Feedback
MSG_CHECK_FALLBACK = "Your submission is incorrect. Try again!"
def requires_ast(f):
@wraps(f)
def wrapper(*args, **kwargs):
state = kwargs.get("state", args[0] if len(args) else None)
state_ast = [state.student_ast... |
datacamp/protowhat | protowhat/checks/check_funcs.py | check_edge | python | def check_edge(
state,
name,
index=0,
missing_msg="Check the {ast_path}. Could not find the {index}{field_name}.",
):
try:
sol_attr = getattr(state.solution_ast, name)
if sol_attr and isinstance(sol_attr, list) and index is not None:
sol_attr = sol_attr[index]
except ... | Select an attribute from an abstract syntax tree (AST) node, using the attribute name.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
name: the name of the attribute to select from current AST node.
index: entry to get from a list field. ... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_funcs.py#L105-L166 | null | from functools import partial, wraps
from protowhat.Feedback import Feedback
MSG_CHECK_FALLBACK = "Your submission is incorrect. Try again!"
def requires_ast(f):
@wraps(f)
def wrapper(*args, **kwargs):
state = kwargs.get("state", args[0] if len(args) else None)
state_ast = [state.student_ast... |
datacamp/protowhat | protowhat/checks/check_funcs.py | has_code | python | def has_code(
state,
text,
incorrect_msg="Check the {ast_path}. The checker expected to find {text}.",
fixed=False,
):
stu_ast = state.student_ast
stu_code = state.student_code
# fallback on using complete student code if no ast
ParseError = state.ast_dispatcher.ParseError
def get_... | Test whether the student code contains text.
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
text : text that student code must contain. Can be a regex pattern or a simple string.
incorrect_msg: feedback message if text is not in student c... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_funcs.py#L172-L243 | [
"def get_text(ast, code):\n if isinstance(ast, ParseError):\n return code\n try:\n return ast.get_text(code)\n except:\n return code\n"
] | from functools import partial, wraps
from protowhat.Feedback import Feedback
MSG_CHECK_FALLBACK = "Your submission is incorrect. Try again!"
def requires_ast(f):
@wraps(f)
def wrapper(*args, **kwargs):
state = kwargs.get("state", args[0] if len(args) else None)
state_ast = [state.student_ast... |
datacamp/protowhat | protowhat/checks/check_funcs.py | has_equal_ast | python | def has_equal_ast(
state,
incorrect_msg="Check the {ast_path}. {extra}",
sql=None,
start=["expression", "subquery", "sql_script"][0],
exact=None,
):
ast = state.ast_dispatcher.ast_mod
sol_ast = state.solution_ast if sql is None else ast.parse(sql, start)
# if sql is set, exact defaults ... | Test whether the student and solution code have identical AST representations
Args:
state: State instance describing student and solution code. Can be omitted if used with Ex().
incorrect_msg: feedback message if student and solution ASTs don't match
sql : optional code to use instead of t... | train | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_funcs.py#L247-L319 | [
"def get_str(ast, code, sql):\n if sql:\n return sql\n if isinstance(ast, str):\n return ast\n try:\n return ast.get_text(code)\n except:\n return None\n"
] | from functools import partial, wraps
from protowhat.Feedback import Feedback
MSG_CHECK_FALLBACK = "Your submission is incorrect. Try again!"
def requires_ast(f):
@wraps(f)
def wrapper(*args, **kwargs):
state = kwargs.get("state", args[0] if len(args) else None)
state_ast = [state.student_ast... |
MycroftAI/mycroft-skills-manager | msm/skill_repo.py | SkillRepo.get_skill_data | python | def get_skill_data(self):
path_to_sha = {
folder: sha for folder, sha in self.get_shas()
}
modules = self.read_file('.gitmodules').split('[submodule "')
for i, module in enumerate(modules):
if not module:
continue
try:
n... | generates tuples of name, path, url, sha | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skill_repo.py#L95-L113 | [
"def read_file(self, filename):\n with open(join(self.path, filename)) as f:\n return f.read()\n",
"def get_shas(self):\n git = Git(self.path)\n with git_to_msm_exceptions():\n shas = git.ls_tree('origin/' + self.branch)\n for line in shas.split('\\n'):\n size, typ, sha, folder = ... | class SkillRepo(object):
def __init__(self, path=None, url=None, branch=None):
self.path = path or "/opt/mycroft/.skills-repo"
self.url = url or "https://github.com/MycroftAI/mycroft-skills"
self.branch = branch or "19.02"
self.repo_info = {}
self.skills_meta_info = load_skil... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.curate_skills_data | python | def curate_skills_data(self, skills_data):
local_skills = [s for s in self.list() if s.is_local]
default_skills = [s.name for s in self.list_defaults()]
local_skill_names = [s.name for s in local_skills]
skills_data_skills = [s['name'] for s in skills_data['skills']]
# Check for... | Sync skills_data with actual skills on disk. | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L118-L145 | [
"def build_skill_entry(name, origin, beta) -> dict:\n \"\"\" Create a new skill entry\n\n Arguments:\n name: skill name\n origin: the source of the installation\n beta: Boolean indicating wether the skill is in beta\n Returns:\n populated skills entry\n \"\"\"\n return {\n... | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.sync_skills_data | python | def sync_skills_data(self):
self.skills_data = self.load_skills_data()
if 'upgraded' in self.skills_data:
self.skills_data.pop('upgraded')
else:
self.skills_data_hash = skills_data_hash(self.skills_data) | Update internal skill_data_structure from disk. | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L155-L161 | [
"def skills_data_hash(data):\n return hash(json.dumps(data, sort_keys=True))\n",
"def load_skills_data(self) -> dict:\n skills_data = load_skills_data()\n if skills_data.get('version', 0) < CURRENT_SKILLS_DATA_VERSION:\n skills_data = self.__upgrade_skills_data(skills_data)\n else:\n ski... | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.write_skills_data | python | def write_skills_data(self, data=None):
data = data or self.skills_data
if skills_data_hash(data) != self.skills_data_hash:
write_skills_data(data)
self.skills_data_hash = skills_data_hash(data) | Write skills data hash if it has been modified. | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L163-L168 | [
"def write_skills_data(data: dict):\n skills_data_file = expanduser('~/.mycroft/skills.json')\n with open(skills_data_file, 'w') as f:\n json.dump(data, f, indent=4, separators=(',', ':'))\n",
"def skills_data_hash(data):\n return hash(json.dumps(data, sort_keys=True))\n"
] | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.install | python | def install(self, param, author=None, constraints=None, origin=''):
if isinstance(param, SkillEntry):
skill = param
else:
skill = self.find_skill(param, author)
entry = build_skill_entry(skill.name, origin, skill.is_beta)
try:
skill.install(constraints... | Install by url or name | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L171-L195 | [
"def build_skill_entry(name, origin, beta) -> dict:\n \"\"\" Create a new skill entry\n\n Arguments:\n name: skill name\n origin: the source of the installation\n beta: Boolean indicating wether the skill is in beta\n Returns:\n populated skills entry\n \"\"\"\n return {\n... | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.remove | python | def remove(self, param, author=None):
if isinstance(param, SkillEntry):
skill = param
else:
skill = self.find_skill(param, author)
skill.remove()
skills = [s for s in self.skills_data['skills']
if s['name'] != skill.name]
self.skills_data... | Remove by url or name | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L198-L208 | [
"def find_skill(self, param, author=None, skills=None):\n # type: (str, str, List[SkillEntry]) -> SkillEntry\n \"\"\"Find skill by name or url\"\"\"\n if param.startswith('https://') or param.startswith('http://'):\n repo_id = SkillEntry.extract_repo_id(param)\n for skill in self.list():\n ... | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.update | python | def update(self, skill=None, author=None):
if skill is None:
return self.update_all()
else:
if isinstance(skill, str):
skill = self.find_skill(skill, author)
entry = get_skill_entry(skill.name, self.skills_data)
if entry:
en... | Update all downloaded skills or one specified skill. | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L224-L237 | [
"def get_skill_entry(name, skills_data) -> dict:\n \"\"\" Find a skill entry in the skills_data and returns it. \"\"\"\n for e in skills_data.get('skills', []):\n if e.get('name') == name:\n return e\n return {}\n",
"def update_all(self):\n local_skills = [skill for skill in self.lis... | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.apply | python | def apply(self, func, skills):
def run_item(skill):
try:
func(skill)
return True
except MsmException as e:
LOG.error('Error running {} on {}: {}'.format(
func.__name__, skill.name, repr(e)
))
... | Run a function on all skills in parallel | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L240-L258 | null | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.install_defaults | python | def install_defaults(self):
def install_or_update_skill(skill):
if skill.is_local:
self.update(skill)
else:
self.install(skill, origin='default')
return self.apply(install_or_update_skill, self.list_defaults()) | Installs the default skills, updates all others | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L261-L270 | [
"def list_defaults(self):\n skill_groups = self.list_all_defaults()\n\n if self.platform not in skill_groups:\n LOG.error('Unknown platform:' + self.platform)\n return skill_groups.get(self.platform,\n skill_groups.get('default', []))\n"
] | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.list_all_defaults | python | def list_all_defaults(self): # type: () -> Dict[str, List[SkillEntry]]
skills = self.list()
name_to_skill = {skill.name: skill for skill in skills}
defaults = {group: [] for group in self.SKILL_GROUPS}
for section_name, skill_names in self.repo.get_default_skill_names():
se... | Returns {'skill_group': [SkillEntry('name')]} | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L272-L287 | [
"def list(self):\n \"\"\"\n Load a list of SkillEntry objects from both local and\n remote skills\n\n It is necessary to load both local and remote skills at\n the same time to correctly associate local skills with the name\n in the repo and remote skills with any custom path that they\n have b... | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.list | python | def list(self):
try:
self.repo.update()
except GitException as e:
if not isdir(self.repo.path):
raise
LOG.warning('Failed to update repo: {}'.format(repr(e)))
remote_skill_list = (
SkillEntry(
name, SkillEntry.create... | Load a list of SkillEntry objects from both local and
remote skills
It is necessary to load both local and remote skills at
the same time to correctly associate local skills with the name
in the repo and remote skills with any custom path that they
have been downloaded to | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L297-L330 | [
"def from_folder(cls, path, msm=None):\n return cls(basename(path), path, cls.find_git_url(path), msm=msm)\n"
] | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/mycroft_skills_manager.py | MycroftSkillsManager.find_skill | python | def find_skill(self, param, author=None, skills=None):
# type: (str, str, List[SkillEntry]) -> SkillEntry
if param.startswith('https://') or param.startswith('http://'):
repo_id = SkillEntry.extract_repo_id(param)
for skill in self.list():
if skill.id == repo_id:
... | Find skill by name or url | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/mycroft_skills_manager.py#L332-L362 | [
"def list(self):\n \"\"\"\n Load a list of SkillEntry objects from both local and\n remote skills\n\n It is necessary to load both local and remote skills at\n the same time to correctly associate local skills with the name\n in the repo and remote skills with any custom path that they\n have b... | class MycroftSkillsManager(object):
SKILL_GROUPS = {'default', 'mycroft_mark_1', 'picroft', 'kde'}
DEFAULT_SKILLS_DIR = "/opt/mycroft/skills"
def __init__(self, platform='default', skills_dir=None, repo=None,
versioned=True):
self.platform = platform
self.skills_dir = (
... |
MycroftAI/mycroft-skills-manager | msm/skills_data.py | load_skills_data | python | def load_skills_data() -> dict:
skills_data_file = expanduser('~/.mycroft/skills.json')
if isfile(skills_data_file):
try:
with open(skills_data_file) as f:
return json.load(f)
except json.JSONDecodeError:
return {}
else:
return {} | Contains info on how skills should be updated | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skills_data.py#L9-L19 | null | """
Functions related to manipulating the skills_data.json
"""
import json
from os.path import expanduser, isfile
def write_skills_data(data: dict):
skills_data_file = expanduser('~/.mycroft/skills.json')
with open(skills_data_file, 'w') as f:
json.dump(data, f, indent=4, separators=(',', ':'))
... |
MycroftAI/mycroft-skills-manager | msm/skills_data.py | get_skill_entry | python | def get_skill_entry(name, skills_data) -> dict:
for e in skills_data.get('skills', []):
if e.get('name') == name:
return e
return {} | Find a skill entry in the skills_data and returns it. | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skills_data.py#L28-L33 | null | """
Functions related to manipulating the skills_data.json
"""
import json
from os.path import expanduser, isfile
def load_skills_data() -> dict:
"""Contains info on how skills should be updated"""
skills_data_file = expanduser('~/.mycroft/skills.json')
if isfile(skills_data_file):
try:
... |
MycroftAI/mycroft-skills-manager | msm/skill_entry.py | _backup_previous_version | python | def _backup_previous_version(func: Callable = None):
@wraps(func)
def wrapper(self, *args, **kwargs):
self.old_path = None
if self.is_local:
self.old_path = join(gettempdir(), self.name)
if exists(self.old_path):
rmtree(self.old_path)
shutil.c... | Private decorator to back up previous skill folder | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skill_entry.py#L69-L96 | null | # Copyright (c) 2018 Mycroft AI, Inc.
#
# This file is part of Mycroft Skills Manager
# (see https://github.com/MatthewScholefield/mycroft-light).
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional inf... |
MycroftAI/mycroft-skills-manager | msm/skill_entry.py | SkillEntry.attach | python | def attach(self, remote_entry):
self.name = remote_entry.name
self.sha = remote_entry.sha
self.url = remote_entry.url
self.author = remote_entry.author
return self | Attach a remote entry to a local entry | train | https://github.com/MycroftAI/mycroft-skills-manager/blob/5acef240de42e8ceae2e82bc7492ffee33288b00/msm/skill_entry.py#L136-L142 | null | class SkillEntry(object):
pip_lock = Lock()
manifest_yml_format = {
'dependencies': {
'system': {},
'exes': [],
'skill': [],
'python': []
}
}
def __init__(self, name, path, url='', sha='', msm=None):
url = url.rstrip('/')
u... |
Hundemeier/sacn | sacn/sender.py | sACNsender.activate_output | python | def activate_output(self, universe: int) -> None:
check_universe(universe)
# check, if the universe already exists in the list:
if universe in self._outputs:
return
# add new sending:
new_output = Output(DataPacket(cid=self.__CID, sourceName=self.source_name, universe... | Activates a universe that's then starting to sending every second.
See http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf for more information
:param universe: the universe to activate | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/sender.py#L56-L68 | [
"def check_universe(universe: int):\n if universe not in range(1, 64000):\n raise TypeError(f'Universe must be between [1-63999]! Universe was {universe}')\n"
] | class sACNsender:
def __init__(self, bind_address: str = "0.0.0.0", bind_port: int = DEFAULT_PORT,
source_name: str = "default source name", cid: tuple = (),
fps: int = 30, universeDiscovery: bool = True):
"""
Creates a sender object. A sender is used to manage mult... |
Hundemeier/sacn | sacn/sender.py | sACNsender.deactivate_output | python | def deactivate_output(self, universe: int) -> None:
check_universe(universe)
try: # try to send out three messages with stream_termination bit set to 1
self._outputs[universe]._packet.option_StreamTerminated = True
for i in range(0, 3):
self._output_thread.send_o... | Deactivates an existing sending. Every data from the existing sending output will be lost.
(TTL, Multicast, DMX data, ..)
:param universe: the universe to deactivate. If the universe was not activated before, no error is raised | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/sender.py#L70-L86 | [
"def check_universe(universe: int):\n if universe not in range(1, 64000):\n raise TypeError(f'Universe must be between [1-63999]! Universe was {universe}')\n"
] | class sACNsender:
def __init__(self, bind_address: str = "0.0.0.0", bind_port: int = DEFAULT_PORT,
source_name: str = "default source name", cid: tuple = (),
fps: int = 30, universeDiscovery: bool = True):
"""
Creates a sender object. A sender is used to manage mult... |
Hundemeier/sacn | sacn/sender.py | sACNsender.move_universe | python | def move_universe(self, universe_from: int, universe_to: int) -> None:
check_universe(universe_from)
check_universe(universe_to)
# store the sending object and change the universe in the packet of the sending
tmp_output = self._outputs[universe_from]
tmp_output._packet.universe =... | Moves an sending from one universe to another. All settings are being restored and only the universe changes
:param universe_from: the universe that should be moved
:param universe_to: the target universe. An existing universe will be overwritten | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/sender.py#L95-L109 | [
"def check_universe(universe: int):\n if universe not in range(1, 64000):\n raise TypeError(f'Universe must be between [1-63999]! Universe was {universe}')\n",
"def deactivate_output(self, universe: int) -> None:\n \"\"\"\n Deactivates an existing sending. Every data from the existing sending outp... | class sACNsender:
def __init__(self, bind_address: str = "0.0.0.0", bind_port: int = DEFAULT_PORT,
source_name: str = "default source name", cid: tuple = (),
fps: int = 30, universeDiscovery: bool = True):
"""
Creates a sender object. A sender is used to manage mult... |
Hundemeier/sacn | sacn/sender.py | sACNsender.start | python | def start(self, bind_address=None, bind_port: int = None, fps: int = None) -> None:
if bind_address is None:
bind_address = self.bindAddress
if fps is None:
fps = self._fps
if bind_port is None:
bind_port = self.bind_port
self.stop()
self._outp... | Starts or restarts a new Thread with the parameters given in the constructor or
the parameters given in this function.
The parameters in this function do not override the class specific values!
:param bind_address: the IP-Address to bind to
:param bind_port: the port to bind to
:... | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/sender.py#L117-L136 | [
"def stop(self) -> None:\n \"\"\"\n Tries to stop a current running sender. A running Thread will be stopped and should terminate.\n \"\"\"\n try:\n self._output_thread.enabled_flag = False\n except:\n pass\n"
] | class sACNsender:
def __init__(self, bind_address: str = "0.0.0.0", bind_port: int = DEFAULT_PORT,
source_name: str = "default source name", cid: tuple = (),
fps: int = 30, universeDiscovery: bool = True):
"""
Creates a sender object. A sender is used to manage mult... |
Hundemeier/sacn | sacn/receiver.py | sACNreceiver.listen_on | python | def listen_on(self, trigger: str, **kwargs) -> callable:
def decorator(f):
self.register_listener(trigger, f, **kwargs)
return f
return decorator | This is a simple decorator for registering a callback for an event. You can also use 'register_listener'.
A list with all possible options is available via LISTEN_ON_OPTIONS.
:param trigger: Currently supported options: 'universe availability change', 'universe' | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/receiver.py#L36-L45 | null | class sACNreceiver:
def __init__(self, bind_address: str = '0.0.0.0', bind_port: int = 5568):
"""
Make a receiver for sACN data. Do not forget to start and add callbacks for receiving messages!
:param bind_address: if you are on a Windows system and want to use multicast provide a valid inte... |
Hundemeier/sacn | sacn/receiver.py | sACNreceiver.register_listener | python | def register_listener(self, trigger: str, func: callable, **kwargs) -> None:
if trigger in LISTEN_ON_OPTIONS:
if trigger == LISTEN_ON_OPTIONS[1]: # if the trigger is universe, use the universe from args as key
try:
self._callbacks[kwargs[LISTEN_ON_OPTIONS[1]]].ap... | Register a listener for the given trigger. Raises an TypeError when the trigger is not a valid one.
To get a list with all valid triggers, use LISTEN_ON_OPTIONS.
:param trigger: the trigger on which the given callback should be used.
Currently supported: 'universe availability change', 'univers... | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/receiver.py#L47-L66 | null | class sACNreceiver:
def __init__(self, bind_address: str = '0.0.0.0', bind_port: int = 5568):
"""
Make a receiver for sACN data. Do not forget to start and add callbacks for receiving messages!
:param bind_address: if you are on a Windows system and want to use multicast provide a valid inte... |
Hundemeier/sacn | sacn/receiver.py | sACNreceiver.join_multicast | python | def join_multicast(self, universe: int) -> None:
self.sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(calculate_multicast_addr(universe)) +
socket.inet_aton(self._bindAddress)) | Joins the multicast address that is used for the given universe. Note: If you are on Windows you must have given
a bind IP-Address for this feature to function properly. On the other hand you are not allowed to set a bind
address if you are on any other OS.
:param universe: the universe to join ... | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/receiver.py#L68-L78 | [
"def calculate_multicast_addr(universe: int) -> str:\n hi_byte = universe >> 8 # a little bit shifting here\n lo_byte = universe & 0xFF # a little bit mask there\n return f\"239.255.{hi_byte}.{lo_byte}\"\n"
] | class sACNreceiver:
def __init__(self, bind_address: str = '0.0.0.0', bind_port: int = 5568):
"""
Make a receiver for sACN data. Do not forget to start and add callbacks for receiving messages!
:param bind_address: if you are on a Windows system and want to use multicast provide a valid inte... |
Hundemeier/sacn | sacn/receiver.py | sACNreceiver.leave_multicast | python | def leave_multicast(self, universe: int) -> None:
try:
self.sock.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP,
socket.inet_aton(calculate_multicast_addr(universe)) +
socket.inet_aton(self._bindAddress))
except: # try t... | Try to leave the multicast group with the specified universe. This does not throw any exception if the group
could not be leaved.
:param universe: the universe to leave the multicast group.
The network hardware has to support the multicast feature! | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/receiver.py#L80-L92 | [
"def calculate_multicast_addr(universe: int) -> str:\n hi_byte = universe >> 8 # a little bit shifting here\n lo_byte = universe & 0xFF # a little bit mask there\n return f\"239.255.{hi_byte}.{lo_byte}\"\n"
] | class sACNreceiver:
def __init__(self, bind_address: str = '0.0.0.0', bind_port: int = 5568):
"""
Make a receiver for sACN data. Do not forget to start and add callbacks for receiving messages!
:param bind_address: if you are on a Windows system and want to use multicast provide a valid inte... |
Hundemeier/sacn | sacn/receiver.py | sACNreceiver.start | python | def start(self) -> None:
self.stop() # stop an existing thread
self._thread = receiverThread(socket=self.sock, callbacks=self._callbacks)
self._thread.start() | Starts a new thread that handles the input. If a thread is already running, the thread will be restarted. | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/receiver.py#L94-L100 | [
"def stop(self) -> None:\n \"\"\"\n Stops a running thread. If no thread was started nothing happens.\n \"\"\"\n try:\n self._thread.enabled_flag = False\n except: # try to stop the thread\n pass\n"
] | class sACNreceiver:
def __init__(self, bind_address: str = '0.0.0.0', bind_port: int = 5568):
"""
Make a receiver for sACN data. Do not forget to start and add callbacks for receiving messages!
:param bind_address: if you are on a Windows system and want to use multicast provide a valid inte... |
Hundemeier/sacn | sacn/messages/data_packet.py | DataPacket.dmxData | python | def dmxData(self, data: tuple):
newData = [0]*512
for i in range(0, min(len(data), 512)):
newData[i] = data[i]
self._dmxData = tuple(newData)
# in theory this class supports dynamic length, so the next line is correcting the length
self.length = 126 + len(self._dmxDat... | For legacy devices and to prevent errors, the length of the DMX data is normalized to 512 | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/messages/data_packet.py#L69-L78 | null | class DataPacket(RootLayer):
def __init__(self, cid: tuple, sourceName: str, universe: int, dmxData: tuple = (), priority: int = 100,
sequence: int = 0, streamTerminated: bool = False, previewData: bool = False):
self._vector1 = VECTOR_E131_DATA_PACKET
self._vector2 = VECTOR_DMP_SET... |
Hundemeier/sacn | sacn/messages/data_packet.py | DataPacket.make_data_packet | python | def make_data_packet(raw_data) -> 'DataPacket':
# Check if the length is sufficient
if len(raw_data) < 126:
raise TypeError('The length of the provided data is not long enough! Min length is 126!')
# Check if the three Vectors are correct
if tuple(raw_data[18:22]) != tuple(VE... | Converts raw byte data to a sACN DataPacket. Note that the raw bytes have to come from a 2016 sACN Message.
This does not support Sync Addresses, Force_Sync option and DMX Start code!
:param raw_data: raw bytes as tuple or list
:return: a DataPacket with the properties set like the raw bytes | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/messages/data_packet.py#L124-L148 | null | class DataPacket(RootLayer):
def __init__(self, cid: tuple, sourceName: str, universe: int, dmxData: tuple = (), priority: int = 100,
sequence: int = 0, streamTerminated: bool = False, previewData: bool = False):
self._vector1 = VECTOR_E131_DATA_PACKET
self._vector2 = VECTOR_DMP_SET... |
Hundemeier/sacn | sacn/messages/root_layer.py | RootLayer.getBytes | python | def getBytes(self) -> list:
'''Returns the Root layer as list with bytes'''
tmpList = []
tmpList.extend(_FIRST_INDEX)
# first append the high byte from the Flags and Length
# high 4 bit: 0x7 then the bits 8-11(indexes) from _length
length = self.length - 16
tmpLis... | Returns the Root layer as list with bytes | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/messages/root_layer.py#L33-L46 | null | class RootLayer:
def __init__(self, length: int, cid: tuple, vector: tuple):
self.length = length
if(len(vector) != 4):
raise ValueError('the length of the vector is not 4!')
self._vector = vector
if(len(cid) != 16):
raise ValueError('the length of the CID is ... |
Hundemeier/sacn | sacn/receiving/receiver_thread.py | receiverThread.is_legal_sequence | python | def is_legal_sequence(self, packet: DataPacket) -> bool:
# if the sequence of the packet is smaller than the last received sequence, return false
# therefore calculate the difference between the two values:
try: # try, because self.lastSequence might not been initialized
diff = pack... | Check if the Sequence number of the DataPacket is legal.
For more information see page 17 of http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf.
:param packet: the packet to check
:return: true if the sequence is legal. False if the sequence number is bad | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/receiving/receiver_thread.py#L109-L127 | null | class receiverThread(threading.Thread):
def __init__(self, socket, callbacks: Dict[any, list]):
"""
This is a private class and should not be used elsewhere. It handles the while loop running in the thread.
:param socket: the socket to use to listen. It will not be initalized and only the so... |
Hundemeier/sacn | sacn/receiving/receiver_thread.py | receiverThread.is_legal_priority | python | def is_legal_priority(self, packet: DataPacket):
# check if the packet's priority is high enough to get processed
if packet.universe not in self.callbacks.keys() or \
packet.priority < self.priorities[packet.universe][0]:
return False # return if the universe is not interesting
... | Check if the given packet has high enough priority for the stored values for the packet's universe.
:param packet: the packet to check
:return: returns True if the priority is good. Otherwise False | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/receiving/receiver_thread.py#L129-L140 | null | class receiverThread(threading.Thread):
def __init__(self, socket, callbacks: Dict[any, list]):
"""
This is a private class and should not be used elsewhere. It handles the while loop running in the thread.
:param socket: the socket to use to listen. It will not be initalized and only the so... |
Hundemeier/sacn | sacn/messages/universe_discovery.py | convert_raw_data_to_universes | python | def convert_raw_data_to_universes(raw_data) -> tuple:
if len(raw_data)%2 != 0:
raise TypeError('The given data has not a length that is a multiple of 2!')
rtrnList = []
for i in range(0, len(raw_data), 2):
rtrnList.append(two_bytes_to_int(raw_data[i], raw_data[i+1]))
return tuple(rtrnLis... | converts the raw data to a readable universes tuple. The raw_data is scanned from index 0 and has to have
16-bit numbers with high byte first. The data is converted from the start to the beginning!
:param raw_data: the raw data to convert
:return: tuple full with 16-bit numbers | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/messages/universe_discovery.py#L131-L143 | [
"def two_bytes_to_int(hi_byte: int, low_byte: int) -> int:\n \"\"\"\n Converts two bytes to a normal integer value.\n :param hi_byte: the high byte\n :param low_byte: the low byte\n :return: converted integer that has a value between [0-65535]\n \"\"\"\n return ((hi_byte & 0xFF)*256) + (low_byt... | """
This class represents an universe discovery packet of the E1.31 Standard.
"""
from typing import List
from sacn.messages.root_layer import RootLayer, VECTOR_ROOT_E131_EXTENDED, \
VECTOR_E131_EXTENDED_DISCOVERY, VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST,\
make_flagsandlength, int_to_bytes
class UniverseDisc... |
Hundemeier/sacn | sacn/messages/universe_discovery.py | UniverseDiscoveryPacket.make_multiple_uni_disc_packets | python | def make_multiple_uni_disc_packets(cid: tuple, sourceName: str, universes: list) -> List['UniverseDiscoveryPacket']:
tmpList = []
if len(universes)%512 != 0:
num_of_packets = int(len(universes)/512)+1
else: # just get how long the list has to be. Just read and think about the if sta... | Creates a list with universe discovery packets based on the given data. It creates automatically enough packets
for the given universes list.
:param cid: the cid to use in all packets
:param sourceName: the source name to use in all packets
:param universes: the universes. Can be longer ... | train | https://github.com/Hundemeier/sacn/blob/f08bf3d7554a1ed2870f23a9e0e7b89a4a509231/sacn/messages/universe_discovery.py#L102-L128 | null | class UniverseDiscoveryPacket(RootLayer):
def __init__(self, cid: tuple, sourceName: str, universes: tuple, page: int = 0, lastPage: int = 0):
self.sourceName: str = sourceName
self._page: int = page
self._lastPage: int = lastPage
self._universes: list = universes
super().__i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.