_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q275500 | SynoStorage.volumes | test | def volumes(self):
"""Returns all available volumes"""
if self._data is not None:
volumes = []
for volume in self._data["volumes"]:
volumes.append(volume["id"])
return volumes | python | {
"resource": ""
} |
q275501 | SynoStorage._get_volume | test | def _get_volume(self, volume_id):
"""Returns a specific volume"""
if self._data is not None:
for volume in self._data["volumes"]:
if volume["id"] == volume_id:
return volume | python | {
"resource": ""
} |
q275502 | SynoStorage.volume_size_total | test | def volume_size_total(self, volume, human_readable=True):
"""Total size of volume"""
volume = self._get_volume(volume)
if volume is not None:
return_data = int(volume["size"]["total"])
if human_readable:
return SynoFormatHelper.bytes_to_readable(
return_data)
else:
return return_data | python | {
"resource": ""
} |
q275503 | SynoStorage.volume_percentage_used | test | def volume_percentage_used(self, volume):
"""Total used size in percentage for volume"""
volume = self._get_volume(volume)
if volume is not None:
total = int(volume["size"]["total"])
used = int(volume["size"]["used"])
if used is not None and used > 0 and \
total is not None and total > 0:
return round((float(used) / float(total)) * 100.0, 1) | python | {
"resource": ""
} |
q275504 | SynoStorage.volume_disk_temp_avg | test | def volume_disk_temp_avg(self, volume):
"""Average temperature of all disks making up the volume"""
volume = self._get_volume(volume)
if volume is not None:
vol_disks = volume["disks"]
if vol_disks is not None:
total_temp = 0
total_disks = 0
for vol_disk in vol_disks:
disk_temp = self.disk_temp(vol_disk)
if disk_temp is not None:
total_disks += 1
total_temp += disk_temp
if total_temp > 0 and total_disks > 0:
return round(total_temp / total_disks, 0) | python | {
"resource": ""
} |
q275505 | SynoStorage.volume_disk_temp_max | test | def volume_disk_temp_max(self, volume):
"""Maximum temperature of all disks making up the volume"""
volume = self._get_volume(volume)
if volume is not None:
vol_disks = volume["disks"]
if vol_disks is not None:
max_temp = 0
for vol_disk in vol_disks:
disk_temp = self.disk_temp(vol_disk)
if disk_temp is not None and disk_temp > max_temp:
max_temp = disk_temp
return max_temp | python | {
"resource": ""
} |
q275506 | SynoStorage._get_disk | test | def _get_disk(self, disk_id):
"""Returns a specific disk"""
if self._data is not None:
for disk in self._data["disks"]:
if disk["id"] == disk_id:
return disk | python | {
"resource": ""
} |
q275507 | SynologyDSM._login | test | def _login(self):
"""Build and execute login request"""
api_path = "%s/auth.cgi?api=SYNO.API.Auth&version=2" % (
self.base_url,
)
login_path = "method=login&%s" % (self._encode_credentials())
url = "%s&%s&session=Core&format=cookie" % (
api_path,
login_path)
result = self._execute_get_url(url, False)
# Parse Result if valid
if result is not None:
self.access_token = result["data"]["sid"]
self._debuglog("Authentication Succesfull, token: " +
str(self.access_token))
return True
else:
self._debuglog("Authentication Failed")
return False | python | {
"resource": ""
} |
q275508 | SynologyDSM._get_url | test | def _get_url(self, url, retry_on_error=True):
"""Function to handle sessions for a GET request"""
# Check if we failed to request the url or need to login
if self.access_token is None or \
self._session is None or \
self._session_error:
# Clear Access Token en reset session error
self.access_token = None
self._session_error = False
# First Reset the session
if self._session is not None:
self._session = None
self._debuglog("Creating New Session")
self._session = requests.Session()
# disable SSL certificate verification
if self._use_https:
self._session.verify = False
# We Created a new Session so login
if self._login() is False:
self._session_error = True
self._debuglog("Login Failed, unable to process request")
return
# Now request the data
response = self._execute_get_url(url)
if (self._session_error or response is None) and retry_on_error:
self._debuglog("Error occured, retrying...")
self._get_url(url, False)
return response | python | {
"resource": ""
} |
q275509 | SynologyDSM._execute_get_url | test | def _execute_get_url(self, request_url, append_sid=True):
"""Function to execute and handle a GET request"""
# Prepare Request
self._debuglog("Requesting URL: '" + request_url + "'")
if append_sid:
self._debuglog("Appending access_token (SID: " +
self.access_token + ") to url")
request_url = "%s&_sid=%s" % (
request_url, self.access_token)
# Execute Request
try:
resp = self._session.get(request_url)
self._debuglog("Request executed: " + str(resp.status_code))
if resp.status_code == 200:
# We got a response
json_data = json.loads(resp.text)
if json_data["success"]:
self._debuglog("Succesfull returning data")
self._debuglog(str(json_data))
return json_data
else:
if json_data["error"]["code"] in {105, 106, 107, 119}:
self._debuglog("Session error: " +
str(json_data["error"]["code"]))
self._session_error = True
else:
self._debuglog("Failed: " + resp.text)
else:
# We got a 404 or 401
return None
#pylint: disable=bare-except
except:
return None | python | {
"resource": ""
} |
q275510 | SynologyDSM.update | test | def update(self):
"""Updates the various instanced modules"""
if self._utilisation is not None:
api = "SYNO.Core.System.Utilization"
url = "%s/entry.cgi?api=%s&version=1&method=get&_sid=%s" % (
self.base_url,
api,
self.access_token)
self._utilisation.update(self._get_url(url))
if self._storage is not None:
api = "SYNO.Storage.CGI.Storage"
url = "%s/entry.cgi?api=%s&version=1&method=load_info&_sid=%s" % (
self.base_url,
api,
self.access_token)
self._storage.update(self._get_url(url)) | python | {
"resource": ""
} |
q275511 | SynologyDSM.utilisation | test | def utilisation(self):
"""Getter for various Utilisation variables"""
if self._utilisation is None:
api = "SYNO.Core.System.Utilization"
url = "%s/entry.cgi?api=%s&version=1&method=get" % (
self.base_url,
api)
self._utilisation = SynoUtilization(self._get_url(url))
return self._utilisation | python | {
"resource": ""
} |
q275512 | SynologyDSM.storage | test | def storage(self):
"""Getter for various Storage variables"""
if self._storage is None:
api = "SYNO.Storage.CGI.Storage"
url = "%s/entry.cgi?api=%s&version=1&method=load_info" % (
self.base_url,
api)
self._storage = SynoStorage(self._get_url(url))
return self._storage | python | {
"resource": ""
} |
q275513 | Context.for_request | test | def for_request(request, body=None):
"""Creates the context for a specific request."""
tenant, jwt_data = Tenant.objects.for_request(request, body)
webhook_sender_id = jwt_data.get('sub')
sender_data = None
if body and 'item' in body:
if 'sender' in body['item']:
sender_data = body['item']['sender']
elif 'message' in body['item'] and 'from' in body['item']['message']:
sender_data = body['item']['message']['from']
if sender_data is None:
if webhook_sender_id is None:
raise BadTenantError('Cannot identify sender in tenant')
sender_data = {'id': webhook_sender_id}
return Context(
tenant=tenant,
sender=HipchatUser(
id=sender_data.get('id'),
name=sender_data.get('name'),
mention_name=sender_data.get('mention_name'),
),
signed_request=request.GET.get('signed_request'),
context=jwt_data.get('context') or {},
) | python | {
"resource": ""
} |
q275514 | Context.tenant_token | test | def tenant_token(self):
"""The cached token of the current tenant."""
rv = getattr(self, '_tenant_token', None)
if rv is None:
rv = self._tenant_token = self.tenant.get_token()
return rv | python | {
"resource": ""
} |
q275515 | WidgetWrapperMixin.build_attrs | test | def build_attrs(self, extra_attrs=None, **kwargs):
"Helper function for building an attribute dictionary."
self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs)
return self.attrs | python | {
"resource": ""
} |
q275516 | with_apps | test | def with_apps(*apps):
"""
Class decorator that makes sure the passed apps are present in
INSTALLED_APPS.
"""
apps_set = set(settings.INSTALLED_APPS)
apps_set.update(apps)
return override_settings(INSTALLED_APPS=list(apps_set)) | python | {
"resource": ""
} |
q275517 | without_apps | test | def without_apps(*apps):
"""
Class decorator that makes sure the passed apps are not present in
INSTALLED_APPS.
"""
apps_list = [a for a in settings.INSTALLED_APPS if a not in apps]
return override_settings(INSTALLED_APPS=apps_list) | python | {
"resource": ""
} |
q275518 | override_settings.get_global_settings | test | def get_global_settings(self):
"""
Return a dictionary of all global_settings values.
"""
return dict((key, getattr(global_settings, key)) for key in dir(global_settings)
if key.isupper()) | python | {
"resource": ""
} |
q275519 | OAuth2UtilRequestHandler.do_GET | test | def do_GET(self):
"""
Handle the retrieval of the code
"""
parsed_url = urlparse(self.path)
if parsed_url[2] == "/" + SERVER_REDIRECT_PATH: # 2 = Path
parsed_query = parse_qs(parsed_url[4]) # 4 = Query
if "code" not in parsed_query:
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write("No code found, try again!".encode("utf-8"))
return
self.server.response_code = parsed_query["code"][0]
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(
"Thank you for using OAuth2Util. The authorization was successful, "
"you can now close this window.".encode("utf-8"))
elif parsed_url[2] == "/" + SERVER_LINK_PATH: # 2 = Path
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write("<html><body>Hey there!<br/>Click <a href=\"{0}\">here</a> to claim your prize.</body></html>"
.format(self.server.authorize_url).encode("utf-8"))
else:
self.send_response(404)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write("404 not found".encode("utf-8")) | python | {
"resource": ""
} |
q275520 | OAuth2Util._get_value | test | def _get_value(self, key, func=None, split_val=None, as_boolean=False,
exception_default=None):
"""
Helper method to get a value from the config
"""
try:
if as_boolean:
return self.config.getboolean(key[0], key[1])
value = self.config.get(key[0], key[1])
if split_val is not None:
value = value.split(split_val)
if func is not None:
return func(value)
return value
except (KeyError, configparser.NoSectionError, configparser.NoOptionError) as e:
if exception_default is not None:
return exception_default
raise KeyError(e) | python | {
"resource": ""
} |
q275521 | OAuth2Util._change_value | test | def _change_value(self, key, value):
"""
Change the value of the given key in the given file to the given value
"""
if not self.config.has_section(key[0]):
self.config.add_section(key[0])
self.config.set(key[0], key[1], str(value))
with open(self.configfile, "w") as f:
self.config.write(f) | python | {
"resource": ""
} |
q275522 | OAuth2Util._migrate_config | test | def _migrate_config(self, oldname=DEFAULT_CONFIG, newname=DEFAULT_CONFIG):
"""
Migrates the old config file format to the new one
"""
self._log("Your OAuth2Util config file is in an old format and needs "
"to be changed. I tried as best as I could to migrate it.", logging.WARNING)
with open(oldname, "r") as old:
with open(newname, "w") as new:
new.write("[app]\n")
new.write(old.read()) | python | {
"resource": ""
} |
q275523 | OAuth2Util._start_webserver | test | def _start_webserver(self, authorize_url=None):
"""
Start the webserver that will receive the code
"""
server_address = (SERVER_URL, SERVER_PORT)
self.server = HTTPServer(server_address, OAuth2UtilRequestHandler)
self.server.response_code = None
self.server.authorize_url = authorize_url
t = Thread(target=self.server.serve_forever)
t.daemon = True
t.start() | python | {
"resource": ""
} |
q275524 | OAuth2Util._wait_for_response | test | def _wait_for_response(self):
"""
Wait until the user accepted or rejected the request
"""
while not self.server.response_code:
time.sleep(2)
time.sleep(5)
self.server.shutdown() | python | {
"resource": ""
} |
q275525 | OAuth2Util._get_new_access_information | test | def _get_new_access_information(self):
"""
Request new access information from reddit using the built in webserver
"""
if not self.r.has_oauth_app_info:
self._log('Cannot obtain authorize url from PRAW. Please check your configuration.', logging.ERROR)
raise AttributeError('Reddit Session invalid, please check your designated config file.')
url = self.r.get_authorize_url('UsingOAuth2Util',
self._get_value(CONFIGKEY_SCOPE, set, split_val=','),
self._get_value(CONFIGKEY_REFRESHABLE, as_boolean=True))
self._start_webserver(url)
if not self._get_value(CONFIGKEY_SERVER_MODE, as_boolean=True):
webbrowser.open(url)
else:
print("Webserver is waiting for you :D. Please open {0}:{1}/{2} "
"in your browser"
.format(SERVER_URL, SERVER_PORT, SERVER_LINK_PATH))
self._wait_for_response()
try:
access_information = self.r.get_access_information(
self.server.response_code)
except praw.errors.OAuthException:
self._log("Can not authenticate, maybe the app infos (e.g. secret) are wrong.", logging.ERROR)
raise
self._change_value(CONFIGKEY_TOKEN, access_information["access_token"])
self._change_value(CONFIGKEY_REFRESH_TOKEN, access_information["refresh_token"])
self._change_value(CONFIGKEY_VALID_UNTIL, time.time() + TOKEN_VALID_DURATION) | python | {
"resource": ""
} |
q275526 | OAuth2Util._check_token_present | test | def _check_token_present(self):
"""
Check whether the tokens are set and request new ones if not
"""
try:
self._get_value(CONFIGKEY_TOKEN)
self._get_value(CONFIGKEY_REFRESH_TOKEN)
self._get_value(CONFIGKEY_REFRESHABLE)
except KeyError:
self._log("Request new Token (CTP)")
self._get_new_access_information() | python | {
"resource": ""
} |
q275527 | OAuth2Util.set_access_credentials | test | def set_access_credentials(self, _retry=0):
"""
Set the token on the Reddit Object again
"""
if _retry >= 5:
raise ConnectionAbortedError('Reddit is not accessible right now, cannot refresh OAuth2 tokens.')
self._check_token_present()
try:
self.r.set_access_credentials(self._get_value(CONFIGKEY_SCOPE, set, split_val=","),
self._get_value(CONFIGKEY_TOKEN),
self._get_value(CONFIGKEY_REFRESH_TOKEN))
except (praw.errors.OAuthInvalidToken, praw.errors.HTTPException) as e:
# todo check e status code
# self._log('Retrying in 5s.')
# time.sleep(5)
# self.set_access_credentials(_retry=_retry + 1)
self._log("Request new Token (SAC)")
self._get_new_access_information() | python | {
"resource": ""
} |
q275528 | OAuth2Util.refresh | test | def refresh(self, force=False, _retry=0):
"""
Check if the token is still valid and requests a new if it is not
valid anymore
Call this method before a call to praw
if there might have passed more than one hour
force: if true, a new token will be retrieved no matter what
"""
if _retry >= 5:
raise ConnectionAbortedError('Reddit is not accessible right now, cannot refresh OAuth2 tokens.')
self._check_token_present()
# We check whether another instance already refreshed the token
if time.time() > self._get_value(CONFIGKEY_VALID_UNTIL, float, exception_default=0) - REFRESH_MARGIN:
self.config.read(self.configfile)
if time.time() < self._get_value(CONFIGKEY_VALID_UNTIL, float, exception_default=0) - REFRESH_MARGIN:
self._log("Found new token")
self.set_access_credentials()
if force or time.time() > self._get_value(CONFIGKEY_VALID_UNTIL, float, exception_default=0) - REFRESH_MARGIN:
self._log("Refresh Token")
try:
new_token = self.r.refresh_access_information(self._get_value(CONFIGKEY_REFRESH_TOKEN))
self._change_value(CONFIGKEY_TOKEN, new_token["access_token"])
self._change_value(CONFIGKEY_VALID_UNTIL, time.time() + TOKEN_VALID_DURATION)
self.set_access_credentials()
except (praw.errors.OAuthInvalidToken, praw.errors.HTTPException) as e:
# todo check e status code
# self._log('Retrying in 5s.')
# time.sleep(5)
# self.refresh(_retry=_retry + 1)
self._log("Request new Token (REF)")
self._get_new_access_information() | python | {
"resource": ""
} |
q275529 | create_manifest_table | test | def create_manifest_table(dynamodb_client, table_name):
"""Create DynamoDB table for run manifests
Arguments:
dynamodb_client - boto3 DynamoDB client (not service)
table_name - string representing existing table name
"""
try:
dynamodb_client.create_table(
AttributeDefinitions=[
{
'AttributeName': DYNAMODB_RUNID_ATTRIBUTE,
'AttributeType': 'S'
},
],
TableName=table_name,
KeySchema=[
{
'AttributeName': DYNAMODB_RUNID_ATTRIBUTE,
'KeyType': 'HASH'
},
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
dynamodb_client.get_waiter('table_exists').wait(TableName=table_name)
except ClientError as e:
# Table already exists
if e.response['Error']['Code'] == 'ResourceInUseException':
pass
else:
raise e | python | {
"resource": ""
} |
q275530 | split_full_path | test | def split_full_path(path):
"""Return pair of bucket without protocol and path
Arguments:
path - valid S3 path, such as s3://somebucket/events
>>> split_full_path('s3://mybucket/path-to-events')
('mybucket', 'path-to-events/')
>>> split_full_path('s3://mybucket')
('mybucket', None)
>>> split_full_path('s3n://snowplow-bucket/some/prefix/')
('snowplow-bucket', 'some/prefix/')
"""
if path.startswith('s3://'):
path = path[5:]
elif path.startswith('s3n://'):
path = path[6:]
elif path.startswith('s3a://'):
path = path[6:]
else:
raise ValueError("S3 path should start with s3://, s3n:// or "
"s3a:// prefix")
parts = path.split('/')
bucket = parts[0]
path = '/'.join(parts[1:])
return bucket, normalize_prefix(path) | python | {
"resource": ""
} |
q275531 | is_glacier | test | def is_glacier(s3_client, bucket, prefix):
"""Check if prefix is archived in Glacier, by checking storage class of
first object inside that prefix
Arguments:
s3_client - boto3 S3 client (not service)
bucket - valid extracted bucket (without protocol and prefix)
example: sowplow-events-data
prefix - valid S3 prefix (usually, run_id)
example: snowplow-archive/enriched/archive/
"""
response = s3_client.list_objects_v2(Bucket=bucket,
Prefix=prefix,
MaxKeys=3) # 3 to not fetch _SUCCESS
for key in response['Contents']:
if key.get('StorageClass', 'STANDARD') == 'GLACIER':
return True
return False | python | {
"resource": ""
} |
q275532 | extract_run_id | test | def extract_run_id(key):
"""Extract date part from run id
Arguments:
key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/
(trailing slash is required)
>>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/')
'shredded-archive/run=2012-12-11-01-11-33/'
>>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33')
>>> extract_run_id('shredded-archive/run=2012-13-11-01-11-33/')
"""
filename = key.split('/')[-2] # -1 element is empty string
run_id = filename.lstrip('run=')
try:
datetime.strptime(run_id, '%Y-%m-%d-%H-%M-%S')
return key
except ValueError:
return None | python | {
"resource": ""
} |
q275533 | clean_dict | test | def clean_dict(dict):
"""Remove all keys with Nones as values
>>> clean_dict({'key': None})
{}
>>> clean_dict({'empty_s': ''})
{'empty_s': ''}
"""
if sys.version_info[0] < 3:
return {k: v for k, v in dict.iteritems() if v is not None}
else:
return {k: v for k, v in dict.items() if v is not None} | python | {
"resource": ""
} |
q275534 | add_to_manifest | test | def add_to_manifest(dynamodb_client, table_name, run_id):
"""Add run_id into DynamoDB manifest table
Arguments:
dynamodb_client - boto3 DynamoDB client (not service)
table_name - string representing existing table name
run_id - string representing run_id to store
"""
dynamodb_client.put_item(
TableName=table_name,
Item={
DYNAMODB_RUNID_ATTRIBUTE: {
'S': run_id
}
}
) | python | {
"resource": ""
} |
q275535 | is_in_manifest | test | def is_in_manifest(dynamodb_client, table_name, run_id):
"""Check if run_id is stored in DynamoDB table.
Return True if run_id is stored or False otherwise.
Arguments:
dynamodb_client - boto3 DynamoDB client (not service)
table_name - string representing existing table name
run_id - string representing run_id to store
"""
response = dynamodb_client.get_item(
TableName=table_name,
Key={
DYNAMODB_RUNID_ATTRIBUTE: {
'S': run_id
}
}
)
return response.get('Item') is not None | python | {
"resource": ""
} |
q275536 | extract_schema | test | def extract_schema(uri):
"""
Extracts Schema information from Iglu URI
>>> extract_schema("iglu:com.acme-corporation_underscore/event_name-dash/jsonschema/1-10-1")['vendor']
'com.acme-corporation_underscore'
"""
match = re.match(SCHEMA_URI_REGEX, uri)
if match:
return {
'vendor': match.group(1),
'name': match.group(2),
'format': match.group(3),
'version': match.group(4)
}
else:
raise SnowplowEventTransformationException([
"Schema {} does not conform to regular expression {}".format(uri, SCHEMA_URI)
]) | python | {
"resource": ""
} |
q275537 | fix_schema | test | def fix_schema(prefix, schema):
"""
Create an Elasticsearch field name from a schema string
"""
schema_dict = extract_schema(schema)
snake_case_organization = schema_dict['vendor'].replace('.', '_').lower()
snake_case_name = re.sub('([^A-Z_])([A-Z])', '\g<1>_\g<2>', schema_dict['name']).lower()
model = schema_dict['version'].split('-')[0]
return "{}_{}_{}_{}".format(prefix, snake_case_organization, snake_case_name, model) | python | {
"resource": ""
} |
q275538 | parse_contexts | test | def parse_contexts(contexts):
"""
Convert a contexts JSON to an Elasticsearch-compatible list of key-value pairs
For example, the JSON
{
"data": [
{
"data": {
"unique": true
},
"schema": "iglu:com.acme/unduplicated/jsonschema/1-0-0"
},
{
"data": {
"value": 1
},
"schema": "iglu:com.acme/duplicated/jsonschema/1-0-0"
},
{
"data": {
"value": 2
},
"schema": "iglu:com.acme/duplicated/jsonschema/1-0-0"
}
],
"schema": "iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0"
}
would become
[
("context_com_acme_duplicated_1", [{"value": 1}, {"value": 2}]),
("context_com_acme_unduplicated_1", [{"unique": true}])
]
"""
my_json = json.loads(contexts)
data = my_json['data']
distinct_contexts = {}
for context in data:
schema = fix_schema("contexts", context['schema'])
inner_data = context['data']
if schema not in distinct_contexts:
distinct_contexts[schema] = [inner_data]
else:
distinct_contexts[schema].append(inner_data)
output = []
for key in distinct_contexts:
output.append((key, distinct_contexts[key]))
return output | python | {
"resource": ""
} |
q275539 | parse_unstruct | test | def parse_unstruct(unstruct):
"""
Convert an unstructured event JSON to a list containing one Elasticsearch-compatible key-value pair
For example, the JSON
{
"data": {
"data": {
"key": "value"
},
"schema": "iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1"
},
"schema": "iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0"
}
would become
[
(
"unstruct_com_snowplowanalytics_snowplow_link_click_1", {
"key": "value"
}
)
]
"""
my_json = json.loads(unstruct)
data = my_json['data']
schema = data['schema']
if 'data' in data:
inner_data = data['data']
else:
raise SnowplowEventTransformationException(["Could not extract inner data field from unstructured event"])
fixed_schema = fix_schema("unstruct_event", schema)
return [(fixed_schema, inner_data)] | python | {
"resource": ""
} |
q275540 | transform | test | def transform(line, known_fields=ENRICHED_EVENT_FIELD_TYPES, add_geolocation_data=True):
"""
Convert a Snowplow enriched event TSV into a JSON
"""
return jsonify_good_event(line.split('\t'), known_fields, add_geolocation_data) | python | {
"resource": ""
} |
q275541 | jsonify_good_event | test | def jsonify_good_event(event, known_fields=ENRICHED_EVENT_FIELD_TYPES, add_geolocation_data=True):
"""
Convert a Snowplow enriched event in the form of an array of fields into a JSON
"""
if len(event) != len(known_fields):
raise SnowplowEventTransformationException(
["Expected {} fields, received {} fields.".format(len(known_fields), len(event))]
)
else:
output = {}
errors = []
if add_geolocation_data and event[LATITUDE_INDEX] != '' and event[LONGITUDE_INDEX] != '':
output['geo_location'] = event[LATITUDE_INDEX] + ',' + event[LONGITUDE_INDEX]
for i in range(len(event)):
key = known_fields[i][0]
if event[i] != '':
try:
kvpairs = known_fields[i][1](key, event[i])
for kvpair in kvpairs:
output[kvpair[0]] = kvpair[1]
except SnowplowEventTransformationException as sete:
errors += sete.error_messages
except Exception as e:
errors += ["Unexpected exception parsing field with key {} and value {}: {}".format(
known_fields[i][0],
event[i],
repr(e)
)]
if errors:
raise SnowplowEventTransformationException(errors)
else:
return output | python | {
"resource": ""
} |
q275542 | get_used_template | test | def get_used_template(response):
"""
Get the template used in a TemplateResponse.
This returns a tuple of "active choice, all choices"
"""
if not hasattr(response, 'template_name'):
return None, None
template = response.template_name
if template is None:
return None, None
if isinstance(template, (list, tuple)):
# See which template name was really used.
if len(template) == 1:
return template[0], None
else:
used_name = _get_used_template_name(template)
return used_name, template
elif isinstance(template, six.string_types):
# Single string
return template, None
else:
# Template object.
filename = _get_template_filename(template)
template_name = '<template object from {0}>'.format(filename) if filename else '<template object>'
return template_name, None | python | {
"resource": ""
} |
q275543 | PrintNode.print_context | test | def print_context(self, context):
"""
Print the entire template context
"""
text = [CONTEXT_TITLE]
for i, context_scope in enumerate(context):
dump1 = linebreaksbr(pformat_django_context_html(context_scope))
dump2 = pformat_dict_summary_html(context_scope)
# Collapse long objects by default (e.g. request, LANGUAGES and sql_queries)
if len(context_scope) <= 3 and dump1.count('<br />') > 20:
(dump1, dump2) = (dump2, dump1)
text.append(CONTEXT_BLOCK.format(
style=PRE_STYLE,
num=i,
dump1=dump1,
dump2=dump2
))
return u''.join(text) | python | {
"resource": ""
} |
q275544 | PrintNode.print_variables | test | def print_variables(self, context):
"""
Print a set of variables
"""
text = []
for name, expr in self.variables:
# Some extended resolving, to handle unknown variables
data = ''
try:
if isinstance(expr.var, Variable):
data = expr.var.resolve(context)
else:
data = expr.resolve(context) # could return TEMPLATE_STRING_IF_INVALID
except VariableDoesNotExist as e:
# Failed to resolve, display exception inline
keys = []
for scope in context:
keys += scope.keys()
keys = sorted(set(keys)) # Remove duplicates, e.g. csrf_token
return ERROR_TYPE_BLOCK.format(style=PRE_ALERT_STYLE, error=escape(u"Variable '{0}' not found! Available context variables are:\n\n{1}".format(expr, u', '.join(keys))))
else:
# Regular format
textdata = linebreaksbr(pformat_django_context_html(data))
# At top level, prefix class name if it's a longer result
if isinstance(data, SHORT_NAME_TYPES):
text.append(BASIC_TYPE_BLOCK.format(style=PRE_STYLE, name=name, value=textdata))
else:
text.append(OBJECT_TYPE_BLOCK.format(style=PRE_STYLE, name=name, type=data.__class__.__name__, value=textdata))
return u''.join(text) | python | {
"resource": ""
} |
q275545 | pformat_sql_html | test | def pformat_sql_html(sql):
"""
Highlight common SQL words in a string.
"""
sql = escape(sql)
sql = RE_SQL_NL.sub(u'<br>\n\\1', sql)
sql = RE_SQL.sub(u'<strong>\\1</strong>', sql)
return sql | python | {
"resource": ""
} |
q275546 | pformat_django_context_html | test | def pformat_django_context_html(object):
"""
Dump a variable to a HTML string with sensible output for template context fields.
It filters out all fields which are not usable in a template context.
"""
if isinstance(object, QuerySet):
text = ''
lineno = 0
for item in object.all()[:21]:
lineno += 1
if lineno >= 21:
text += u' (remaining items truncated...)'
break
text += u' {0}\n'.format(escape(repr(item)))
return text
elif isinstance(object, Manager):
return mark_safe(u' (use <kbd>.all</kbd> to read it)')
elif isinstance(object, six.string_types):
return escape(repr(object))
elif isinstance(object, Promise):
# lazy() object
return escape(_format_lazy(object))
elif isinstance(object, dict):
# This can also be a ContextDict
return _format_dict(object)
elif isinstance(object, list):
return _format_list(object)
elif hasattr(object, '__dict__'):
return _format_object(object)
else:
# Use regular pprint as fallback.
text = DebugPrettyPrinter(width=200).pformat(object)
return _style_text(text) | python | {
"resource": ""
} |
q275547 | pformat_dict_summary_html | test | def pformat_dict_summary_html(dict):
"""
Briefly print the dictionary keys.
"""
if not dict:
return ' {}'
html = []
for key, value in sorted(six.iteritems(dict)):
if not isinstance(value, DICT_EXPANDED_TYPES):
value = '...'
html.append(_format_dict_item(key, value))
return mark_safe(u'<br/>'.join(html)) | python | {
"resource": ""
} |
q275548 | _style_text | test | def _style_text(text):
"""
Apply some HTML highlighting to the contents.
This can't be done in the
"""
# Escape text and apply some formatting.
# To have really good highlighting, pprint would have to be re-implemented.
text = escape(text)
text = text.replace(' <iterator object>', " <small><<var>this object can be used in a 'for' loop</var>></small>")
text = text.replace(' <dynamic item>', ' <small><<var>this object may have extra field names</var>></small>')
text = text.replace(' <dynamic attribute>', ' <small><<var>this object may have extra field names</var>></small>')
text = RE_PROXY.sub('\g<1><small><<var>proxy object</var>></small>', text)
text = RE_FUNCTION.sub('\g<1><small><<var>object method</var>></small>', text)
text = RE_GENERATOR.sub("\g<1><small><<var>generator, use 'for' to traverse it</var>></small>", text)
text = RE_OBJECT_ADDRESS.sub('\g<1><small><<var>\g<2> object</var>></small>', text)
text = RE_MANAGER.sub('\g<1><small><<var>manager, use <kbd>.all</kbd> to traverse it</var>></small>', text)
text = RE_CLASS_REPR.sub('\g<1><small><<var>\g<2> class</var>></small>', text)
# Since Django's WSGIRequest does a pprint like format for it's __repr__, make that styling consistent
text = RE_REQUEST_FIELDNAME.sub('\g<1>:\n <strong style="color: #222;">\g<2></strong>: ', text)
text = RE_REQUEST_CLEANUP1.sub('\g<1>', text)
text = RE_REQUEST_CLEANUP2.sub(')', text)
return mark_safe(text) | python | {
"resource": ""
} |
q275549 | DebugPrettyPrinter.format | test | def format(self, object, context, maxlevels, level):
"""
Format an item in the result.
Could be a dictionary key, value, etc..
"""
try:
return PrettyPrinter.format(self, object, context, maxlevels, level)
except HANDLED_EXCEPTIONS as e:
return _format_exception(e), True, False | python | {
"resource": ""
} |
q275550 | DebugPrettyPrinter._format | test | def _format(self, object, stream, indent, allowance, context, level):
"""
Recursive part of the formatting
"""
try:
PrettyPrinter._format(self, object, stream, indent, allowance, context, level)
except Exception as e:
stream.write(_format_exception(e)) | python | {
"resource": ""
} |
q275551 | get_token | test | def get_token(s, pos, brackets_are_chars=True, environments=True, **parse_flags):
"""
Parse the next token in the stream.
Returns a `LatexToken`. Raises `LatexWalkerEndOfStream` if end of stream reached.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_token()` instead.
"""
return LatexWalker(s, **parse_flags).get_token(pos=pos,
brackets_are_chars=brackets_are_chars,
environments=environments) | python | {
"resource": ""
} |
q275552 | get_latex_nodes | test | def get_latex_nodes(s, pos=0, stop_upon_closing_brace=None, stop_upon_end_environment=None,
stop_upon_closing_mathmode=None, **parse_flags):
"""
Parses latex content `s`.
Returns a tuple `(nodelist, pos, len)` where nodelist is a list of `LatexNode` 's.
If `stop_upon_closing_brace` is given, then `len` includes the closing brace, but the
closing brace is not included in any of the nodes in the `nodelist`.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_latex_nodes()` instead.
"""
return LatexWalker(s, **parse_flags).get_latex_nodes(stop_upon_closing_brace=stop_upon_closing_brace,
stop_upon_end_environment=stop_upon_end_environment,
stop_upon_closing_mathmode=stop_upon_closing_mathmode) | python | {
"resource": ""
} |
q275553 | latex2text | test | def latex2text(content, tolerant_parsing=False, keep_inline_math=False, keep_comments=False):
"""
Extracts text from `content` meant for database indexing. `content` is
some LaTeX code.
.. deprecated:: 1.0
Please use :py:class:`LatexNodes2Text` instead.
"""
(nodelist, tpos, tlen) = latexwalker.get_latex_nodes(content, keep_inline_math=keep_inline_math,
tolerant_parsing=tolerant_parsing)
return latexnodes2text(nodelist, keep_inline_math=keep_inline_math, keep_comments=keep_comments) | python | {
"resource": ""
} |
q275554 | LatexNodes2Text.set_tex_input_directory | test | def set_tex_input_directory(self, tex_input_directory, latex_walker_init_args=None, strict_input=True):
"""
Set where to look for input files when encountering the ``\\input`` or
``\\include`` macro.
Alternatively, you may also override :py:meth:`read_input_file()` to
implement a custom file lookup mechanism.
The argument `tex_input_directory` is the directory relative to which to
search for input files.
If `strict_input` is set to `True`, then we always check that the
referenced file lies within the subtree of `tex_input_directory`,
prohibiting for instance hacks with '..' in filenames or using symbolic
links to refer to files out of the directory tree.
The argument `latex_walker_init_args` allows you to specify the parse
flags passed to the constructor of
:py:class:`pylatexenc.latexwalker.LatexWalker` when parsing the input
file.
"""
self.tex_input_directory = tex_input_directory
self.latex_walker_init_args = latex_walker_init_args if latex_walker_init_args else {}
self.strict_input = strict_input
if tex_input_directory:
self.macro_dict['input'] = MacroDef('input', lambda n: self._callback_input(n))
self.macro_dict['include'] = MacroDef('include', lambda n: self._callback_input(n))
else:
self.macro_dict['input'] = MacroDef('input', discard=True)
self.macro_dict['include'] = MacroDef('include', discard=True) | python | {
"resource": ""
} |
q275555 | LatexNodes2Text.read_input_file | test | def read_input_file(self, fn):
"""
This method may be overridden to implement a custom lookup mechanism when
encountering ``\\input`` or ``\\include`` directives.
The default implementation looks for a file of the given name relative
to the directory set by :py:meth:`set_tex_input_directory()`. If
`strict_input=True` was set, we ensure strictly that the file resides in
a subtree of the reference input directory (after canonicalizing the
paths and resolving all symlinks).
You may override this method to obtain the input data in however way you
see fit. (In that case, a call to `set_tex_input_directory()` may not
be needed as that function simply sets properties which are used by the
default implementation of `read_input_file()`.)
This function accepts the referred filename as argument (the argument to
the ``\\input`` macro), and should return a string with the file
contents (or generate a warning or raise an error).
"""
fnfull = os.path.realpath(os.path.join(self.tex_input_directory, fn))
if self.strict_input:
# make sure that the input file is strictly within dirfull, and didn't escape with
# '../..' tricks or via symlinks.
dirfull = os.path.realpath(self.tex_input_directory)
if not fnfull.startswith(dirfull):
logger.warning(
"Can't access path '%s' leading outside of mandated directory [strict input mode]",
fn
)
return ''
if not os.path.exists(fnfull) and os.path.exists(fnfull + '.tex'):
fnfull = fnfull + '.tex'
if not os.path.exists(fnfull) and os.path.exists(fnfull + '.latex'):
fnfull = fnfull + '.latex'
if not os.path.isfile(fnfull):
logger.warning(u"Error, file doesn't exist: '%s'", fn)
return ''
logger.debug("Reading input file %r", fnfull)
try:
with open(fnfull) as f:
return f.read()
except IOError as e:
logger.warning(u"Error, can't access '%s': %s", fn, e)
return '' | python | {
"resource": ""
} |
q275556 | LatexNodes2Text.latex_to_text | test | def latex_to_text(self, latex, **parse_flags):
"""
Parses the given `latex` code and returns its textual representation.
The `parse_flags` are the flags to give on to the
:py:class:`pylatexenc.latexwalker.LatexWalker` constructor.
"""
return self.nodelist_to_text(latexwalker.LatexWalker(latex, **parse_flags).get_latex_nodes()[0]) | python | {
"resource": ""
} |
q275557 | utf8tolatex | test | def utf8tolatex(s, non_ascii_only=False, brackets=True, substitute_bad_chars=False, fail_bad_chars=False):
u"""
Encode a UTF-8 string to a LaTeX snippet.
If `non_ascii_only` is set to `True`, then usual (ascii) characters such as ``#``,
``{``, ``}`` etc. will not be escaped. If set to `False` (the default), they are
escaped to their respective LaTeX escape sequences.
If `brackets` is set to `True` (the default), then LaTeX macros are enclosed in
brackets. For example, ``sant\N{LATIN SMALL LETTER E WITH ACUTE}`` is replaced by
``sant{\\'e}`` if `brackets=True` and by ``sant\\'e`` if `brackets=False`.
.. warning::
Using `brackets=False` might give you an invalid LaTeX string, so avoid
it! (for instance, ``ma\N{LATIN SMALL LETTER I WITH CIRCUMFLEX}tre`` will be
replaced incorrectly by ``ma\\^\\itre`` resulting in an unknown macro ``\\itre``).
If `substitute_bad_chars=True`, then any non-ascii character for which no LaTeX escape
sequence is known is replaced by a question mark in boldface. Otherwise (by default),
the character is left as it is.
If `fail_bad_chars=True`, then a `ValueError` is raised if we cannot find a
character substitution for any non-ascii character.
.. versionchanged:: 1.3
Added `fail_bad_chars` switch
"""
s = unicode(s) # make sure s is unicode
s = unicodedata.normalize('NFC', s)
if not s:
return ""
result = u""
for ch in s:
#log.longdebug("Encoding char %r", ch)
if (non_ascii_only and ord(ch) < 127):
result += ch
else:
lch = utf82latex.get(ord(ch), None)
if (lch is not None):
# add brackets if needed, i.e. if we have a substituting macro.
# note: in condition, beware, that lch might be of zero length.
result += ( '{'+lch+'}' if brackets and lch[0:1] == '\\' else
lch )
elif ((ord(ch) >= 32 and ord(ch) <= 127) or
(ch in "\n\r\t")):
# ordinary printable ascii char, just add it
result += ch
else:
# non-ascii char
msg = u"Character cannot be encoded into LaTeX: U+%04X - `%s'" % (ord(ch), ch)
if fail_bad_chars:
raise ValueError(msg)
log.warning(msg)
if substitute_bad_chars:
result += r'{\bfseries ?}'
else:
# keep unescaped char
result += ch
return result | python | {
"resource": ""
} |
q275558 | _unascii | test | def _unascii(s):
"""Unpack `\\uNNNN` escapes in 's' and encode the result as UTF-8
This method takes the output of the JSONEncoder and expands any \\uNNNN
escapes it finds (except for \\u0000 to \\u001F, which are converted to
\\xNN escapes).
For performance, it assumes that the input is valid JSON, and performs few
sanity checks.
"""
# make the fast path fast: if there are no matches in the string, the
# whole thing is ascii. On python 2, that means we're done. On python 3,
# we have to turn it into a bytes, which is quickest with encode('utf-8')
m = _U_ESCAPE.search(s)
if not m:
return s if PY2 else s.encode('utf-8')
# appending to a string (or a bytes) is slooow, so we accumulate sections
# of string result in 'chunks', and join them all together later.
# (It doesn't seem to make much difference whether we accumulate
# utf8-encoded bytes, or strings which we utf-8 encode after rejoining)
#
chunks = []
# 'pos' tracks the index in 's' that we have processed into 'chunks' so
# far.
pos = 0
while m:
start = m.start()
end = m.end()
g = m.group(1)
if g is None:
# escaped backslash: pass it through along with anything before the
# match
chunks.append(s[pos:end])
else:
# \uNNNN, but we have to watch out for surrogate pairs.
#
# On python 2, str.encode("utf-8") will decode utf-16 surrogates
# before re-encoding, so it's fine for us to pass the surrogates
# through. (Indeed we must, to deal with UCS-2 python builds, per
# https://github.com/matrix-org/python-canonicaljson/issues/12).
#
# On python 3, str.encode("utf-8") complains about surrogates, so
# we have to unpack them.
c = int(g, 16)
if c < 0x20:
# leave as a \uNNNN escape
chunks.append(s[pos:end])
else:
if PY3: # pragma nocover
if c & 0xfc00 == 0xd800 and s[end:end + 2] == '\\u':
esc2 = s[end + 2:end + 6]
c2 = int(esc2, 16)
if c2 & 0xfc00 == 0xdc00:
c = 0x10000 + (((c - 0xd800) << 10) |
(c2 - 0xdc00))
end += 6
chunks.append(s[pos:start])
chunks.append(unichr(c))
pos = end
m = _U_ESCAPE.search(s, pos)
# pass through anything after the last match
chunks.append(s[pos:])
return (''.join(chunks)).encode("utf-8") | python | {
"resource": ""
} |
q275559 | Organisation.get_organisation_information | test | def get_organisation_information(self, query_params=None):
'''
Get information fot this organisation. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275560 | Organisation.get_boards | test | def get_boards(self, **query_params):
'''
Get all the boards for this organisation. Returns a list of Board s.
Returns:
list(Board): The boards attached to this organisation
'''
boards = self.get_boards_json(self.base_uri, query_params=query_params)
boards_list = []
for board_json in boards:
boards_list.append(self.create_board(board_json))
return boards_list | python | {
"resource": ""
} |
q275561 | Organisation.get_members | test | def get_members(self, **query_params):
'''
Get all members attached to this organisation. Returns a list of
Member objects
Returns:
list(Member): The members attached to this organisation
'''
members = self.get_members_json(self.base_uri,
query_params=query_params)
members_list = []
for member_json in members:
members_list.append(self.create_member(member_json))
return members_list | python | {
"resource": ""
} |
q275562 | Organisation.update_organisation | test | def update_organisation(self, query_params=None):
'''
Update this organisations information. Returns a new organisation
object.
'''
organisation_json = self.fetch_json(
uri_path=self.base_uri,
http_method='PUT',
query_params=query_params or {}
)
return self.create_organisation(organisation_json) | python | {
"resource": ""
} |
q275563 | Organisation.remove_member | test | def remove_member(self, member_id):
'''
Remove a member from the organisation.Returns JSON of all members if
successful or raises an Unauthorised exception if not.
'''
return self.fetch_json(
uri_path=self.base_uri + '/members/%s' % member_id,
http_method='DELETE'
) | python | {
"resource": ""
} |
q275564 | Organisation.add_member_by_id | test | def add_member_by_id(self, member_id, membership_type='normal'):
'''
Add a member to the board using the id. Membership type can be
normal or admin. Returns JSON of all members if successful or raises an
Unauthorised exception if not.
'''
return self.fetch_json(
uri_path=self.base_uri + '/members/%s' % member_id,
http_method='PUT',
query_params={
'type': membership_type
}
) | python | {
"resource": ""
} |
q275565 | Organisation.add_member | test | def add_member(self, email, fullname, membership_type='normal'):
'''
Add a member to the board. Membership type can be normal or admin.
Returns JSON of all members if successful or raises an Unauthorised
exception if not.
'''
return self.fetch_json(
uri_path=self.base_uri + '/members',
http_method='PUT',
query_params={
'email': email,
'fullName': fullname,
'type': membership_type
}
) | python | {
"resource": ""
} |
q275566 | List.get_list_information | test | def get_list_information(self, query_params=None):
'''
Get information for this list. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275567 | List.add_card | test | def add_card(self, query_params=None):
'''
Create a card for this list. Returns a Card object.
'''
card_json = self.fetch_json(
uri_path=self.base_uri + '/cards',
http_method='POST',
query_params=query_params or {}
)
return self.create_card(card_json) | python | {
"resource": ""
} |
q275568 | Label.get_label_information | test | def get_label_information(self, query_params=None):
'''
Get all information for this Label. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275569 | Label.get_items | test | def get_items(self, query_params=None):
'''
Get all the items for this label. Returns a list of dictionaries.
Each dictionary has the values for an item.
'''
return self.fetch_json(
uri_path=self.base_uri + '/checkItems',
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275570 | Label._update_label_name | test | def _update_label_name(self, name):
'''
Update the current label's name. Returns a new Label object.
'''
label_json = self.fetch_json(
uri_path=self.base_uri,
http_method='PUT',
query_params={'name': name}
)
return self.create_label(label_json) | python | {
"resource": ""
} |
q275571 | Label._update_label_dict | test | def _update_label_dict(self, query_params={}):
'''
Update the current label. Returns a new Label object.
'''
label_json = self.fetch_json(
uri_path=self.base_uri,
http_method='PUT',
query_params=query_params
)
return self.create_label(label_json) | python | {
"resource": ""
} |
q275572 | Authorise.get_authorisation_url | test | def get_authorisation_url(self, application_name, token_expire='1day'):
'''
Returns a URL that needs to be opened in a browser to retrieve an
access token.
'''
query_params = {
'name': application_name,
'expiration': token_expire,
'response_type': 'token',
'scope': 'read,write'
}
authorisation_url = self.build_uri(
path='/authorize',
query_params=self.add_authorisation(query_params)
)
print('Please go to the following URL and get the user authorisation '
'token:\n', authorisation_url)
return authorisation_url | python | {
"resource": ""
} |
q275573 | Card.get_card_information | test | def get_card_information(self, query_params=None):
'''
Get information for this card. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275574 | Card.get_board | test | def get_board(self, **query_params):
'''
Get board information for this card. Returns a Board object.
Returns:
Board: The board this card is attached to
'''
board_json = self.get_board_json(self.base_uri,
query_params=query_params)
return self.create_board(board_json) | python | {
"resource": ""
} |
q275575 | Card.get_list | test | def get_list(self, **query_params):
'''
Get list information for this card. Returns a List object.
Returns:
List: The list this card is attached to
'''
list_json = self.get_list_json(self.base_uri,
query_params=query_params)
return self.create_list(list_json) | python | {
"resource": ""
} |
q275576 | Card.get_checklists | test | def get_checklists(self, **query_params):
'''
Get the checklists for this card. Returns a list of Checklist objects.
Returns:
list(Checklist): The checklists attached to this card
'''
checklists = self.get_checklist_json(self.base_uri,
query_params=query_params)
checklists_list = []
for checklist_json in checklists:
checklists_list.append(self.create_checklist(checklist_json))
return checklists_list | python | {
"resource": ""
} |
q275577 | Card.add_comment | test | def add_comment(self, comment_text):
'''
Adds a comment to this card by the current user.
'''
return self.fetch_json(
uri_path=self.base_uri + '/actions/comments',
http_method='POST',
query_params={'text': comment_text}
) | python | {
"resource": ""
} |
q275578 | Card.add_attachment | test | def add_attachment(self, filename, open_file):
'''
Adds an attachment to this card.
'''
fields = {
'api_key': self.client.api_key,
'token': self.client.user_auth_token
}
content_type, body = self.encode_multipart_formdata(
fields=fields,
filename=filename,
file_values=open_file
)
return self.fetch_json(
uri_path=self.base_uri + '/attachments',
http_method='POST',
body=body,
headers={'Content-Type': content_type},
) | python | {
"resource": ""
} |
q275579 | Card.add_checklist | test | def add_checklist(self, query_params=None):
'''
Add a checklist to this card. Returns a Checklist object.
'''
checklist_json = self.fetch_json(
uri_path=self.base_uri + '/checklists',
http_method='POST',
query_params=query_params or {}
)
return self.create_checklist(checklist_json) | python | {
"resource": ""
} |
q275580 | Card._add_label_from_dict | test | def _add_label_from_dict(self, query_params=None):
'''
Add a label to this card, from a dictionary.
'''
return self.fetch_json(
uri_path=self.base_uri + '/labels',
http_method='POST',
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275581 | Card._add_label_from_class | test | def _add_label_from_class(self, label=None):
'''
Add an existing label to this card.
'''
return self.fetch_json(
uri_path=self.base_uri + '/idLabels',
http_method='POST',
query_params={'value': label.id}
) | python | {
"resource": ""
} |
q275582 | Card.add_member | test | def add_member(self, member_id):
'''
Add a member to this card. Returns a list of Member objects.
'''
members = self.fetch_json(
uri_path=self.base_uri + '/idMembers',
http_method='POST',
query_params={'value': member_id}
)
members_list = []
for member_json in members:
members_list.append(self.create_member(member_json))
return members_list | python | {
"resource": ""
} |
q275583 | Member.get_member_information | test | def get_member_information(self, query_params=None):
'''
Get Information for a member. Returns a dictionary of values.
Returns:
dict
'''
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275584 | Member.get_cards | test | def get_cards(self, **query_params):
'''
Get all cards this member is attached to. Return a list of Card
objects.
Returns:
list(Card): Return all cards this member is attached to
'''
cards = self.get_cards_json(self.base_uri, query_params=query_params)
cards_list = []
for card_json in cards:
cards_list.append(self.create_card(card_json))
return cards_list | python | {
"resource": ""
} |
q275585 | Member.get_organisations | test | def get_organisations(self, **query_params):
'''
Get all organisations this member is attached to. Return a list of
Organisation objects.
Returns:
list(Organisation): Return all organisations this member is
attached to
'''
organisations = self.get_organisations_json(self.base_uri,
query_params=query_params)
organisations_list = []
for organisation_json in organisations:
organisations_list.append(
self.create_organisation(organisation_json))
return organisations_list | python | {
"resource": ""
} |
q275586 | Member.create_new_board | test | def create_new_board(self, query_params=None):
'''
Create a new board. name is required in query_params. Returns a Board
object.
Returns:
Board: Returns the created board
'''
board_json = self.fetch_json(
uri_path='/boards',
http_method='POST',
query_params=query_params or {}
)
return self.create_board(board_json) | python | {
"resource": ""
} |
q275587 | singledispatchmethod | test | def singledispatchmethod(method):
'''
Enable singledispatch for class methods.
See http://stackoverflow.com/a/24602374/274318
'''
dispatcher = singledispatch(method)
def wrapper(*args, **kw):
return dispatcher.dispatch(args[1].__class__)(*args, **kw)
wrapper.register = dispatcher.register
update_wrapper(wrapper, dispatcher)
return wrapper | python | {
"resource": ""
} |
q275588 | Board.get_board_information | test | def get_board_information(self, query_params=None):
'''
Get all information for this board. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path='/boards/' + self.id,
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275589 | Board.get_lists | test | def get_lists(self, **query_params):
'''
Get the lists attached to this board. Returns a list of List objects.
Returns:
list(List): The lists attached to this board
'''
lists = self.get_lists_json(self.base_uri, query_params=query_params)
lists_list = []
for list_json in lists:
lists_list.append(self.create_list(list_json))
return lists_list | python | {
"resource": ""
} |
q275590 | Board.get_labels | test | def get_labels(self, **query_params):
'''
Get the labels attached to this board. Returns a label of Label
objects.
Returns:
list(Label): The labels attached to this board
'''
labels = self.get_labels_json(self.base_uri, query_params=query_params)
labels_list = []
for label_json in labels:
labels_list.append(self.create_label(label_json))
return labels_list | python | {
"resource": ""
} |
q275591 | Board.get_card | test | def get_card(self, card_id, **query_params):
'''
Get a Card for a given card id. Returns a Card object.
Returns:
Card: The card with the given card_id
'''
card_json = self.fetch_json(
uri_path=self.base_uri + '/cards/' + card_id
)
return self.create_card(card_json) | python | {
"resource": ""
} |
q275592 | Board.get_checklists | test | def get_checklists( self ):
"""
Get the checklists for this board. Returns a list of Checklist objects.
"""
checklists = self.getChecklistsJson( self.base_uri )
checklists_list = []
for checklist_json in checklists:
checklists_list.append( self.createChecklist( checklist_json ) )
return checklists_list | python | {
"resource": ""
} |
q275593 | Board.get_organisation | test | def get_organisation(self, **query_params):
'''
Get the Organisation for this board. Returns Organisation object.
Returns:
list(Organisation): The organisation attached to this board
'''
organisation_json = self.get_organisations_json(
self.base_uri, query_params=query_params)
return self.create_organisation(organisation_json) | python | {
"resource": ""
} |
q275594 | Board.update_board | test | def update_board(self, query_params=None):
'''
Update this board's information. Returns a new board.
'''
board_json = self.fetch_json(
uri_path=self.base_uri,
http_method='PUT',
query_params=query_params or {}
)
return self.create_board(board_json) | python | {
"resource": ""
} |
q275595 | Board.add_list | test | def add_list(self, query_params=None):
'''
Create a list for a board. Returns a new List object.
'''
list_json = self.fetch_json(
uri_path=self.base_uri + '/lists',
http_method='POST',
query_params=query_params or {}
)
return self.create_list(list_json) | python | {
"resource": ""
} |
q275596 | Board.add_label | test | def add_label(self, query_params=None):
'''
Create a label for a board. Returns a new Label object.
'''
list_json = self.fetch_json(
uri_path=self.base_uri + '/labels',
http_method='POST',
query_params=query_params or {}
)
return self.create_label(list_json) | python | {
"resource": ""
} |
q275597 | Checklist.get_checklist_information | test | def get_checklist_information(self, query_params=None):
'''
Get all information for this Checklist. Returns a dictionary of values.
'''
# We don't use trelloobject.TrelloObject.get_checklist_json, because
# that is meant to return lists of checklists.
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
) | python | {
"resource": ""
} |
q275598 | Checklist.get_card | test | def get_card(self):
'''
Get card this checklist is on.
'''
card_id = self.get_checklist_information().get('idCard', None)
if card_id:
return self.client.get_card(card_id) | python | {
"resource": ""
} |
q275599 | Checklist.get_item_objects | test | def get_item_objects(self, query_params=None):
"""
Get the items for this checklist. Returns a list of ChecklistItem objects.
"""
card = self.get_card()
checklistitems_list = []
for checklistitem_json in self.get_items(query_params):
checklistitems_list.append(self.create_checklist_item(card.id, self.id, checklistitem_json))
return checklistitems_list | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.