repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Dallinger/Dallinger
dallinger/networks.py
DiscreteGenerational.add_node
def add_node(self, node): """Link to the agent from a parent based on the parent's fitness""" num_agents = len(self.nodes(type=Agent)) curr_generation = int((num_agents - 1) / float(self.generation_size)) node.generation = curr_generation if curr_generation == 0 and self.initial...
python
def add_node(self, node): """Link to the agent from a parent based on the parent's fitness""" num_agents = len(self.nodes(type=Agent)) curr_generation = int((num_agents - 1) / float(self.generation_size)) node.generation = curr_generation if curr_generation == 0 and self.initial...
[ "def", "add_node", "(", "self", ",", "node", ")", ":", "num_agents", "=", "len", "(", "self", ".", "nodes", "(", "type", "=", "Agent", ")", ")", "curr_generation", "=", "int", "(", "(", "num_agents", "-", "1", ")", "/", "float", "(", "self", ".", ...
Link to the agent from a parent based on the parent's fitness
[ "Link", "to", "the", "agent", "from", "a", "parent", "based", "on", "the", "parent", "s", "fitness" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/networks.py#L168-L183
Dallinger/Dallinger
dallinger/networks.py
SequentialMicrosociety.add_node
def add_node(self, node): """Add a node, connecting it to all the active nodes.""" for predecessor in self._most_recent_predecessors_to(node): predecessor.connect(whom=node)
python
def add_node(self, node): """Add a node, connecting it to all the active nodes.""" for predecessor in self._most_recent_predecessors_to(node): predecessor.connect(whom=node)
[ "def", "add_node", "(", "self", ",", "node", ")", ":", "for", "predecessor", "in", "self", ".", "_most_recent_predecessors_to", "(", "node", ")", ":", "predecessor", ".", "connect", "(", "whom", "=", "node", ")" ]
Add a node, connecting it to all the active nodes.
[ "Add", "a", "node", "connecting", "it", "to", "all", "the", "active", "nodes", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/networks.py#L282-L285
Dallinger/Dallinger
demos/dlgr/demos/chatroom/experiment.py
CoordinationChatroom.create_network
def create_network(self): """Create a new network by reading the configuration file.""" class_ = getattr(networks, self.network_class) return class_(max_size=self.quorum)
python
def create_network(self): """Create a new network by reading the configuration file.""" class_ = getattr(networks, self.network_class) return class_(max_size=self.quorum)
[ "def", "create_network", "(", "self", ")", ":", "class_", "=", "getattr", "(", "networks", ",", "self", ".", "network_class", ")", "return", "class_", "(", "max_size", "=", "self", ".", "quorum", ")" ]
Create a new network by reading the configuration file.
[ "Create", "a", "new", "network", "by", "reading", "the", "configuration", "file", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/chatroom/experiment.py#L44-L47
Dallinger/Dallinger
demos/dlgr/demos/chatroom/experiment.py
CoordinationChatroom.info_post_request
def info_post_request(self, node, info): """Run when a request to create an info is complete.""" for agent in node.neighbors(): node.transmit(what=info, to_whom=agent)
python
def info_post_request(self, node, info): """Run when a request to create an info is complete.""" for agent in node.neighbors(): node.transmit(what=info, to_whom=agent)
[ "def", "info_post_request", "(", "self", ",", "node", ",", "info", ")", ":", "for", "agent", "in", "node", ".", "neighbors", "(", ")", ":", "node", ".", "transmit", "(", "what", "=", "info", ",", "to_whom", "=", "agent", ")" ]
Run when a request to create an info is complete.
[ "Run", "when", "a", "request", "to", "create", "an", "info", "is", "complete", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/chatroom/experiment.py#L53-L56
Dallinger/Dallinger
dallinger/experiment_server/utils.py
nocache
def nocache(func): """Stop caching for pages wrapped in nocache decorator.""" def new_func(*args, **kwargs): """No cache Wrapper.""" resp = make_response(func(*args, **kwargs)) resp.cache_control.no_cache = True return resp return update_wrapper(new_func, func)
python
def nocache(func): """Stop caching for pages wrapped in nocache decorator.""" def new_func(*args, **kwargs): """No cache Wrapper.""" resp = make_response(func(*args, **kwargs)) resp.cache_control.no_cache = True return resp return update_wrapper(new_func, func)
[ "def", "nocache", "(", "func", ")", ":", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"No cache Wrapper.\"\"\"", "resp", "=", "make_response", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "resp", ...
Stop caching for pages wrapped in nocache decorator.
[ "Stop", "caching", "for", "pages", "wrapped", "in", "nocache", "decorator", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/utils.py#L6-L15
Dallinger/Dallinger
dallinger/experiment_server/utils.py
ValidatesBrowser.exclusions
def exclusions(self): """Return list of browser exclusion rules defined in the Configuration. """ exclusion_rules = [ r.strip() for r in self.config.get("browser_exclude_rule", "").split(",") if r.strip() ] return exclusion_rules
python
def exclusions(self): """Return list of browser exclusion rules defined in the Configuration. """ exclusion_rules = [ r.strip() for r in self.config.get("browser_exclude_rule", "").split(",") if r.strip() ] return exclusion_rules
[ "def", "exclusions", "(", "self", ")", ":", "exclusion_rules", "=", "[", "r", ".", "strip", "(", ")", "for", "r", "in", "self", ".", "config", ".", "get", "(", "\"browser_exclude_rule\"", ",", "\"\"", ")", ".", "split", "(", "\",\"", ")", "if", "r", ...
Return list of browser exclusion rules defined in the Configuration.
[ "Return", "list", "of", "browser", "exclusion", "rules", "defined", "in", "the", "Configuration", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/utils.py#L26-L34
Dallinger/Dallinger
dallinger/experiment_server/utils.py
ValidatesBrowser.is_supported
def is_supported(self, user_agent_string): """Check user agent against configured exclusions. """ user_agent_obj = user_agents.parse(user_agent_string) browser_ok = True for rule in self.exclusions: if rule in ["mobile", "tablet", "touchcapable", "pc", "bot"]: ...
python
def is_supported(self, user_agent_string): """Check user agent against configured exclusions. """ user_agent_obj = user_agents.parse(user_agent_string) browser_ok = True for rule in self.exclusions: if rule in ["mobile", "tablet", "touchcapable", "pc", "bot"]: ...
[ "def", "is_supported", "(", "self", ",", "user_agent_string", ")", ":", "user_agent_obj", "=", "user_agents", ".", "parse", "(", "user_agent_string", ")", "browser_ok", "=", "True", "for", "rule", "in", "self", ".", "exclusions", ":", "if", "rule", "in", "["...
Check user agent against configured exclusions.
[ "Check", "user", "agent", "against", "configured", "exclusions", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/utils.py#L36-L54
Dallinger/Dallinger
demos/dlgr/demos/function_learning/experiment.py
FunctionLearning.setup
def setup(self): """Setup does stuff only if there are no networks. This is so it only runs once at the start of the experiment. It first calls the same function in the super (see experiments.py in dallinger). Then it adds a source to each network. """ if not self.networ...
python
def setup(self): """Setup does stuff only if there are no networks. This is so it only runs once at the start of the experiment. It first calls the same function in the super (see experiments.py in dallinger). Then it adds a source to each network. """ if not self.networ...
[ "def", "setup", "(", "self", ")", ":", "if", "not", "self", ".", "networks", "(", ")", ":", "super", "(", "FunctionLearning", ",", "self", ")", ".", "setup", "(", ")", "for", "net", "in", "self", ".", "networks", "(", ")", ":", "self", ".", "mode...
Setup does stuff only if there are no networks. This is so it only runs once at the start of the experiment. It first calls the same function in the super (see experiments.py in dallinger). Then it adds a source to each network.
[ "Setup", "does", "stuff", "only", "if", "there", "are", "no", "networks", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/function_learning/experiment.py#L28-L38
Dallinger/Dallinger
demos/dlgr/demos/mcmcp/experiment.py
MCMCP.create_node
def create_node(self, network, participant): """Create a node for a participant.""" return self.models.MCMCPAgent(network=network, participant=participant)
python
def create_node(self, network, participant): """Create a node for a participant.""" return self.models.MCMCPAgent(network=network, participant=participant)
[ "def", "create_node", "(", "self", ",", "network", ",", "participant", ")", ":", "return", "self", ".", "models", ".", "MCMCPAgent", "(", "network", "=", "network", ",", "participant", "=", "participant", ")" ]
Create a node for a participant.
[ "Create", "a", "node", "for", "a", "participant", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/mcmcp/experiment.py#L40-L42
Dallinger/Dallinger
demos/dlgr/demos/mcmcp/experiment.py
MCMCP.data_check
def data_check(self, participant): """Make sure each trial contains exactly one chosen info.""" infos = participant.infos() return len([info for info in infos if info.chosen]) * 2 == len(infos)
python
def data_check(self, participant): """Make sure each trial contains exactly one chosen info.""" infos = participant.infos() return len([info for info in infos if info.chosen]) * 2 == len(infos)
[ "def", "data_check", "(", "self", ",", "participant", ")", ":", "infos", "=", "participant", ".", "infos", "(", ")", "return", "len", "(", "[", "info", "for", "info", "in", "infos", "if", "info", ".", "chosen", "]", ")", "*", "2", "==", "len", "(",...
Make sure each trial contains exactly one chosen info.
[ "Make", "sure", "each", "trial", "contains", "exactly", "one", "chosen", "info", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/mcmcp/experiment.py#L69-L72
Dallinger/Dallinger
demos/dlgr/demos/mcmcp/experiment.py
Bot.participate
def participate(self): """Finish reading and send text""" try: while True: left = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.ID, "left_button")) ) right = WebDriverWait(self.driver, 10).until( ...
python
def participate(self): """Finish reading and send text""" try: while True: left = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.ID, "left_button")) ) right = WebDriverWait(self.driver, 10).until( ...
[ "def", "participate", "(", "self", ")", ":", "try", ":", "while", "True", ":", "left", "=", "WebDriverWait", "(", "self", ".", "driver", ",", "10", ")", ".", "until", "(", "EC", ".", "element_to_be_clickable", "(", "(", "By", ".", "ID", ",", "\"left_...
Finish reading and send text
[ "Finish", "reading", "and", "send", "text" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/mcmcp/experiment.py#L107-L121
Dallinger/Dallinger
dallinger/data.py
find_experiment_export
def find_experiment_export(app_id): """Attempt to find a zipped export of an experiment with the ID provided and return its path. Returns None if not found. Search order: 1. local "data" subdirectory 2. user S3 bucket 3. Dallinger S3 bucket """ # Check locally first cwd...
python
def find_experiment_export(app_id): """Attempt to find a zipped export of an experiment with the ID provided and return its path. Returns None if not found. Search order: 1. local "data" subdirectory 2. user S3 bucket 3. Dallinger S3 bucket """ # Check locally first cwd...
[ "def", "find_experiment_export", "(", "app_id", ")", ":", "# Check locally first", "cwd", "=", "os", ".", "getcwd", "(", ")", "data_filename", "=", "\"{}-data.zip\"", ".", "format", "(", "app_id", ")", "path_to_data", "=", "os", ".", "path", ".", "join", "("...
Attempt to find a zipped export of an experiment with the ID provided and return its path. Returns None if not found. Search order: 1. local "data" subdirectory 2. user S3 bucket 3. Dallinger S3 bucket
[ "Attempt", "to", "find", "a", "zipped", "export", "of", "an", "experiment", "with", "the", "ID", "provided", "and", "return", "its", "path", ".", "Returns", "None", "if", "not", "found", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L53-L92
Dallinger/Dallinger
dallinger/data.py
load
def load(app_id): """Load the data from wherever it is found.""" path_to_data = find_experiment_export(app_id) if path_to_data is None: raise IOError("Dataset {} could not be found.".format(app_id)) return Data(path_to_data)
python
def load(app_id): """Load the data from wherever it is found.""" path_to_data = find_experiment_export(app_id) if path_to_data is None: raise IOError("Dataset {} could not be found.".format(app_id)) return Data(path_to_data)
[ "def", "load", "(", "app_id", ")", ":", "path_to_data", "=", "find_experiment_export", "(", "app_id", ")", "if", "path_to_data", "is", "None", ":", "raise", "IOError", "(", "\"Dataset {} could not be found.\"", ".", "format", "(", "app_id", ")", ")", "return", ...
Load the data from wherever it is found.
[ "Load", "the", "data", "from", "wherever", "it", "is", "found", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L95-L101
Dallinger/Dallinger
dallinger/data.py
dump_database
def dump_database(id): """Dump the database to a temporary directory.""" tmp_dir = tempfile.mkdtemp() current_dir = os.getcwd() os.chdir(tmp_dir) FNULL = open(os.devnull, "w") heroku_app = HerokuApp(dallinger_uid=id, output=FNULL) heroku_app.backup_capture() heroku_app.backup_download(...
python
def dump_database(id): """Dump the database to a temporary directory.""" tmp_dir = tempfile.mkdtemp() current_dir = os.getcwd() os.chdir(tmp_dir) FNULL = open(os.devnull, "w") heroku_app = HerokuApp(dallinger_uid=id, output=FNULL) heroku_app.backup_capture() heroku_app.backup_download(...
[ "def", "dump_database", "(", "id", ")", ":", "tmp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "current_dir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "tmp_dir", ")", "FNULL", "=", "open", "(", "os", ".", "devnull", ",", "\"...
Dump the database to a temporary directory.
[ "Dump", "the", "database", "to", "a", "temporary", "directory", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L104-L122
Dallinger/Dallinger
dallinger/data.py
backup
def backup(id): """Backup the database to S3.""" filename = dump_database(id) key = "{}.dump".format(id) bucket = user_s3_bucket() bucket.upload_file(filename, key) return _generate_s3_url(bucket, key)
python
def backup(id): """Backup the database to S3.""" filename = dump_database(id) key = "{}.dump".format(id) bucket = user_s3_bucket() bucket.upload_file(filename, key) return _generate_s3_url(bucket, key)
[ "def", "backup", "(", "id", ")", ":", "filename", "=", "dump_database", "(", "id", ")", "key", "=", "\"{}.dump\"", ".", "format", "(", "id", ")", "bucket", "=", "user_s3_bucket", "(", ")", "bucket", ".", "upload_file", "(", "filename", ",", "key", ")",...
Backup the database to S3.
[ "Backup", "the", "database", "to", "S3", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L125-L132
Dallinger/Dallinger
dallinger/data.py
register
def register(id, url=None): """Register a UUID key in the global S3 bucket.""" bucket = registration_s3_bucket() key = registration_key(id) obj = bucket.Object(key) obj.put(Body=url or "missing") return _generate_s3_url(bucket, key)
python
def register(id, url=None): """Register a UUID key in the global S3 bucket.""" bucket = registration_s3_bucket() key = registration_key(id) obj = bucket.Object(key) obj.put(Body=url or "missing") return _generate_s3_url(bucket, key)
[ "def", "register", "(", "id", ",", "url", "=", "None", ")", ":", "bucket", "=", "registration_s3_bucket", "(", ")", "key", "=", "registration_key", "(", "id", ")", "obj", "=", "bucket", ".", "Object", "(", "key", ")", "obj", ".", "put", "(", "Body", ...
Register a UUID key in the global S3 bucket.
[ "Register", "a", "UUID", "key", "in", "the", "global", "S3", "bucket", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L139-L145
Dallinger/Dallinger
dallinger/data.py
is_registered
def is_registered(id): """Check if a UUID is already registered""" bucket = registration_s3_bucket() key = registration_key(id) found_keys = set(obj.key for obj in bucket.objects.filter(Prefix=key)) return key in found_keys
python
def is_registered(id): """Check if a UUID is already registered""" bucket = registration_s3_bucket() key = registration_key(id) found_keys = set(obj.key for obj in bucket.objects.filter(Prefix=key)) return key in found_keys
[ "def", "is_registered", "(", "id", ")", ":", "bucket", "=", "registration_s3_bucket", "(", ")", "key", "=", "registration_key", "(", "id", ")", "found_keys", "=", "set", "(", "obj", ".", "key", "for", "obj", "in", "bucket", ".", "objects", ".", "filter",...
Check if a UUID is already registered
[ "Check", "if", "a", "UUID", "is", "already", "registered" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L148-L153
Dallinger/Dallinger
dallinger/data.py
copy_heroku_to_local
def copy_heroku_to_local(id): """Copy a Heroku database locally.""" heroku_app = HerokuApp(dallinger_uid=id) try: subprocess.call(["dropdb", heroku_app.name]) except Exception: pass heroku_app.pg_pull()
python
def copy_heroku_to_local(id): """Copy a Heroku database locally.""" heroku_app = HerokuApp(dallinger_uid=id) try: subprocess.call(["dropdb", heroku_app.name]) except Exception: pass heroku_app.pg_pull()
[ "def", "copy_heroku_to_local", "(", "id", ")", ":", "heroku_app", "=", "HerokuApp", "(", "dallinger_uid", "=", "id", ")", "try", ":", "subprocess", ".", "call", "(", "[", "\"dropdb\"", ",", "heroku_app", ".", "name", "]", ")", "except", "Exception", ":", ...
Copy a Heroku database locally.
[ "Copy", "a", "Heroku", "database", "locally", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L156-L164
Dallinger/Dallinger
dallinger/data.py
copy_db_to_csv
def copy_db_to_csv(dsn, path, scrub_pii=False): """Copy a local database to a set of CSV files.""" if "postgresql://" in dsn or "postgres://" in dsn: conn = psycopg2.connect(dsn=dsn) else: conn = psycopg2.connect(database=dsn, user="dallinger") cur = conn.cursor() for table in table_...
python
def copy_db_to_csv(dsn, path, scrub_pii=False): """Copy a local database to a set of CSV files.""" if "postgresql://" in dsn or "postgres://" in dsn: conn = psycopg2.connect(dsn=dsn) else: conn = psycopg2.connect(database=dsn, user="dallinger") cur = conn.cursor() for table in table_...
[ "def", "copy_db_to_csv", "(", "dsn", ",", "path", ",", "scrub_pii", "=", "False", ")", ":", "if", "\"postgresql://\"", "in", "dsn", "or", "\"postgres://\"", "in", "dsn", ":", "conn", "=", "psycopg2", ".", "connect", "(", "dsn", "=", "dsn", ")", "else", ...
Copy a local database to a set of CSV files.
[ "Copy", "a", "local", "database", "to", "a", "set", "of", "CSV", "files", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L167-L181
Dallinger/Dallinger
dallinger/data.py
_scrub_participant_table
def _scrub_participant_table(path_to_data): """Scrub PII from the given participant table.""" path = os.path.join(path_to_data, "participant.csv") with open_for_csv(path, "r") as input, open("{}.0".format(path), "w") as output: reader = csv.reader(input) writer = csv.writer(output) h...
python
def _scrub_participant_table(path_to_data): """Scrub PII from the given participant table.""" path = os.path.join(path_to_data, "participant.csv") with open_for_csv(path, "r") as input, open("{}.0".format(path), "w") as output: reader = csv.reader(input) writer = csv.writer(output) h...
[ "def", "_scrub_participant_table", "(", "path_to_data", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path_to_data", ",", "\"participant.csv\"", ")", "with", "open_for_csv", "(", "path", ",", "\"r\"", ")", "as", "input", ",", "open", "(", "\...
Scrub PII from the given participant table.
[ "Scrub", "PII", "from", "the", "given", "participant", "table", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L188-L203
Dallinger/Dallinger
dallinger/data.py
export
def export(id, local=False, scrub_pii=False): """Export data from an experiment.""" print("Preparing to export the data...") if local: db_uri = db.db_url else: db_uri = HerokuApp(id).db_uri # Create the data package if it doesn't already exist. subdata_path = os.path.join("dat...
python
def export(id, local=False, scrub_pii=False): """Export data from an experiment.""" print("Preparing to export the data...") if local: db_uri = db.db_url else: db_uri = HerokuApp(id).db_uri # Create the data package if it doesn't already exist. subdata_path = os.path.join("dat...
[ "def", "export", "(", "id", ",", "local", "=", "False", ",", "scrub_pii", "=", "False", ")", ":", "print", "(", "\"Preparing to export the data...\"", ")", "if", "local", ":", "db_uri", "=", "db", ".", "db_url", "else", ":", "db_uri", "=", "HerokuApp", "...
Export data from an experiment.
[ "Export", "data", "from", "an", "experiment", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L206-L263
Dallinger/Dallinger
dallinger/data.py
ingest_zip
def ingest_zip(path, engine=None): """Given a path to a zip file created with `export()`, recreate the database with the data stored in the included .csv files. """ import_order = [ "network", "participant", "node", "info", "notification", "question", ...
python
def ingest_zip(path, engine=None): """Given a path to a zip file created with `export()`, recreate the database with the data stored in the included .csv files. """ import_order = [ "network", "participant", "node", "info", "notification", "question", ...
[ "def", "ingest_zip", "(", "path", ",", "engine", "=", "None", ")", ":", "import_order", "=", "[", "\"network\"", ",", "\"participant\"", ",", "\"node\"", ",", "\"info\"", ",", "\"notification\"", ",", "\"question\"", ",", "\"transformation\"", ",", "\"vector\"",...
Given a path to a zip file created with `export()`, recreate the database with the data stored in the included .csv files.
[ "Given", "a", "path", "to", "a", "zip", "file", "created", "with", "export", "()", "recreate", "the", "database", "with", "the", "data", "stored", "in", "the", "included", ".", "csv", "files", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L266-L290
Dallinger/Dallinger
dallinger/data.py
ingest_to_model
def ingest_to_model(file, model, engine=None): """Load data from a CSV file handle into storage for a SQLAlchemy model class. """ if engine is None: engine = db.engine reader = csv.reader(file) columns = tuple('"{}"'.format(n) for n in next(reader)) postgres_copy.copy_from( f...
python
def ingest_to_model(file, model, engine=None): """Load data from a CSV file handle into storage for a SQLAlchemy model class. """ if engine is None: engine = db.engine reader = csv.reader(file) columns = tuple('"{}"'.format(n) for n in next(reader)) postgres_copy.copy_from( f...
[ "def", "ingest_to_model", "(", "file", ",", "model", ",", "engine", "=", "None", ")", ":", "if", "engine", "is", "None", ":", "engine", "=", "db", ".", "engine", "reader", "=", "csv", ".", "reader", "(", "file", ")", "columns", "=", "tuple", "(", "...
Load data from a CSV file handle into storage for a SQLAlchemy model class.
[ "Load", "data", "from", "a", "CSV", "file", "handle", "into", "storage", "for", "a", "SQLAlchemy", "model", "class", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L302-L313
Dallinger/Dallinger
dallinger/data.py
_get_or_create_s3_bucket
def _get_or_create_s3_bucket(s3, name): """Get an S3 bucket resource after making sure it exists""" exists = True try: s3.meta.client.head_bucket(Bucket=name) except botocore.exceptions.ClientError as e: error_code = int(e.response["Error"]["Code"]) if error_code == 404: ...
python
def _get_or_create_s3_bucket(s3, name): """Get an S3 bucket resource after making sure it exists""" exists = True try: s3.meta.client.head_bucket(Bucket=name) except botocore.exceptions.ClientError as e: error_code = int(e.response["Error"]["Code"]) if error_code == 404: ...
[ "def", "_get_or_create_s3_bucket", "(", "s3", ",", "name", ")", ":", "exists", "=", "True", "try", ":", "s3", ".", "meta", ".", "client", ".", "head_bucket", "(", "Bucket", "=", "name", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "a...
Get an S3 bucket resource after making sure it exists
[ "Get", "an", "S3", "bucket", "resource", "after", "making", "sure", "it", "exists" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L332-L347
Dallinger/Dallinger
dallinger/data.py
user_s3_bucket
def user_s3_bucket(canonical_user_id=None): """Get the user's S3 bucket.""" s3 = _s3_resource() if not canonical_user_id: canonical_user_id = _get_canonical_aws_user_id(s3) s3_bucket_name = "dallinger-{}".format( hashlib.sha256(canonical_user_id.encode("utf8")).hexdigest()[0:8] ) ...
python
def user_s3_bucket(canonical_user_id=None): """Get the user's S3 bucket.""" s3 = _s3_resource() if not canonical_user_id: canonical_user_id = _get_canonical_aws_user_id(s3) s3_bucket_name = "dallinger-{}".format( hashlib.sha256(canonical_user_id.encode("utf8")).hexdigest()[0:8] ) ...
[ "def", "user_s3_bucket", "(", "canonical_user_id", "=", "None", ")", ":", "s3", "=", "_s3_resource", "(", ")", "if", "not", "canonical_user_id", ":", "canonical_user_id", "=", "_get_canonical_aws_user_id", "(", "s3", ")", "s3_bucket_name", "=", "\"dallinger-{}\"", ...
Get the user's S3 bucket.
[ "Get", "the", "user", "s", "S3", "bucket", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L354-L364
Dallinger/Dallinger
dallinger/data.py
_s3_resource
def _s3_resource(dallinger_region=False): """A boto3 S3 resource using the AWS keys in the config.""" config = get_config() if not config.ready: config.load() region = "us-east-1" if dallinger_region else config.get("aws_region") return boto3.resource( "s3", region_name=regi...
python
def _s3_resource(dallinger_region=False): """A boto3 S3 resource using the AWS keys in the config.""" config = get_config() if not config.ready: config.load() region = "us-east-1" if dallinger_region else config.get("aws_region") return boto3.resource( "s3", region_name=regi...
[ "def", "_s3_resource", "(", "dallinger_region", "=", "False", ")", ":", "config", "=", "get_config", "(", ")", "if", "not", "config", ".", "ready", ":", "config", ".", "load", "(", ")", "region", "=", "\"us-east-1\"", "if", "dallinger_region", "else", "con...
A boto3 S3 resource using the AWS keys in the config.
[ "A", "boto3", "S3", "resource", "using", "the", "AWS", "keys", "in", "the", "config", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L379-L391
Dallinger/Dallinger
demos/dlgr/demos/iterated_drawing/models.py
DrawingSource._contents
def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.cho...
python
def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.cho...
[ "def", "_contents", "(", "self", ")", ":", "images", "=", "[", "\"owl.png\"", "]", "# We're selecting from a list of only one item here, but it's a useful", "# technique to demonstrate:", "image", "=", "random", ".", "choice", "(", "images", ")", "image_path", "=", "os"...
Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents().
[ "Define", "the", "contents", "of", "new", "Infos", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/iterated_drawing/models.py#L13-L30
Dallinger/Dallinger
dallinger/processes.py
transmit_by_fitness
def transmit_by_fitness(from_whom, to_whom=None, what=None): """Choose a parent with probability proportional to their fitness.""" parents = from_whom parent_fs = [p.fitness for p in parents] parent_probs = [(f / (1.0 * sum(parent_fs))) for f in parent_fs] rnd = random.random() temp = 0.0 f...
python
def transmit_by_fitness(from_whom, to_whom=None, what=None): """Choose a parent with probability proportional to their fitness.""" parents = from_whom parent_fs = [p.fitness for p in parents] parent_probs = [(f / (1.0 * sum(parent_fs))) for f in parent_fs] rnd = random.random() temp = 0.0 f...
[ "def", "transmit_by_fitness", "(", "from_whom", ",", "to_whom", "=", "None", ",", "what", "=", "None", ")", ":", "parents", "=", "from_whom", "parent_fs", "=", "[", "p", ".", "fitness", "for", "p", "in", "parents", "]", "parent_probs", "=", "[", "(", "...
Choose a parent with probability proportional to their fitness.
[ "Choose", "a", "parent", "with", "probability", "proportional", "to", "their", "fitness", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/processes.py#L82-L96
Dallinger/Dallinger
dallinger/notifications.py
get_messenger
def get_messenger(config): """Return an appropriate Messenger. If we're in debug mode, or email settings aren't set, return a debug version which logs the message instead of attempting to send a real email. """ email_settings = EmailConfig(config) if config.get("mode") == "debug": r...
python
def get_messenger(config): """Return an appropriate Messenger. If we're in debug mode, or email settings aren't set, return a debug version which logs the message instead of attempting to send a real email. """ email_settings = EmailConfig(config) if config.get("mode") == "debug": r...
[ "def", "get_messenger", "(", "config", ")", ":", "email_settings", "=", "EmailConfig", "(", "config", ")", "if", "config", ".", "get", "(", "\"mode\"", ")", "==", "\"debug\"", ":", "return", "DebugMessenger", "(", "email_settings", ")", "problems", "=", "ema...
Return an appropriate Messenger. If we're in debug mode, or email settings aren't set, return a debug version which logs the message instead of attempting to send a real email.
[ "Return", "an", "appropriate", "Messenger", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/notifications.py#L100-L114
Dallinger/Dallinger
dallinger/notifications.py
EmailConfig.validate
def validate(self): """Could this config be used to send a real email?""" missing = [] for k, v in self._map.items(): attr = getattr(self, k, False) if not attr or attr == CONFIG_PLACEHOLDER: missing.append(v) if missing: return "Missin...
python
def validate(self): """Could this config be used to send a real email?""" missing = [] for k, v in self._map.items(): attr = getattr(self, k, False) if not attr or attr == CONFIG_PLACEHOLDER: missing.append(v) if missing: return "Missin...
[ "def", "validate", "(", "self", ")", ":", "missing", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "_map", ".", "items", "(", ")", ":", "attr", "=", "getattr", "(", "self", ",", "k", ",", "False", ")", "if", "not", "attr", "or", "at...
Could this config be used to send a real email?
[ "Could", "this", "config", "be", "used", "to", "send", "a", "real", "email?" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/notifications.py#L42-L52
Dallinger/Dallinger
dallinger/db.py
sessions_scope
def sessions_scope(local_session, commit=False): """Provide a transactional scope around a series of operations.""" try: yield local_session if commit: local_session.commit() logger.debug("DB session auto-committed as requested") except Exception as e: # We lo...
python
def sessions_scope(local_session, commit=False): """Provide a transactional scope around a series of operations.""" try: yield local_session if commit: local_session.commit() logger.debug("DB session auto-committed as requested") except Exception as e: # We lo...
[ "def", "sessions_scope", "(", "local_session", ",", "commit", "=", "False", ")", ":", "try", ":", "yield", "local_session", "if", "commit", ":", "local_session", ".", "commit", "(", ")", "logger", ".", "debug", "(", "\"DB session auto-committed as requested\"", ...
Provide a transactional scope around a series of operations.
[ "Provide", "a", "transactional", "scope", "around", "a", "series", "of", "operations", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/db.py#L67-L85
Dallinger/Dallinger
dallinger/db.py
scoped_session_decorator
def scoped_session_decorator(func): """Manage contexts and add debugging to db sessions.""" @wraps(func) def wrapper(*args, **kwargs): with sessions_scope(session): # The session used in func comes from the funcs globals, but # it will be a proxied thread local var from the ...
python
def scoped_session_decorator(func): """Manage contexts and add debugging to db sessions.""" @wraps(func) def wrapper(*args, **kwargs): with sessions_scope(session): # The session used in func comes from the funcs globals, but # it will be a proxied thread local var from the ...
[ "def", "scoped_session_decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "sessions_scope", "(", "session", ")", ":", "# The session used in func comes from the func...
Manage contexts and add debugging to db sessions.
[ "Manage", "contexts", "and", "add", "debugging", "to", "db", "sessions", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/db.py#L88-L101
Dallinger/Dallinger
dallinger/db.py
init_db
def init_db(drop_all=False, bind=engine): """Initialize the database, optionally dropping existing tables.""" try: if drop_all: Base.metadata.drop_all(bind=bind) Base.metadata.create_all(bind=bind) except OperationalError as err: msg = 'password authentication failed for ...
python
def init_db(drop_all=False, bind=engine): """Initialize the database, optionally dropping existing tables.""" try: if drop_all: Base.metadata.drop_all(bind=bind) Base.metadata.create_all(bind=bind) except OperationalError as err: msg = 'password authentication failed for ...
[ "def", "init_db", "(", "drop_all", "=", "False", ",", "bind", "=", "engine", ")", ":", "try", ":", "if", "drop_all", ":", "Base", ".", "metadata", ".", "drop_all", "(", "bind", "=", "bind", ")", "Base", ".", "metadata", ".", "create_all", "(", "bind"...
Initialize the database, optionally dropping existing tables.
[ "Initialize", "the", "database", "optionally", "dropping", "existing", "tables", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/db.py#L104-L116
Dallinger/Dallinger
dallinger/db.py
serialized
def serialized(func): """Run a function within a db transaction using SERIALIZABLE isolation. With this isolation level, committing will fail if this transaction read data that was since modified by another transaction. So we need to handle that case and retry the transaction. """ @wraps(func)...
python
def serialized(func): """Run a function within a db transaction using SERIALIZABLE isolation. With this isolation level, committing will fail if this transaction read data that was since modified by another transaction. So we need to handle that case and retry the transaction. """ @wraps(func)...
[ "def", "serialized", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "attempts", "=", "100", "session", ".", "remove", "(", ")", "while", "attempts", ">", "0", ":", "try", ...
Run a function within a db transaction using SERIALIZABLE isolation. With this isolation level, committing will fail if this transaction read data that was since modified by another transaction. So we need to handle that case and retry the transaction.
[ "Run", "a", "function", "within", "a", "db", "transaction", "using", "SERIALIZABLE", "isolation", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/db.py#L119-L155
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
chat
def chat(ws): """Relay chat messages to and from clients. """ lag_tolerance_secs = float(request.args.get("tolerance", 0.1)) client = Client(ws, lag_tolerance_secs=lag_tolerance_secs) client.subscribe(request.args.get("channel")) gevent.spawn(client.heartbeat) client.publish()
python
def chat(ws): """Relay chat messages to and from clients. """ lag_tolerance_secs = float(request.args.get("tolerance", 0.1)) client = Client(ws, lag_tolerance_secs=lag_tolerance_secs) client.subscribe(request.args.get("channel")) gevent.spawn(client.heartbeat) client.publish()
[ "def", "chat", "(", "ws", ")", ":", "lag_tolerance_secs", "=", "float", "(", "request", ".", "args", ".", "get", "(", "\"tolerance\"", ",", "0.1", ")", ")", "client", "=", "Client", "(", "ws", ",", "lag_tolerance_secs", "=", "lag_tolerance_secs", ")", "c...
Relay chat messages to and from clients.
[ "Relay", "chat", "messages", "to", "and", "from", "clients", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L159-L166
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
Channel.subscribe
def subscribe(self, client): """Subscribe a client to the channel.""" self.clients.append(client) log("Subscribed client {} to channel {}".format(client, self.name))
python
def subscribe(self, client): """Subscribe a client to the channel.""" self.clients.append(client) log("Subscribed client {} to channel {}".format(client, self.name))
[ "def", "subscribe", "(", "self", ",", "client", ")", ":", "self", ".", "clients", ".", "append", "(", "client", ")", "log", "(", "\"Subscribed client {} to channel {}\"", ".", "format", "(", "client", ",", "self", ".", "name", ")", ")" ]
Subscribe a client to the channel.
[ "Subscribe", "a", "client", "to", "the", "channel", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L41-L44
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
Channel.unsubscribe
def unsubscribe(self, client): """Unsubscribe a client from the channel.""" if client in self.clients: self.clients.remove(client) log("Unsubscribed client {} from channel {}".format(client, self.name))
python
def unsubscribe(self, client): """Unsubscribe a client from the channel.""" if client in self.clients: self.clients.remove(client) log("Unsubscribed client {} from channel {}".format(client, self.name))
[ "def", "unsubscribe", "(", "self", ",", "client", ")", ":", "if", "client", "in", "self", ".", "clients", ":", "self", ".", "clients", ".", "remove", "(", "client", ")", "log", "(", "\"Unsubscribed client {} from channel {}\"", ".", "format", "(", "client", ...
Unsubscribe a client from the channel.
[ "Unsubscribe", "a", "client", "from", "the", "channel", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L46-L50
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
Channel.listen
def listen(self): """Relay messages from a redis pubsub to all subscribed clients. This is run continuously in a separate greenlet. """ pubsub = redis_conn.pubsub() name = self.name if isinstance(name, six.text_type): name = name.encode("utf-8") try: ...
python
def listen(self): """Relay messages from a redis pubsub to all subscribed clients. This is run continuously in a separate greenlet. """ pubsub = redis_conn.pubsub() name = self.name if isinstance(name, six.text_type): name = name.encode("utf-8") try: ...
[ "def", "listen", "(", "self", ")", ":", "pubsub", "=", "redis_conn", ".", "pubsub", "(", ")", "name", "=", "self", ".", "name", "if", "isinstance", "(", "name", ",", "six", ".", "text_type", ")", ":", "name", "=", "name", ".", "encode", "(", "\"utf...
Relay messages from a redis pubsub to all subscribed clients. This is run continuously in a separate greenlet.
[ "Relay", "messages", "from", "a", "redis", "pubsub", "to", "all", "subscribed", "clients", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L52-L73
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
ChatBackend.subscribe
def subscribe(self, client, channel_name): """Register a new client to receive messages on a channel.""" if channel_name not in self.channels: self.channels[channel_name] = channel = Channel(channel_name) channel.start() self.channels[channel_name].subscribe(client)
python
def subscribe(self, client, channel_name): """Register a new client to receive messages on a channel.""" if channel_name not in self.channels: self.channels[channel_name] = channel = Channel(channel_name) channel.start() self.channels[channel_name].subscribe(client)
[ "def", "subscribe", "(", "self", ",", "client", ",", "channel_name", ")", ":", "if", "channel_name", "not", "in", "self", ".", "channels", ":", "self", ".", "channels", "[", "channel_name", "]", "=", "channel", "=", "Channel", "(", "channel_name", ")", "...
Register a new client to receive messages on a channel.
[ "Register", "a", "new", "client", "to", "receive", "messages", "on", "a", "channel", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L92-L98
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
ChatBackend.unsubscribe
def unsubscribe(self, client): """Unsubscribe a client from all channels.""" for channel in self.channels.values(): channel.unsubscribe(client)
python
def unsubscribe(self, client): """Unsubscribe a client from all channels.""" for channel in self.channels.values(): channel.unsubscribe(client)
[ "def", "unsubscribe", "(", "self", ",", "client", ")", ":", "for", "channel", "in", "self", ".", "channels", ".", "values", "(", ")", ":", "channel", ".", "unsubscribe", "(", "client", ")" ]
Unsubscribe a client from all channels.
[ "Unsubscribe", "a", "client", "from", "all", "channels", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L100-L103
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
Client.send
def send(self, message): """Send a single message to the websocket.""" if isinstance(message, bytes): message = message.decode("utf8") with self.send_lock: try: self.ws.send(message) except socket.error: chat_backend.unsubscrib...
python
def send(self, message): """Send a single message to the websocket.""" if isinstance(message, bytes): message = message.decode("utf8") with self.send_lock: try: self.ws.send(message) except socket.error: chat_backend.unsubscrib...
[ "def", "send", "(", "self", ",", "message", ")", ":", "if", "isinstance", "(", "message", ",", "bytes", ")", ":", "message", "=", "message", ".", "decode", "(", "\"utf8\"", ")", "with", "self", ".", "send_lock", ":", "try", ":", "self", ".", "ws", ...
Send a single message to the websocket.
[ "Send", "a", "single", "message", "to", "the", "websocket", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L121-L130
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
Client.heartbeat
def heartbeat(self): """Send a ping to the websocket periodically. This is needed so that Heroku won't close the connection from inactivity. """ while not self.ws.closed: gevent.sleep(HEARTBEAT_DELAY) gevent.spawn(self.send, "ping")
python
def heartbeat(self): """Send a ping to the websocket periodically. This is needed so that Heroku won't close the connection from inactivity. """ while not self.ws.closed: gevent.sleep(HEARTBEAT_DELAY) gevent.spawn(self.send, "ping")
[ "def", "heartbeat", "(", "self", ")", ":", "while", "not", "self", ".", "ws", ".", "closed", ":", "gevent", ".", "sleep", "(", "HEARTBEAT_DELAY", ")", "gevent", ".", "spawn", "(", "self", ".", "send", ",", "\"ping\"", ")" ]
Send a ping to the websocket periodically. This is needed so that Heroku won't close the connection from inactivity.
[ "Send", "a", "ping", "to", "the", "websocket", "periodically", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L133-L141
Dallinger/Dallinger
dallinger/experiment_server/sockets.py
Client.publish
def publish(self): """Relay messages from client to redis.""" while not self.ws.closed: # Sleep to prevent *constant* context-switches. gevent.sleep(self.lag_tolerance_secs) message = self.ws.receive() if message is not None: channel_name, ...
python
def publish(self): """Relay messages from client to redis.""" while not self.ws.closed: # Sleep to prevent *constant* context-switches. gevent.sleep(self.lag_tolerance_secs) message = self.ws.receive() if message is not None: channel_name, ...
[ "def", "publish", "(", "self", ")", ":", "while", "not", "self", ".", "ws", ".", "closed", ":", "# Sleep to prevent *constant* context-switches.", "gevent", ".", "sleep", "(", "self", ".", "lag_tolerance_secs", ")", "message", "=", "self", ".", "ws", ".", "r...
Relay messages from client to redis.
[ "Relay", "messages", "from", "client", "to", "redis", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/sockets.py#L147-L155
Dallinger/Dallinger
dallinger/bots.py
BotBase.driver
def driver(self): """Returns a Selenium WebDriver instance of the type requested in the configuration.""" from dallinger.config import get_config config = get_config() if not config.ready: config.load() driver_url = config.get("webdriver_url", None) d...
python
def driver(self): """Returns a Selenium WebDriver instance of the type requested in the configuration.""" from dallinger.config import get_config config = get_config() if not config.ready: config.load() driver_url = config.get("webdriver_url", None) d...
[ "def", "driver", "(", "self", ")", ":", "from", "dallinger", ".", "config", "import", "get_config", "config", "=", "get_config", "(", ")", "if", "not", "config", ".", "ready", ":", "config", ".", "load", "(", ")", "driver_url", "=", "config", ".", "get...
Returns a Selenium WebDriver instance of the type requested in the configuration.
[ "Returns", "a", "Selenium", "WebDriver", "instance", "of", "the", "type", "requested", "in", "the", "configuration", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L68-L99
Dallinger/Dallinger
dallinger/bots.py
BotBase.sign_up
def sign_up(self): """Accept HIT, give consent and start experiment. This uses Selenium to click through buttons on the ad, consent, and instruction pages. """ try: self.driver.get(self.URL) logger.info("Loaded ad page.") begin = WebDriverWait...
python
def sign_up(self): """Accept HIT, give consent and start experiment. This uses Selenium to click through buttons on the ad, consent, and instruction pages. """ try: self.driver.get(self.URL) logger.info("Loaded ad page.") begin = WebDriverWait...
[ "def", "sign_up", "(", "self", ")", ":", "try", ":", "self", ".", "driver", ".", "get", "(", "self", ".", "URL", ")", "logger", ".", "info", "(", "\"Loaded ad page.\"", ")", "begin", "=", "WebDriverWait", "(", "self", ".", "driver", ",", "10", ")", ...
Accept HIT, give consent and start experiment. This uses Selenium to click through buttons on the ad, consent, and instruction pages.
[ "Accept", "HIT", "give", "consent", "and", "start", "experiment", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L101-L132
Dallinger/Dallinger
dallinger/bots.py
BotBase.complete_questionnaire
def complete_questionnaire(self): """Complete the standard debriefing form. Answers the questions in the base questionnaire. """ logger.info("Complete questionnaire.") difficulty = self.driver.find_element_by_id("difficulty") difficulty.value = "4" engagement = s...
python
def complete_questionnaire(self): """Complete the standard debriefing form. Answers the questions in the base questionnaire. """ logger.info("Complete questionnaire.") difficulty = self.driver.find_element_by_id("difficulty") difficulty.value = "4" engagement = s...
[ "def", "complete_questionnaire", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Complete questionnaire.\"", ")", "difficulty", "=", "self", ".", "driver", ".", "find_element_by_id", "(", "\"difficulty\"", ")", "difficulty", ".", "value", "=", "\"4\"", "en...
Complete the standard debriefing form. Answers the questions in the base questionnaire.
[ "Complete", "the", "standard", "debriefing", "form", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L142-L151
Dallinger/Dallinger
dallinger/bots.py
BotBase.sign_off
def sign_off(self): """Submit questionnaire and finish. This uses Selenium to click the submit button on the questionnaire and return to the original window. """ try: logger.info("Bot player signing off.") feedback = WebDriverWait(self.driver, 20).until( ...
python
def sign_off(self): """Submit questionnaire and finish. This uses Selenium to click the submit button on the questionnaire and return to the original window. """ try: logger.info("Bot player signing off.") feedback = WebDriverWait(self.driver, 20).until( ...
[ "def", "sign_off", "(", "self", ")", ":", "try", ":", "logger", ".", "info", "(", "\"Bot player signing off.\"", ")", "feedback", "=", "WebDriverWait", "(", "self", ".", "driver", ",", "20", ")", ".", "until", "(", "EC", ".", "presence_of_element_located", ...
Submit questionnaire and finish. This uses Selenium to click the submit button on the questionnaire and return to the original window.
[ "Submit", "questionnaire", "and", "finish", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L153-L173
Dallinger/Dallinger
dallinger/bots.py
BotBase.complete_experiment
def complete_experiment(self, status): """Sends worker status ('worker_complete' or 'worker_failed') to the experiment server. """ url = self.driver.current_url p = urllib.parse.urlparse(url) complete_url = "%s://%s/%s?participant_id=%s" complete_url = complete_ur...
python
def complete_experiment(self, status): """Sends worker status ('worker_complete' or 'worker_failed') to the experiment server. """ url = self.driver.current_url p = urllib.parse.urlparse(url) complete_url = "%s://%s/%s?participant_id=%s" complete_url = complete_ur...
[ "def", "complete_experiment", "(", "self", ",", "status", ")", ":", "url", "=", "self", ".", "driver", ".", "current_url", "p", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "complete_url", "=", "\"%s://%s/%s?participant_id=%s\"", "complete_ur...
Sends worker status ('worker_complete' or 'worker_failed') to the experiment server.
[ "Sends", "worker", "status", "(", "worker_complete", "or", "worker_failed", ")", "to", "the", "experiment", "server", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L175-L184
Dallinger/Dallinger
dallinger/bots.py
BotBase.run_experiment
def run_experiment(self): """Sign up, run the ``participate`` method, then sign off and close the driver.""" try: self.sign_up() self.participate() if self.sign_off(): self.complete_experiment("worker_complete") else: ...
python
def run_experiment(self): """Sign up, run the ``participate`` method, then sign off and close the driver.""" try: self.sign_up() self.participate() if self.sign_off(): self.complete_experiment("worker_complete") else: ...
[ "def", "run_experiment", "(", "self", ")", ":", "try", ":", "self", ".", "sign_up", "(", ")", "self", ".", "participate", "(", ")", "if", "self", ".", "sign_off", "(", ")", ":", "self", ".", "complete_experiment", "(", "\"worker_complete\"", ")", "else",...
Sign up, run the ``participate`` method, then sign off and close the driver.
[ "Sign", "up", "run", "the", "participate", "method", "then", "sign", "off", "and", "close", "the", "driver", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L186-L197
Dallinger/Dallinger
dallinger/bots.py
HighPerformanceBotBase.run_experiment
def run_experiment(self): """Runs the phases of interacting with the experiment including signup, participation, signoff, and recording completion. """ self.sign_up() self.participate() if self.sign_off(): self.complete_experiment("worker_complete") el...
python
def run_experiment(self): """Runs the phases of interacting with the experiment including signup, participation, signoff, and recording completion. """ self.sign_up() self.participate() if self.sign_off(): self.complete_experiment("worker_complete") el...
[ "def", "run_experiment", "(", "self", ")", ":", "self", ".", "sign_up", "(", ")", "self", ".", "participate", "(", ")", "if", "self", ".", "sign_off", "(", ")", ":", "self", ".", "complete_experiment", "(", "\"worker_complete\"", ")", "else", ":", "self"...
Runs the phases of interacting with the experiment including signup, participation, signoff, and recording completion.
[ "Runs", "the", "phases", "of", "interacting", "with", "the", "experiment", "including", "signup", "participation", "signoff", "and", "recording", "completion", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L215-L224
Dallinger/Dallinger
dallinger/bots.py
HighPerformanceBotBase.sign_up
def sign_up(self): """Signs up a participant for the experiment. This is done using a POST request to the /participant/ endpoint. """ self.log("Bot player signing up.") self.subscribe_to_quorum_channel() while True: url = ( "{host}/participant...
python
def sign_up(self): """Signs up a participant for the experiment. This is done using a POST request to the /participant/ endpoint. """ self.log("Bot player signing up.") self.subscribe_to_quorum_channel() while True: url = ( "{host}/participant...
[ "def", "sign_up", "(", "self", ")", ":", "self", ".", "log", "(", "\"Bot player signing up.\"", ")", "self", ".", "subscribe_to_quorum_channel", "(", ")", "while", "True", ":", "url", "=", "(", "\"{host}/participant/{self.worker_id}/\"", "\"{self.hit_id}/{self.assignm...
Signs up a participant for the experiment. This is done using a POST request to the /participant/ endpoint.
[ "Signs", "up", "a", "participant", "for", "the", "experiment", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L226-L256
Dallinger/Dallinger
dallinger/bots.py
HighPerformanceBotBase.complete_experiment
def complete_experiment(self, status): """Record worker completion status to the experiment server. This is done using a GET request to the /worker_complete or /worker_failed endpoints. """ self.log("Bot player completing experiment. Status: {}".format(status)) while Tru...
python
def complete_experiment(self, status): """Record worker completion status to the experiment server. This is done using a GET request to the /worker_complete or /worker_failed endpoints. """ self.log("Bot player completing experiment. Status: {}".format(status)) while Tru...
[ "def", "complete_experiment", "(", "self", ",", "status", ")", ":", "self", ".", "log", "(", "\"Bot player completing experiment. Status: {}\"", ".", "format", "(", "status", ")", ")", "while", "True", ":", "url", "=", "\"{host}/{status}?participant_id={participant_id...
Record worker completion status to the experiment server. This is done using a GET request to the /worker_complete or /worker_failed endpoints.
[ "Record", "worker", "completion", "status", "to", "the", "experiment", "server", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L266-L283
Dallinger/Dallinger
dallinger/bots.py
HighPerformanceBotBase.subscribe_to_quorum_channel
def subscribe_to_quorum_channel(self): """In case the experiment enforces a quorum, listen for notifications before creating Partipant objects. """ from dallinger.experiment_server.sockets import chat_backend self.log("Bot subscribing to quorum channel.") chat_backend.su...
python
def subscribe_to_quorum_channel(self): """In case the experiment enforces a quorum, listen for notifications before creating Partipant objects. """ from dallinger.experiment_server.sockets import chat_backend self.log("Bot subscribing to quorum channel.") chat_backend.su...
[ "def", "subscribe_to_quorum_channel", "(", "self", ")", ":", "from", "dallinger", ".", "experiment_server", ".", "sockets", "import", "chat_backend", "self", ".", "log", "(", "\"Bot subscribing to quorum channel.\"", ")", "chat_backend", ".", "subscribe", "(", "self",...
In case the experiment enforces a quorum, listen for notifications before creating Partipant objects.
[ "In", "case", "the", "experiment", "enforces", "a", "quorum", "listen", "for", "notifications", "before", "creating", "Partipant", "objects", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L289-L296
Dallinger/Dallinger
dallinger/bots.py
HighPerformanceBotBase.complete_questionnaire
def complete_questionnaire(self): """Complete the standard debriefing form. Answers the questions in the base questionnaire. """ while True: data = { "question": "questionnaire", "number": 1, "response": json.dumps(self.questio...
python
def complete_questionnaire(self): """Complete the standard debriefing form. Answers the questions in the base questionnaire. """ while True: data = { "question": "questionnaire", "number": 1, "response": json.dumps(self.questio...
[ "def", "complete_questionnaire", "(", "self", ")", ":", "while", "True", ":", "data", "=", "{", "\"question\"", ":", "\"questionnaire\"", ",", "\"number\"", ":", "1", ",", "\"response\"", ":", "json", ".", "dumps", "(", "self", ".", "question_responses", ")"...
Complete the standard debriefing form. Answers the questions in the base questionnaire.
[ "Complete", "the", "standard", "debriefing", "form", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/bots.py#L306-L326
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.check_credentials
def check_credentials(self): """Verifies key/secret/host combination by making a balance inquiry""" try: return bool(self.mturk.get_account_balance()) except NoCredentialsError: raise MTurkServiceException("No AWS credentials set!") except ClientError: ...
python
def check_credentials(self): """Verifies key/secret/host combination by making a balance inquiry""" try: return bool(self.mturk.get_account_balance()) except NoCredentialsError: raise MTurkServiceException("No AWS credentials set!") except ClientError: ...
[ "def", "check_credentials", "(", "self", ")", ":", "try", ":", "return", "bool", "(", "self", ".", "mturk", ".", "get_account_balance", "(", ")", ")", "except", "NoCredentialsError", ":", "raise", "MTurkServiceException", "(", "\"No AWS credentials set!\"", ")", ...
Verifies key/secret/host combination by making a balance inquiry
[ "Verifies", "key", "/", "secret", "/", "host", "combination", "by", "making", "a", "balance", "inquiry" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L87-L98
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.set_rest_notification
def set_rest_notification(self, url, hit_type_id): """Set a REST endpoint to recieve notifications about the HIT The newer AWS MTurk API does not support this feature, which means we cannot use boto3 here. Instead, we make the call manually after assembling a properly signed request. ...
python
def set_rest_notification(self, url, hit_type_id): """Set a REST endpoint to recieve notifications about the HIT The newer AWS MTurk API does not support this feature, which means we cannot use boto3 here. Instead, we make the call manually after assembling a properly signed request. ...
[ "def", "set_rest_notification", "(", "self", ",", "url", ",", "hit_type_id", ")", ":", "ISO8601", "=", "\"%Y-%m-%dT%H:%M:%SZ\"", "notification_version", "=", "\"2006-05-05\"", "API_version", "=", "\"2014-08-15\"", "data", "=", "{", "\"AWSAccessKeyId\"", ":", "self", ...
Set a REST endpoint to recieve notifications about the HIT The newer AWS MTurk API does not support this feature, which means we cannot use boto3 here. Instead, we make the call manually after assembling a properly signed request.
[ "Set", "a", "REST", "endpoint", "to", "recieve", "notifications", "about", "the", "HIT", "The", "newer", "AWS", "MTurk", "API", "does", "not", "support", "this", "feature", "which", "means", "we", "cannot", "use", "boto3", "here", ".", "Instead", "we", "ma...
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L100-L136
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.register_hit_type
def register_hit_type( self, title, description, reward, duration_hours, keywords, qualifications ): """Register HIT Type for this HIT and return the type's ID, which is required for creating a HIT. """ reward = str(reward) duration_secs = int(datetime.timedelta(hours...
python
def register_hit_type( self, title, description, reward, duration_hours, keywords, qualifications ): """Register HIT Type for this HIT and return the type's ID, which is required for creating a HIT. """ reward = str(reward) duration_secs = int(datetime.timedelta(hours...
[ "def", "register_hit_type", "(", "self", ",", "title", ",", "description", ",", "reward", ",", "duration_hours", ",", "keywords", ",", "qualifications", ")", ":", "reward", "=", "str", "(", "reward", ")", "duration_secs", "=", "int", "(", "datetime", ".", ...
Register HIT Type for this HIT and return the type's ID, which is required for creating a HIT.
[ "Register", "HIT", "Type", "for", "this", "HIT", "and", "return", "the", "type", "s", "ID", "which", "is", "required", "for", "creating", "a", "HIT", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L138-L156
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.build_hit_qualifications
def build_hit_qualifications(self, approve_requirement, restrict_to_usa, blacklist): """Translate restrictions/qualifications to boto Qualifications objects @blacklist is a list of names for Qualifications workers must not already hold in order to see and accept the HIT. """ qua...
python
def build_hit_qualifications(self, approve_requirement, restrict_to_usa, blacklist): """Translate restrictions/qualifications to boto Qualifications objects @blacklist is a list of names for Qualifications workers must not already hold in order to see and accept the HIT. """ qua...
[ "def", "build_hit_qualifications", "(", "self", ",", "approve_requirement", ",", "restrict_to_usa", ",", "blacklist", ")", ":", "quals", "=", "[", "{", "\"QualificationTypeId\"", ":", "PERCENTAGE_APPROVED_REQUIREMENT_ID", ",", "\"Comparator\"", ":", "\"GreaterThanOrEqualT...
Translate restrictions/qualifications to boto Qualifications objects @blacklist is a list of names for Qualifications workers must not already hold in order to see and accept the HIT.
[ "Translate", "restrictions", "/", "qualifications", "to", "boto", "Qualifications", "objects" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L158-L192
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.create_qualification_type
def create_qualification_type(self, name, description, status="Active"): """Create a new qualification Workers can be scored for. """ try: response = self.mturk.create_qualification_type( Name=name, Description=description, QualificationTypeStatus=status )...
python
def create_qualification_type(self, name, description, status="Active"): """Create a new qualification Workers can be scored for. """ try: response = self.mturk.create_qualification_type( Name=name, Description=description, QualificationTypeStatus=status )...
[ "def", "create_qualification_type", "(", "self", ",", "name", ",", "description", ",", "status", "=", "\"Active\"", ")", ":", "try", ":", "response", "=", "self", ".", "mturk", ".", "create_qualification_type", "(", "Name", "=", "name", ",", "Description", "...
Create a new qualification Workers can be scored for.
[ "Create", "a", "new", "qualification", "Workers", "can", "be", "scored", "for", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L194-L205
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_qualification_type_by_name
def get_qualification_type_by_name(self, name): """Return a Qualification Type by name. If the provided name matches more than one Qualification, check to see if any of the results match the provided name exactly. If there's an exact match, return that Qualification. Otherwise, raise an ...
python
def get_qualification_type_by_name(self, name): """Return a Qualification Type by name. If the provided name matches more than one Qualification, check to see if any of the results match the provided name exactly. If there's an exact match, return that Qualification. Otherwise, raise an ...
[ "def", "get_qualification_type_by_name", "(", "self", ",", "name", ")", ":", "max_fuzzy_matches_to_check", "=", "100", "query", "=", "name", ".", "upper", "(", ")", "start", "=", "time", ".", "time", "(", ")", "args", "=", "{", "\"Query\"", ":", "query", ...
Return a Qualification Type by name. If the provided name matches more than one Qualification, check to see if any of the results match the provided name exactly. If there's an exact match, return that Qualification. Otherwise, raise an exception.
[ "Return", "a", "Qualification", "Type", "by", "name", ".", "If", "the", "provided", "name", "matches", "more", "than", "one", "Qualification", "check", "to", "see", "if", "any", "of", "the", "results", "match", "the", "provided", "name", "exactly", ".", "I...
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L207-L240
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.assign_qualification
def assign_qualification(self, qualification_id, worker_id, score, notify=False): """Score a worker for a specific qualification""" return self._is_ok( self.mturk.associate_qualification_with_worker( QualificationTypeId=qualification_id, WorkerId=worker_id, ...
python
def assign_qualification(self, qualification_id, worker_id, score, notify=False): """Score a worker for a specific qualification""" return self._is_ok( self.mturk.associate_qualification_with_worker( QualificationTypeId=qualification_id, WorkerId=worker_id, ...
[ "def", "assign_qualification", "(", "self", ",", "qualification_id", ",", "worker_id", ",", "score", ",", "notify", "=", "False", ")", ":", "return", "self", ".", "_is_ok", "(", "self", ".", "mturk", ".", "associate_qualification_with_worker", "(", "Qualificatio...
Score a worker for a specific qualification
[ "Score", "a", "worker", "for", "a", "specific", "qualification" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L242-L251
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.increment_qualification_score
def increment_qualification_score(self, name, worker_id, notify=False): """Increment the current qualification score for a worker, on a qualification with the provided name. """ result = self.get_current_qualification_score(name, worker_id) current_score = result["score"] or 0 ...
python
def increment_qualification_score(self, name, worker_id, notify=False): """Increment the current qualification score for a worker, on a qualification with the provided name. """ result = self.get_current_qualification_score(name, worker_id) current_score = result["score"] or 0 ...
[ "def", "increment_qualification_score", "(", "self", ",", "name", ",", "worker_id", ",", "notify", "=", "False", ")", ":", "result", "=", "self", ".", "get_current_qualification_score", "(", "name", ",", "worker_id", ")", "current_score", "=", "result", "[", "...
Increment the current qualification score for a worker, on a qualification with the provided name.
[ "Increment", "the", "current", "qualification", "score", "for", "a", "worker", "on", "a", "qualification", "with", "the", "provided", "name", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L257-L267
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_qualification_score
def get_qualification_score(self, qualification_id, worker_id): """Return a worker's qualification score as an iteger. """ try: response = self.mturk.get_qualification_score( QualificationTypeId=qualification_id, WorkerId=worker_id ) except ClientE...
python
def get_qualification_score(self, qualification_id, worker_id): """Return a worker's qualification score as an iteger. """ try: response = self.mturk.get_qualification_score( QualificationTypeId=qualification_id, WorkerId=worker_id ) except ClientE...
[ "def", "get_qualification_score", "(", "self", ",", "qualification_id", ",", "worker_id", ")", ":", "try", ":", "response", "=", "self", ".", "mturk", ".", "get_qualification_score", "(", "QualificationTypeId", "=", "qualification_id", ",", "WorkerId", "=", "worke...
Return a worker's qualification score as an iteger.
[ "Return", "a", "worker", "s", "qualification", "score", "as", "an", "iteger", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L276-L299
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_current_qualification_score
def get_current_qualification_score(self, name, worker_id): """Return the current score for a worker, on a qualification with the provided name. """ qtype = self.get_qualification_type_by_name(name) if qtype is None: raise QualificationNotFoundException( ...
python
def get_current_qualification_score(self, name, worker_id): """Return the current score for a worker, on a qualification with the provided name. """ qtype = self.get_qualification_type_by_name(name) if qtype is None: raise QualificationNotFoundException( ...
[ "def", "get_current_qualification_score", "(", "self", ",", "name", ",", "worker_id", ")", ":", "qtype", "=", "self", ".", "get_qualification_type_by_name", "(", "name", ")", "if", "qtype", "is", "None", ":", "raise", "QualificationNotFoundException", "(", "'No Qu...
Return the current score for a worker, on a qualification with the provided name.
[ "Return", "the", "current", "score", "for", "a", "worker", "on", "a", "qualification", "with", "the", "provided", "name", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L301-L315
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.dispose_qualification_type
def dispose_qualification_type(self, qualification_id): """Remove a qualification type we created""" return self._is_ok( self.mturk.delete_qualification_type(QualificationTypeId=qualification_id) )
python
def dispose_qualification_type(self, qualification_id): """Remove a qualification type we created""" return self._is_ok( self.mturk.delete_qualification_type(QualificationTypeId=qualification_id) )
[ "def", "dispose_qualification_type", "(", "self", ",", "qualification_id", ")", ":", "return", "self", ".", "_is_ok", "(", "self", ".", "mturk", ".", "delete_qualification_type", "(", "QualificationTypeId", "=", "qualification_id", ")", ")" ]
Remove a qualification type we created
[ "Remove", "a", "qualification", "type", "we", "created" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L317-L321
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_workers_with_qualification
def get_workers_with_qualification(self, qualification_id): """Get workers with the given qualification.""" done = False next_token = None while not done: if next_token is not None: response = self.mturk.list_workers_with_qualification_type( ...
python
def get_workers_with_qualification(self, qualification_id): """Get workers with the given qualification.""" done = False next_token = None while not done: if next_token is not None: response = self.mturk.list_workers_with_qualification_type( ...
[ "def", "get_workers_with_qualification", "(", "self", ",", "qualification_id", ")", ":", "done", "=", "False", "next_token", "=", "None", "while", "not", "done", ":", "if", "next_token", "is", "not", "None", ":", "response", "=", "self", ".", "mturk", ".", ...
Get workers with the given qualification.
[ "Get", "workers", "with", "the", "given", "qualification", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L323-L347
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.create_hit
def create_hit( self, title, description, keywords, reward, duration_hours, lifetime_days, ad_url, notification_url, approve_requirement, max_assignments, us_only, blacklist=None, annotation=None, ): ...
python
def create_hit( self, title, description, keywords, reward, duration_hours, lifetime_days, ad_url, notification_url, approve_requirement, max_assignments, us_only, blacklist=None, annotation=None, ): ...
[ "def", "create_hit", "(", "self", ",", "title", ",", "description", ",", "keywords", ",", "reward", ",", "duration_hours", ",", "lifetime_days", ",", "ad_url", ",", "notification_url", ",", "approve_requirement", ",", "max_assignments", ",", "us_only", ",", "bla...
Create the actual HIT and return a dict with its useful properties.
[ "Create", "the", "actual", "HIT", "and", "return", "a", "dict", "with", "its", "useful", "properties", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L349-L392
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.extend_hit
def extend_hit(self, hit_id, number, duration_hours=None): """Extend an existing HIT and return an updated description""" self.create_additional_assignments_for_hit(hit_id, number) if duration_hours is not None: self.update_expiration_for_hit(hit_id, duration_hours) return ...
python
def extend_hit(self, hit_id, number, duration_hours=None): """Extend an existing HIT and return an updated description""" self.create_additional_assignments_for_hit(hit_id, number) if duration_hours is not None: self.update_expiration_for_hit(hit_id, duration_hours) return ...
[ "def", "extend_hit", "(", "self", ",", "hit_id", ",", "number", ",", "duration_hours", "=", "None", ")", ":", "self", ".", "create_additional_assignments_for_hit", "(", "hit_id", ",", "number", ")", "if", "duration_hours", "is", "not", "None", ":", "self", "...
Extend an existing HIT and return an updated description
[ "Extend", "an", "existing", "HIT", "and", "return", "an", "updated", "description" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L394-L401
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.expire_hit
def expire_hit(self, hit_id): """Expire a HIT, which will change its status to "Reviewable", allowing it to be deleted. """ try: self.mturk.update_expiration_for_hit(HITId=hit_id, ExpireAt=0) except Exception as ex: raise MTurkServiceException( ...
python
def expire_hit(self, hit_id): """Expire a HIT, which will change its status to "Reviewable", allowing it to be deleted. """ try: self.mturk.update_expiration_for_hit(HITId=hit_id, ExpireAt=0) except Exception as ex: raise MTurkServiceException( ...
[ "def", "expire_hit", "(", "self", ",", "hit_id", ")", ":", "try", ":", "self", ".", "mturk", ".", "update_expiration_for_hit", "(", "HITId", "=", "hit_id", ",", "ExpireAt", "=", "0", ")", "except", "Exception", "as", "ex", ":", "raise", "MTurkServiceExcept...
Expire a HIT, which will change its status to "Reviewable", allowing it to be deleted.
[ "Expire", "a", "HIT", "which", "will", "change", "its", "status", "to", "Reviewable", "allowing", "it", "to", "be", "deleted", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L442-L452
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.grant_bonus
def grant_bonus(self, assignment_id, amount, reason): """Grant a bonus to the MTurk Worker. Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or re...
python
def grant_bonus(self, assignment_id, amount, reason): """Grant a bonus to the MTurk Worker. Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or re...
[ "def", "grant_bonus", "(", "self", ",", "assignment_id", ",", "amount", ",", "reason", ")", ":", "assignment", "=", "self", ".", "get_assignment", "(", "assignment_id", ")", "worker_id", "=", "assignment", "[", "\"worker_id\"", "]", "amount_str", "=", "\"{:.2f...
Grant a bonus to the MTurk Worker. Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or rejected. This payment happens separately from the reward y...
[ "Grant", "a", "bonus", "to", "the", "MTurk", "Worker", ".", "Issues", "a", "payment", "of", "money", "from", "your", "account", "to", "a", "Worker", ".", "To", "be", "eligible", "for", "a", "bonus", "the", "Worker", "must", "have", "submitted", "results"...
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L476-L502
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_assignment
def get_assignment(self, assignment_id): """Get an assignment by ID and reformat the response. """ try: response = self.mturk.get_assignment(AssignmentId=assignment_id) except ClientError as ex: if "does not exist" in str(ex): return None ...
python
def get_assignment(self, assignment_id): """Get an assignment by ID and reformat the response. """ try: response = self.mturk.get_assignment(AssignmentId=assignment_id) except ClientError as ex: if "does not exist" in str(ex): return None ...
[ "def", "get_assignment", "(", "self", ",", "assignment_id", ")", ":", "try", ":", "response", "=", "self", ".", "mturk", ".", "get_assignment", "(", "AssignmentId", "=", "assignment_id", ")", "except", "ClientError", "as", "ex", ":", "if", "\"does not exist\""...
Get an assignment by ID and reformat the response.
[ "Get", "an", "assignment", "by", "ID", "and", "reformat", "the", "response", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L504-L513
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.approve_assignment
def approve_assignment(self, assignment_id): """Approving an assignment initiates two payments from the Requester's Amazon.com account: 1. The Worker who submitted the results is paid the reward specified in the HIT. 2. Amazon Mechanical Turk fees are debited. ...
python
def approve_assignment(self, assignment_id): """Approving an assignment initiates two payments from the Requester's Amazon.com account: 1. The Worker who submitted the results is paid the reward specified in the HIT. 2. Amazon Mechanical Turk fees are debited. ...
[ "def", "approve_assignment", "(", "self", ",", "assignment_id", ")", ":", "try", ":", "return", "self", ".", "_is_ok", "(", "self", ".", "mturk", ".", "approve_assignment", "(", "AssignmentId", "=", "assignment_id", ")", ")", "except", "ClientError", "as", "...
Approving an assignment initiates two payments from the Requester's Amazon.com account: 1. The Worker who submitted the results is paid the reward specified in the HIT. 2. Amazon Mechanical Turk fees are debited.
[ "Approving", "an", "assignment", "initiates", "two", "payments", "from", "the", "Requester", "s", "Amazon", ".", "com", "account", ":", "1", ".", "The", "Worker", "who", "submitted", "the", "results", "is", "paid", "the", "reward", "specified", "in", "the", ...
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L515-L532
Dallinger/Dallinger
dallinger/config.py
initialize_experiment_package
def initialize_experiment_package(path): """Make the specified directory importable as the `dallinger_experiment` package.""" # Create __init__.py if it doesn't exist (needed for Python 2) init_py = os.path.join(path, "__init__.py") if not os.path.exists(init_py): open(init_py, "a").close() ...
python
def initialize_experiment_package(path): """Make the specified directory importable as the `dallinger_experiment` package.""" # Create __init__.py if it doesn't exist (needed for Python 2) init_py = os.path.join(path, "__init__.py") if not os.path.exists(init_py): open(init_py, "a").close() ...
[ "def", "initialize_experiment_package", "(", "path", ")", ":", "# Create __init__.py if it doesn't exist (needed for Python 2)", "init_py", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"__init__.py\"", ")", "if", "not", "os", ".", "path", ".", "exists", ...
Make the specified directory importable as the `dallinger_experiment` package.
[ "Make", "the", "specified", "directory", "importable", "as", "the", "dallinger_experiment", "package", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/config.py#L270-L288
Dallinger/Dallinger
dallinger/models.py
Participant.json_data
def json_data(self): """Return json description of a participant.""" return { "type": self.type, "recruiter": self.recruiter_id, "assignment_id": self.assignment_id, "hit_id": self.hit_id, "mode": self.mode, "end_time": self.end_tim...
python
def json_data(self): """Return json description of a participant.""" return { "type": self.type, "recruiter": self.recruiter_id, "assignment_id": self.assignment_id, "hit_id": self.hit_id, "mode": self.mode, "end_time": self.end_tim...
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"type\"", ":", "self", ".", "type", ",", "\"recruiter\"", ":", "self", ".", "recruiter_id", ",", "\"assignment_id\"", ":", "self", ".", "assignment_id", ",", "\"hit_id\"", ":", "self", ".", "hit_i...
Return json description of a participant.
[ "Return", "json", "description", "of", "a", "participant", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L180-L192
Dallinger/Dallinger
dallinger/models.py
Participant.questions
def questions(self, type=None): """Get questions associated with this participant. Return a list of questions associated with the participant. If specified, ``type`` filters by class. """ if type is None: type = Question if not issubclass(type, Question): ...
python
def questions(self, type=None): """Get questions associated with this participant. Return a list of questions associated with the participant. If specified, ``type`` filters by class. """ if type is None: type = Question if not issubclass(type, Question): ...
[ "def", "questions", "(", "self", ",", "type", "=", "None", ")", ":", "if", "type", "is", "None", ":", "type", "=", "Question", "if", "not", "issubclass", "(", "type", ",", "Question", ")", ":", "raise", "TypeError", "(", "\"{} is not a valid question type....
Get questions associated with this participant. Return a list of questions associated with the participant. If specified, ``type`` filters by class.
[ "Get", "questions", "associated", "with", "this", "participant", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L217-L230
Dallinger/Dallinger
dallinger/models.py
Participant.infos
def infos(self, type=None, failed=False): """Get all infos created by the participants nodes. Return a list of infos produced by nodes associated with the participant. If specified, ``type`` filters by class. By default, failed infos are excluded, to include only failed nodes use ``fail...
python
def infos(self, type=None, failed=False): """Get all infos created by the participants nodes. Return a list of infos produced by nodes associated with the participant. If specified, ``type`` filters by class. By default, failed infos are excluded, to include only failed nodes use ``fail...
[ "def", "infos", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "nodes", "=", "self", ".", "nodes", "(", "failed", "=", "\"all\"", ")", "infos", "=", "[", "]", "for", "n", "in", "nodes", ":", "infos", ".", "extend", ...
Get all infos created by the participants nodes. Return a list of infos produced by nodes associated with the participant. If specified, ``type`` filters by class. By default, failed infos are excluded, to include only failed nodes use ``failed=True``, for all nodes use ``failed=all``. ...
[ "Get", "all", "infos", "created", "by", "the", "participants", "nodes", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L232-L247
Dallinger/Dallinger
dallinger/models.py
Question.json_data
def json_data(self): """Return json description of a question.""" return { "number": self.number, "type": self.type, "participant_id": self.participant_id, "question": self.question, "response": self.response, }
python
def json_data(self): """Return json description of a question.""" return { "number": self.number, "type": self.type, "participant_id": self.participant_id, "question": self.question, "response": self.response, }
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"number\"", ":", "self", ".", "number", ",", "\"type\"", ":", "self", ".", "type", ",", "\"participant_id\"", ":", "self", ".", "participant_id", ",", "\"question\"", ":", "self", ".", "question",...
Return json description of a question.
[ "Return", "json", "description", "of", "a", "question", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L332-L340
Dallinger/Dallinger
dallinger/models.py
Network.json_data
def json_data(self): """Return json description of a participant.""" return { "type": self.type, "max_size": self.max_size, "full": self.full, "role": self.role, }
python
def json_data(self): """Return json description of a participant.""" return { "type": self.type, "max_size": self.max_size, "full": self.full, "role": self.role, }
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"type\"", ":", "self", ".", "type", ",", "\"max_size\"", ":", "self", ".", "max_size", ",", "\"full\"", ":", "self", ".", "full", ",", "\"role\"", ":", "self", ".", "role", ",", "}" ]
Return json description of a participant.
[ "Return", "json", "description", "of", "a", "participant", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L380-L387
Dallinger/Dallinger
dallinger/models.py
Network.nodes
def nodes(self, type=None, failed=False, participant_id=None): """Get nodes in the network. type specifies the type of Node. Failed can be "all", False (default) or True. If a participant_id is passed only nodes with that participant_id will be returned. """ if type is N...
python
def nodes(self, type=None, failed=False, participant_id=None): """Get nodes in the network. type specifies the type of Node. Failed can be "all", False (default) or True. If a participant_id is passed only nodes with that participant_id will be returned. """ if type is N...
[ "def", "nodes", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ",", "participant_id", "=", "None", ")", ":", "if", "type", "is", "None", ":", "type", "=", "Node", "if", "not", "issubclass", "(", "type", ",", "Node", ")", ":", ...
Get nodes in the network. type specifies the type of Node. Failed can be "all", False (default) or True. If a participant_id is passed only nodes with that participant_id will be returned.
[ "Get", "nodes", "in", "the", "network", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L393-L422
Dallinger/Dallinger
dallinger/models.py
Network.size
def size(self, type=None, failed=False): """How many nodes in a network. type specifies the class of node, failed can be True/False/all. """ return len(self.nodes(type=type, failed=failed))
python
def size(self, type=None, failed=False): """How many nodes in a network. type specifies the class of node, failed can be True/False/all. """ return len(self.nodes(type=type, failed=failed))
[ "def", "size", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "return", "len", "(", "self", ".", "nodes", "(", "type", "=", "type", ",", "failed", "=", "failed", ")", ")" ]
How many nodes in a network. type specifies the class of node, failed can be True/False/all.
[ "How", "many", "nodes", "in", "a", "network", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L424-L430
Dallinger/Dallinger
dallinger/models.py
Network.infos
def infos(self, type=None, failed=False): """ Get infos in the network. type specifies the type of info (defaults to Info). failed { False, True, "all" } specifies the failed state of the infos. To get infos from a specific node, see the infos() method in class :class:`~...
python
def infos(self, type=None, failed=False): """ Get infos in the network. type specifies the type of info (defaults to Info). failed { False, True, "all" } specifies the failed state of the infos. To get infos from a specific node, see the infos() method in class :class:`~...
[ "def", "infos", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "if", "type", "is", "None", ":", "type", "=", "Info", "if", "failed", "not", "in", "[", "\"all\"", ",", "False", ",", "True", "]", ":", "raise", "ValueE...
Get infos in the network. type specifies the type of info (defaults to Info). failed { False, True, "all" } specifies the failed state of the infos. To get infos from a specific node, see the infos() method in class :class:`~dallinger.models.Node`.
[ "Get", "infos", "in", "the", "network", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L432-L450
Dallinger/Dallinger
dallinger/models.py
Network.transmissions
def transmissions(self, status="all", failed=False): """Get transmissions in the network. status { "all", "received", "pending" } failed { False, True, "all" } To get transmissions from a specific vector, see the transmissions() method in class Vector. """ if sta...
python
def transmissions(self, status="all", failed=False): """Get transmissions in the network. status { "all", "received", "pending" } failed { False, True, "all" } To get transmissions from a specific vector, see the transmissions() method in class Vector. """ if sta...
[ "def", "transmissions", "(", "self", ",", "status", "=", "\"all\"", ",", "failed", "=", "False", ")", ":", "if", "status", "not", "in", "[", "\"all\"", ",", "\"pending\"", ",", "\"received\"", "]", ":", "raise", "ValueError", "(", "\"You cannot get transmiss...
Get transmissions in the network. status { "all", "received", "pending" } failed { False, True, "all" } To get transmissions from a specific vector, see the transmissions() method in class Vector.
[ "Get", "transmissions", "in", "the", "network", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L452-L483
Dallinger/Dallinger
dallinger/models.py
Network.vectors
def vectors(self, failed=False): """ Get vectors in the network. failed = { False, True, "all" } To get the vectors to/from to a specific node, see Node.vectors(). """ if failed not in ["all", False, True]: raise ValueError("{} is not a valid vector failed".f...
python
def vectors(self, failed=False): """ Get vectors in the network. failed = { False, True, "all" } To get the vectors to/from to a specific node, see Node.vectors(). """ if failed not in ["all", False, True]: raise ValueError("{} is not a valid vector failed".f...
[ "def", "vectors", "(", "self", ",", "failed", "=", "False", ")", ":", "if", "failed", "not", "in", "[", "\"all\"", ",", "False", ",", "True", "]", ":", "raise", "ValueError", "(", "\"{} is not a valid vector failed\"", ".", "format", "(", "failed", ")", ...
Get vectors in the network. failed = { False, True, "all" } To get the vectors to/from to a specific node, see Node.vectors().
[ "Get", "vectors", "in", "the", "network", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L519-L532
Dallinger/Dallinger
dallinger/models.py
Node.neighbors
def neighbors(self, type=None, direction="to", failed=None): """Get a node's neighbors - nodes that are directly connected to it. Type specifies the class of neighbour and must be a subclass of Node (default is Node). Connection is the direction of the connections and can be "to" ...
python
def neighbors(self, type=None, direction="to", failed=None): """Get a node's neighbors - nodes that are directly connected to it. Type specifies the class of neighbour and must be a subclass of Node (default is Node). Connection is the direction of the connections and can be "to" ...
[ "def", "neighbors", "(", "self", ",", "type", "=", "None", ",", "direction", "=", "\"to\"", ",", "failed", "=", "None", ")", ":", "# get type", "if", "type", "is", "None", ":", "type", "=", "Node", "if", "not", "issubclass", "(", "type", ",", "Node",...
Get a node's neighbors - nodes that are directly connected to it. Type specifies the class of neighbour and must be a subclass of Node (default is Node). Connection is the direction of the connections and can be "to" (default), "from", "either", or "both".
[ "Get", "a", "node", "s", "neighbors", "-", "nodes", "that", "are", "directly", "connected", "to", "it", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L692-L769
Dallinger/Dallinger
dallinger/models.py
Node.is_connected
def is_connected(self, whom, direction="to", failed=None): """Check whether this node is connected [to/from] whom. whom can be a list of nodes or a single node. direction can be "to" (default), "from", "both" or "either". If whom is a single node this method returns a boolean, ...
python
def is_connected(self, whom, direction="to", failed=None): """Check whether this node is connected [to/from] whom. whom can be a list of nodes or a single node. direction can be "to" (default), "from", "both" or "either". If whom is a single node this method returns a boolean, ...
[ "def", "is_connected", "(", "self", ",", "whom", ",", "direction", "=", "\"to\"", ",", "failed", "=", "None", ")", ":", "if", "failed", "is", "not", "None", ":", "raise", "ValueError", "(", "\"You should not pass a failed argument to is_connected.\"", "\"is_connec...
Check whether this node is connected [to/from] whom. whom can be a list of nodes or a single node. direction can be "to" (default), "from", "both" or "either". If whom is a single node this method returns a boolean, otherwise it returns a list of booleans
[ "Check", "whether", "this", "node", "is", "connected", "[", "to", "/", "from", "]", "whom", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L771-L867
Dallinger/Dallinger
dallinger/models.py
Node.infos
def infos(self, type=None, failed=False): """Get infos that originate from this node. Type must be a subclass of :class:`~dallinger.models.Info`, the default is ``Info``. Failed can be True, False or "all". """ if type is None: type = Info if not issubclass...
python
def infos(self, type=None, failed=False): """Get infos that originate from this node. Type must be a subclass of :class:`~dallinger.models.Info`, the default is ``Info``. Failed can be True, False or "all". """ if type is None: type = Info if not issubclass...
[ "def", "infos", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "if", "type", "is", "None", ":", "type", "=", "Info", "if", "not", "issubclass", "(", "type", ",", "Info", ")", ":", "raise", "TypeError", "(", "\"Cannot ...
Get infos that originate from this node. Type must be a subclass of :class:`~dallinger.models.Info`, the default is ``Info``. Failed can be True, False or "all".
[ "Get", "infos", "that", "originate", "from", "this", "node", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L869-L890
Dallinger/Dallinger
dallinger/models.py
Node.received_infos
def received_infos(self, type=None, failed=None): """Get infos that have been sent to this node. Type must be a subclass of info, the default is Info. """ if failed is not None: raise ValueError( "You should not pass a failed argument to received_infos. " ...
python
def received_infos(self, type=None, failed=None): """Get infos that have been sent to this node. Type must be a subclass of info, the default is Info. """ if failed is not None: raise ValueError( "You should not pass a failed argument to received_infos. " ...
[ "def", "received_infos", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "None", ")", ":", "if", "failed", "is", "not", "None", ":", "raise", "ValueError", "(", "\"You should not pass a failed argument to received_infos. \"", "\"received_infos is \"", "\"...
Get infos that have been sent to this node. Type must be a subclass of info, the default is Info.
[ "Get", "infos", "that", "have", "been", "sent", "to", "this", "node", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L892-L927
Dallinger/Dallinger
dallinger/models.py
Node.transformations
def transformations(self, type=None, failed=False): """ Get Transformations done by this Node. type must be a type of Transformation (defaults to Transformation) Failed can be True, False or "all" """ if failed not in ["all", False, True]: raise ValueError("{...
python
def transformations(self, type=None, failed=False): """ Get Transformations done by this Node. type must be a type of Transformation (defaults to Transformation) Failed can be True, False or "all" """ if failed not in ["all", False, True]: raise ValueError("{...
[ "def", "transformations", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "if", "failed", "not", "in", "[", "\"all\"", ",", "False", ",", "True", "]", ":", "raise", "ValueError", "(", "\"{} is not a valid transmission failed\"",...
Get Transformations done by this Node. type must be a type of Transformation (defaults to Transformation) Failed can be True, False or "all"
[ "Get", "Transformations", "done", "by", "this", "Node", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1022-L1038
Dallinger/Dallinger
dallinger/models.py
Node.fail
def fail(self): """ Fail a node, setting its status to "failed". Also fails all vectors that connect to or from the node. You cannot fail a node that has already failed, but you can fail a dead node. Set node.failed to True and :attr:`~dallinger.models.Node.time_of_deat...
python
def fail(self): """ Fail a node, setting its status to "failed". Also fails all vectors that connect to or from the node. You cannot fail a node that has already failed, but you can fail a dead node. Set node.failed to True and :attr:`~dallinger.models.Node.time_of_deat...
[ "def", "fail", "(", "self", ")", ":", "if", "self", ".", "failed", "is", "True", ":", "raise", "AttributeError", "(", "\"Cannot fail {} - it has already failed.\"", ".", "format", "(", "self", ")", ")", "else", ":", "self", ".", "failed", "=", "True", "sel...
Fail a node, setting its status to "failed". Also fails all vectors that connect to or from the node. You cannot fail a node that has already failed, but you can fail a dead node. Set node.failed to True and :attr:`~dallinger.models.Node.time_of_death` to now. Instruct all not-...
[ "Fail", "a", "node", "setting", "its", "status", "to", "failed", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1044-L1072
Dallinger/Dallinger
dallinger/models.py
Node.connect
def connect(self, whom, direction="to"): """Create a vector from self to/from whom. Return a list of newly created vector between the node and whom. ``whom`` can be a specific node or a (nested) list of nodes. Nodes can only connect with nodes in the same network. In addition nodes cann...
python
def connect(self, whom, direction="to"): """Create a vector from self to/from whom. Return a list of newly created vector between the node and whom. ``whom`` can be a specific node or a (nested) list of nodes. Nodes can only connect with nodes in the same network. In addition nodes cann...
[ "def", "connect", "(", "self", ",", "whom", ",", "direction", "=", "\"to\"", ")", ":", "# check direction", "if", "direction", "not", "in", "[", "\"to\"", ",", "\"from\"", ",", "\"both\"", "]", ":", "raise", "ValueError", "(", "\"{} is not a valid direction fo...
Create a vector from self to/from whom. Return a list of newly created vector between the node and whom. ``whom`` can be a specific node or a (nested) list of nodes. Nodes can only connect with nodes in the same network. In addition nodes cannot connect with themselves or with Sources. ...
[ "Create", "a", "vector", "from", "self", "to", "/", "from", "whom", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1074-L1134
Dallinger/Dallinger
dallinger/models.py
Node.flatten
def flatten(self, lst): """Turn a list of lists into a list.""" if lst == []: return lst if isinstance(lst[0], list): return self.flatten(lst[0]) + self.flatten(lst[1:]) return lst[:1] + self.flatten(lst[1:])
python
def flatten(self, lst): """Turn a list of lists into a list.""" if lst == []: return lst if isinstance(lst[0], list): return self.flatten(lst[0]) + self.flatten(lst[1:]) return lst[:1] + self.flatten(lst[1:])
[ "def", "flatten", "(", "self", ",", "lst", ")", ":", "if", "lst", "==", "[", "]", ":", "return", "lst", "if", "isinstance", "(", "lst", "[", "0", "]", ",", "list", ")", ":", "return", "self", ".", "flatten", "(", "lst", "[", "0", "]", ")", "+...
Turn a list of lists into a list.
[ "Turn", "a", "list", "of", "lists", "into", "a", "list", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1136-L1142
Dallinger/Dallinger
dallinger/models.py
Node.transmit
def transmit(self, what=None, to_whom=None): """Transmit one or more infos from one node to another. "what" dictates which infos are sent, it can be: (1) None (in which case the node's _what method is called). (2) an Info (in which case the node transmits the info) (...
python
def transmit(self, what=None, to_whom=None): """Transmit one or more infos from one node to another. "what" dictates which infos are sent, it can be: (1) None (in which case the node's _what method is called). (2) an Info (in which case the node transmits the info) (...
[ "def", "transmit", "(", "self", ",", "what", "=", "None", ",", "to_whom", "=", "None", ")", ":", "whats", "=", "set", "(", ")", "for", "what", "in", "self", ".", "flatten", "(", "[", "what", "]", ")", ":", "if", "what", "is", "None", ":", "what...
Transmit one or more infos from one node to another. "what" dictates which infos are sent, it can be: (1) None (in which case the node's _what method is called). (2) an Info (in which case the node transmits the info) (3) a subclass of Info (in which case the node transmits ...
[ "Transmit", "one", "or", "more", "infos", "from", "one", "node", "to", "another", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1144-L1198
Dallinger/Dallinger
dallinger/models.py
Vector.fail
def fail(self): """Fail a vector.""" if self.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(self)) else: self.failed = True self.time_of_death = timenow() for t in self.transmissions(): t.fail...
python
def fail(self): """Fail a vector.""" if self.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(self)) else: self.failed = True self.time_of_death = timenow() for t in self.transmissions(): t.fail...
[ "def", "fail", "(", "self", ")", ":", "if", "self", ".", "failed", "is", "True", ":", "raise", "AttributeError", "(", "\"Cannot fail {} - it has already failed.\"", ".", "format", "(", "self", ")", ")", "else", ":", "self", ".", "failed", "=", "True", "sel...
Fail a vector.
[ "Fail", "a", "vector", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1415-L1424
Dallinger/Dallinger
dallinger/models.py
Info.json_data
def json_data(self): """The json representation of an info.""" return { "type": self.type, "origin_id": self.origin_id, "network_id": self.network_id, "contents": self.contents, }
python
def json_data(self): """The json representation of an info.""" return { "type": self.type, "origin_id": self.origin_id, "network_id": self.network_id, "contents": self.contents, }
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"type\"", ":", "self", ".", "type", ",", "\"origin_id\"", ":", "self", ".", "origin_id", ",", "\"network_id\"", ":", "self", ".", "network_id", ",", "\"contents\"", ":", "self", ".", "contents", ...
The json representation of an info.
[ "The", "json", "representation", "of", "an", "info", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1477-L1484
Dallinger/Dallinger
dallinger/models.py
Info.transformations
def transformations(self, relationship="all"): """Get all the transformations of this info. Return a list of transformations involving this info. ``relationship`` can be "parent" (in which case only transformations where the info is the ``info_in`` are returned), "child" (in which case ...
python
def transformations(self, relationship="all"): """Get all the transformations of this info. Return a list of transformations involving this info. ``relationship`` can be "parent" (in which case only transformations where the info is the ``info_in`` are returned), "child" (in which case ...
[ "def", "transformations", "(", "self", ",", "relationship", "=", "\"all\"", ")", ":", "if", "relationship", "not", "in", "[", "\"all\"", ",", "\"parent\"", ",", "\"child\"", "]", ":", "raise", "ValueError", "(", "\"You cannot get transformations of relationship {}\"...
Get all the transformations of this info. Return a list of transformations involving this info. ``relationship`` can be "parent" (in which case only transformations where the info is the ``info_in`` are returned), "child" (in which case only transformations where the info is the ``info_...
[ "Get", "all", "the", "transformations", "of", "this", "info", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1521-L1556
Dallinger/Dallinger
dallinger/models.py
Transmission.json_data
def json_data(self): """The json representation of a transmissions.""" return { "vector_id": self.vector_id, "origin_id": self.origin_id, "destination_id": self.destination_id, "info_id": self.info_id, "network_id": self.network_id, ...
python
def json_data(self): """The json representation of a transmissions.""" return { "vector_id": self.vector_id, "origin_id": self.origin_id, "destination_id": self.destination_id, "info_id": self.info_id, "network_id": self.network_id, ...
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"vector_id\"", ":", "self", ".", "vector_id", ",", "\"origin_id\"", ":", "self", ".", "origin_id", ",", "\"destination_id\"", ":", "self", ".", "destination_id", ",", "\"info_id\"", ":", "self", "."...
The json representation of a transmissions.
[ "The", "json", "representation", "of", "a", "transmissions", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1663-L1673
Dallinger/Dallinger
dallinger/models.py
Transformation.json_data
def json_data(self): """The json representation of a transformation.""" return { "info_in_id": self.info_in_id, "info_out_id": self.info_out_id, "node_id": self.node_id, "network_id": self.network_id, }
python
def json_data(self): """The json representation of a transformation.""" return { "info_in_id": self.info_in_id, "info_out_id": self.info_out_id, "node_id": self.node_id, "network_id": self.network_id, }
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"info_in_id\"", ":", "self", ".", "info_in_id", ",", "\"info_out_id\"", ":", "self", ".", "info_out_id", ",", "\"node_id\"", ":", "self", ".", "node_id", ",", "\"network_id\"", ":", "self", ".", "...
The json representation of a transformation.
[ "The", "json", "representation", "of", "a", "transformation", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1756-L1763
Dallinger/Dallinger
dallinger/utils.py
dallinger_package_path
def dallinger_package_path(): """Return the absolute path of the root directory of the installed Dallinger package: >>> utils.dallinger_package_location() '/Users/janedoe/projects/Dallinger3/dallinger' """ dist = get_distribution("dallinger") src_base = os.path.join(dist.location, dist.proj...
python
def dallinger_package_path(): """Return the absolute path of the root directory of the installed Dallinger package: >>> utils.dallinger_package_location() '/Users/janedoe/projects/Dallinger3/dallinger' """ dist = get_distribution("dallinger") src_base = os.path.join(dist.location, dist.proj...
[ "def", "dallinger_package_path", "(", ")", ":", "dist", "=", "get_distribution", "(", "\"dallinger\"", ")", "src_base", "=", "os", ".", "path", ".", "join", "(", "dist", ".", "location", ",", "dist", ".", "project_name", ")", "return", "src_base" ]
Return the absolute path of the root directory of the installed Dallinger package: >>> utils.dallinger_package_location() '/Users/janedoe/projects/Dallinger3/dallinger'
[ "Return", "the", "absolute", "path", "of", "the", "root", "directory", "of", "the", "installed", "Dallinger", "package", ":" ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/utils.py#L34-L44
Dallinger/Dallinger
dallinger/utils.py
generate_random_id
def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits): """Generate random id numbers.""" return "".join(random.choice(chars) for x in range(size))
python
def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits): """Generate random id numbers.""" return "".join(random.choice(chars) for x in range(size))
[ "def", "generate_random_id", "(", "size", "=", "6", ",", "chars", "=", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", ":", "return", "\"\"", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "x", "in", "range", ...
Generate random id numbers.
[ "Generate", "random", "id", "numbers", "." ]
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/utils.py#L47-L49
Dallinger/Dallinger
dallinger/utils.py
run_command
def run_command(cmd, out, ignore_errors=False): """We want to both send subprocess output to stdout or another file descriptor as the subprocess runs, *and* capture the actual exception message on errors. CalledProcessErrors do not reliably contain the underlying exception in either the 'message' or 'ou...
python
def run_command(cmd, out, ignore_errors=False): """We want to both send subprocess output to stdout or another file descriptor as the subprocess runs, *and* capture the actual exception message on errors. CalledProcessErrors do not reliably contain the underlying exception in either the 'message' or 'ou...
[ "def", "run_command", "(", "cmd", ",", "out", ",", "ignore_errors", "=", "False", ")", ":", "tempdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "output_file", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "\"stderr\"", ")", "original_cmd", ...
We want to both send subprocess output to stdout or another file descriptor as the subprocess runs, *and* capture the actual exception message on errors. CalledProcessErrors do not reliably contain the underlying exception in either the 'message' or 'out' attributes, so we tee the stderr to a temporary ...
[ "We", "want", "to", "both", "send", "subprocess", "output", "to", "stdout", "or", "another", "file", "descriptor", "as", "the", "subprocess", "runs", "*", "and", "*", "capture", "the", "actual", "exception", "message", "on", "errors", ".", "CalledProcessErrors...
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/utils.py#L58-L84