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_documentation_string stringlengths 1 47.2k | 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... | Link to the agent from a parent based on the parent's fitness | 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) | Add a node, connecting it to all the active nodes. | 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) | Create a new network by reading the configuration file. | 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) | Run when a request to create an info is complete. | 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) | Stop caching for pages wrapped in nocache decorator. | 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 | Return list of browser exclusion rules defined in the Configuration. | 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"]:
... | Check user agent against configured exclusions. | 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... | 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. | 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) | Create a node for a participant. | 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) | Make sure each trial contains exactly one chosen info. | 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(
... | Finish reading and send text | 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... | 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 | 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) | Load the data from wherever it is found. | 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(... | Dump the database to a temporary directory. | 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) | Backup the database to S3. | 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) | Register a UUID key in the global S3 bucket. | 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 | Check if a UUID is already registered | 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() | Copy a Heroku database locally. | 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_... | Copy a local database to a set of CSV files. | 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... | Scrub PII from the given participant table. | 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... | Export data from an experiment. | 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",
... | Given a path to a zip file created with `export()`, recreate the
database with the data stored in the included .csv files. | 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... | Load data from a CSV file handle into storage for a
SQLAlchemy model class. | 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:
... | Get an S3 bucket resource after making sure it exists | 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]
)
... | Get the user's S3 bucket. | 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... | A boto3 S3 resource using the AWS keys in the config. | 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... | Define the contents of new Infos.
transmit() -> _what() -> create_information() -> _contents(). | 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... | Choose a parent with probability proportional to their fitness. | 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... | 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. | 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... | Could this config be used to send a real email? | 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... | Provide a transactional scope around a series of operations. | 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 ... | Manage contexts and add debugging to db sessions. | 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 ... | Initialize the database, optionally dropping existing tables. | 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)... | 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. | 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() | Relay chat messages to and from clients. | 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)) | Subscribe a client to the channel. | 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)) | Unsubscribe a client from the channel. | 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:
... | Relay messages from a redis pubsub to all subscribed clients.
This is run continuously in a separate greenlet. | 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) | Register a new client to receive messages on a channel. | 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) | Unsubscribe a client from all channels. | 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... | Send a single message to the websocket. | 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") | Send a ping to the websocket periodically.
This is needed so that Heroku won't close the connection
from inactivity. | 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, ... | Relay messages from client to redis. | 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... | Returns a Selenium WebDriver instance of the type requested in the
configuration. | 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... | Accept HIT, give consent and start experiment.
This uses Selenium to click through buttons on the ad,
consent, and instruction pages. | 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... | Complete the standard debriefing form.
Answers the questions in the base questionnaire. | 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(
... | Submit questionnaire and finish.
This uses Selenium to click the submit button on the questionnaire
and return to the original window. | 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... | Sends worker status ('worker_complete' or 'worker_failed')
to the experiment server. | 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:
... | Sign up, run the ``participate`` method, then sign off and close
the driver. | 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... | Runs the phases of interacting with the experiment
including signup, participation, signoff, and recording completion. | 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... | Signs up a participant for the experiment.
This is done using a POST request to the /participant/ endpoint. | 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... | Record worker completion status to the experiment server.
This is done using a GET request to the /worker_complete
or /worker_failed endpoints. | 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... | In case the experiment enforces a quorum, listen for notifications
before creating Partipant objects. | 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... | Complete the standard debriefing form.
Answers the questions in the base questionnaire. | 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:
... | Verifies key/secret/host combination by making a balance inquiry | 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.
... | 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. | 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... | Register HIT Type for this HIT and return the type's ID, which
is required for creating a HIT. | 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... | 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. | 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
)... | Create a new qualification Workers can be scored for. | 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 ... | 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. | 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,
... | Score a worker for a specific qualification | 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
... | Increment the current qualification score for a worker, on a
qualification with the provided name. | 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... | Return a worker's qualification score as an iteger. | 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(
... | Return the current score for a worker, on a qualification with the
provided name. | 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)
) | Remove a qualification type we created | 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(
... | Get workers with the given qualification. | 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,
):
... | Create the actual HIT and return a dict with its useful properties. | 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 ... | Extend an existing HIT and return an updated description | 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(
... | Expire a HIT, which will change its status to "Reviewable",
allowing it to be deleted. | 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... | 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... | 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
... | Get an assignment by ID and reformat the response. | 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.
... | 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. | 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()
... | Make the specified directory importable as the `dallinger_experiment` package. | 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... | Return json description of a participant. | 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):
... | Get questions associated with this participant.
Return a list of questions associated with the participant. If
specified, ``type`` filters by class. | 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... | 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``. ... | 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,
} | Return json description of a question. | 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,
} | Return json description of a participant. | 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... | 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. | 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)) | How many nodes in a network.
type specifies the class of node, failed
can be True/False/all. | 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:`~... | 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`. | 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... | 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. | 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... | Get vectors in the network.
failed = { False, True, "all" }
To get the vectors to/from to a specific node, see Node.vectors(). | 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"
... | 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". | 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,
... | 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 | 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... | 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". | 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. "
... | Get infos that have been sent to this node.
Type must be a subclass of info, the default is Info. | 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("{... | Get Transformations done by this Node.
type must be a type of Transformation (defaults to Transformation)
Failed can be True, False or "all" | 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... | 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-... | 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... | 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. ... | 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:]) | Turn a list of lists into a list. | 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)
(... | 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 ... | 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... | Fail a vector. | 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,
} | The json representation of an info. | 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 ... | 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_... | 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,
... | The json representation of a transmissions. | 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,
} | The json representation of a transformation. | 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... | Return the absolute path of the root directory of the installed
Dallinger package:
>>> utils.dallinger_package_location()
'/Users/janedoe/projects/Dallinger3/dallinger' | 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)) | Generate random id numbers. | 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... | 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 ... | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/utils.py#L58-L84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.