repo_name
stringclasses 400
values | branch_name
stringclasses 4
values | file_content
stringlengths 16
72.5k
| language
stringclasses 1
value | num_lines
int64 1
1.66k
| avg_line_length
float64 6
85
| max_line_length
int64 9
949
| path
stringlengths 5
103
| alphanum_fraction
float64 0.29
0.89
| alpha_fraction
float64 0.27
0.89
|
|---|---|---|---|---|---|---|---|---|---|
lukemadera/ml-learning
|
refs/heads/master
|
import copy
import random
def findIndex(array1, key, value):
return find_index(array1, key, value)
def find_index(array1, key, value):
for index, arr_item in enumerate(array1):
if key in arr_item and arr_item[key] == value:
return index
return -1
def extend_object(default, new):
final = {}
# Go through defaults first
for key in default:
if key not in new:
final[key] = default[key]
else:
final[key] = new[key]
# In case any keys in new but not in default, add them
for key in new:
if key not in final:
final[key] = new[key]
return final
def sort2D(array1, key, order = 'ascending'):
if len(array1) < 2:
return array1
# def compare(a, b):
# aVal = a[key]
# bVal = b[key]
# if aVal == bVal:
# return 0
# if (aVal > bVal and order == 'ascending') or (aVal < bVal and order == 'descending'):
# return 1
# return -1
def getValue(item):
return item[key]
reverse = True if order == 'descending' else False
return sorted(array1, key=getValue, reverse=reverse)
def omit(object1, keys = []):
new_object = {}
for key in object1:
if key not in keys:
new_object[key] = object1[key]
return new_object
def pick(object1, keys = []):
new_object = {}
for key in object1:
if key in keys:
new_object[key] = object1[key]
return new_object
def map_pick(array1, keys = []):
def pick1(obj1):
return pick(obj1, keys)
return list(map(pick1, array1))
def mapOmit(array1, omitKeys = []):
def omit1(obj1):
return omit(obj1, omitKeys)
return list(map(omit1, array1))
def get_key_array(items, key, skipEmpty=0, emptyValue=None):
if skipEmpty:
return list(map(lambda item: item[key] if key in item else emptyValue, items))
else:
return list(map(lambda item: item[key], items))
# def append_if_unique(array1, value):
# if value not in array1:
# array1.append(value)
def random_string(length = 10):
text = ''
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
chars_length = len(chars)
counter = 0
while counter < length:
index = random.randint(0, (chars_length - 1))
text = text + chars[index]
counter = counter + 1
return text
def removeArrayIndices(array, indices):
array1 = copy.deepcopy(array)
for index, item in reversed(list(enumerate(array1))):
if index in indices:
del array1[index]
return array1
|
Python
| 97
| 26.216496
| 95
|
/lodash.py
| 0.598485
| 0.577273
|
andrew-li729/CIS-2348-Homework-3
|
refs/heads/master
|
# Andrew Li
# 1824794
class FoodItem:
def __init__(self, name="None", fat=0, carbs=0, protein=0):
self.name = name
self.fat = fat
self.carbs = carbs
self.protein = protein
def get_calories(self, num_servings):
# Calorie formula
calories = ((self.fat * 9) + (self.carbs * 4) + (self.protein * 4)) * num_servings;
return calories
def print_info(self):
print('Nutritional information per serving of {}:'.format(self.name))
print(' Fat: {:.2f} g'.format(self.fat))
print(' Carbohydrates: {:.2f} g'.format(self.carbs))
print(' Protein: {:.2f} g'.format(self.protein))
if __name__ == '__main__':
name = input()
fat = float(input())
carbs = float(input())
protein = float(input())
num_servings = float(input())
food_1 = FoodItem()
total_calories1 = food_1.get_calories(num_servings)
food_1.print_info()
print("Number of calories for {:.2f} serving(s): {:.2f}".format(num_servings, total_calories1))
print()
food2 = FoodItem(name, fat, carbs, protein)
total_calories2 = food2.get_calories(num_servings)
food2.print_info()
print("Number of calories for {:.2f} serving(s): {:.2f}".format(num_servings, total_calories2))
|
Python
| 37
| 33.432434
| 99
|
/Lab_10.11.py
| 0.596863
| 0.573333
|
andrew-li729/CIS-2348-Homework-3
|
refs/heads/master
|
# Andrew Li
# 1824794
class ItemToPurchase:
def __init__(self, item_name="none", item_price=0, item_quantity=0, item_description="none"):
self.item_name = item_name
self.item_price = item_price
self.item_quantity = item_quantity
self.item_description = item_description
def print_item_cost(self):
print("{} {} @ ${:.0f} = ${:.0f}".format(self.item_name, self.item_quantity, self.item_price,
self.item_price * self.item_quantity))
def print_item_description(self):
print(self.item_description)
def compute_total(self):
return self.item_price * self.item_quantity
class ShoppingCart:
def __init__(self, customer_name="none", current_date="January 1, 2016"):
self.customer_name = customer_name
self.current_date = current_date
self.cart_items = []
def add_item(self):
print('ADD ITEM TO CART')
item_name = str(input('Enter the item name:\n'))
item_description = str(input('Enter the item description:\n'))
item_price = int(input('Enter the item price:\n'))
item_quantity = int(input('Enter the item quantity:\n'))
self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))
def remove_item(self, item_name):
flag = None
item_string = item_name
for item in self.cart_items:
if item_string == item.item_name:
flag = True
del self.cart_items[self.cart_items.index(item)]
break
else:
flag = False
if not flag:
print("Item not found in cart. Nothing removed.")
def modify_item(self, ItemToPurchase):
item_string = ItemToPurchase
new_quantity = int(input("Enter the new quantity:\n"))
flag = None
for item in self.cart_items:
if item_string == item.item_name:
item.item_quantity = new_quantity
flag = True
break
else:
flag = False
if not flag:
print("Item not found in cart. Nothing modified.")
def get_num_items_in_cart(self):
num_items = 0
for item in self.cart_items:
num_items += item.item_quantity
return num_items
def get_cost_of_cart(self):
total = 0
for item in self.cart_items:
cost = item.item_price * item.item_quantity
total += cost
return total
def print_total(self):
if not self.cart_items:
print("{}'s Shopping Cart - {}".format(self.customer_name, self.current_date))
print("Number of Items: {}\n".format(self.get_num_items_in_cart()))
print("SHOPPING CART IS EMPTY\n")
print("Total: ${}".format(self.get_cost_of_cart()))
else:
print("{}'s Shopping Cart - {}".format(self.customer_name, self.current_date))
print("Number of Items: {}\n".format(self.get_num_items_in_cart()))
for item in self.cart_items:
print("{} {} @ ${:.0f} = ${:.0f}".format(item.item_name, item.item_quantity, item.item_price,
item.item_price * item.item_quantity))
print()
print("Total: ${}".format(self.get_cost_of_cart()))
def print_descriptions(self):
print("{}'s Shopping Cart - {}\n".format(self.customer_name, self.current_date))
print("Item Descriptions")
for item in self.cart_items:
print("{}: {}".format(item.item_name, item.item_description))
def print_menu(cart):
option = ""
print("MENU")
print("a - Add item to cart")
print("r - Remove item from cart")
print("c - Change item quantity")
print("i - Output items' descriptions")
print("o - Output shopping cart")
print("q - Quit\n")
while option != 'a' and option != 'o' and option != 'i' and option != 'r' and option != 'c' and option != 'q':
option = input('Choose an option:\n')
if option == 'a':
cart.add_item()
if option == "r":
print("REMOVE ITEM FROM CART")
cart.remove_item(input("Enter name of item to remove:\n"))
if option == "c":
print("CHANGE ITEM QUANTITY")
cart.modify_item(input("Enter the item name:\n"))
if option == "i":
print("OUTPUT ITEMS' DESCRIPTIONS")
cart.print_descriptions()
if option == "o":
print("OUTPUT SHOPPING CART")
cart.print_total()
return option
if __name__ == '__main__':
# initialize and print customer name and date
name = input("Enter customer's name:\n")
date = input("Enter today's date:\n")
print()
print("Customer name:", name)
print("Today's date:", date)
option = ""
# create ShoppingCart object
cart1 = ShoppingCart(customer_name=name, current_date=date)
while option != "q":
print("")
option = print_menu(cart1)
|
Python
| 141
| 34.914894
| 114
|
/Lab_10.19.py
| 0.563784
| 0.559439
|
andrew-li729/CIS-2348-Homework-3
|
refs/heads/master
|
# Andrew Li
# 1824794
player_dict = {}
key_list = []
option = ''
# gets user input and adds to dictionary
for i in range(1, 6):
jersey_num = input("Enter player {}'s jersey number:\n".format(i))
player_rating = input("Enter player {}'s rating:\n".format(i))
print()
player_dict[jersey_num] = player_rating
# print(player_dict)
# adds dict keys to list to be able to be sorted
for key in player_dict:
key_list.append(key)
def print_roster():
key_list.sort(key=int)
# print(key_list) # for debugging
# prints roster created from user inputs
print("ROSTER")
for key in key_list:
print("Jersey number: {}, Rating: {}".format(key, player_dict[key]))
print_roster()
while option != 'q':
option = ''
print("\nMENU")
print("a - Add player")
print("d - Remove player")
print("u - Update player rating")
print("r - Output players above a rating")
print("o - Output roster")
print("q - Quit\n")
while option != 'a' and option != 'd' and option != 'u' and option != 'r' and option != 'o' and option != 'q':
option = input('Choose an option:\n')
if option == 'a':
new_jersey = input("Enter a new player's jersey number:\n")
new_rating = input("Enter the player's rating:\n")
player_dict[new_jersey] = new_rating
key_list.append(new_jersey)
if option == "d":
key_to_delete = input("Enter a jersey number:\n")
del player_dict[key_to_delete]
key_list.remove(key_to_delete)
if option == "u":
jersey_num = input("Enter a jersey number:\n")
player_rating = input("Enter a new rating for player:\n")
player_dict[jersey_num] = player_rating
if option == "r":
rating = input("Enter a rating:\n")
print("\nABOVE", rating)
for key in key_list:
if player_dict[key] > rating:
print("Jersey number: {}, Rating: {}".format(key, player_dict[key]))
if option == "o":
print_roster()
|
Python
| 66
| 29.5
| 114
|
/Lab_11.27.py
| 0.590164
| 0.585693
|
andrew-li729/CIS-2348-Homework-3
|
refs/heads/master
|
# Andrew Li
# 1824794
input_list = input().split(" ")
for i in range(0, len(input_list)):
input_list[i] = int(input_list[i])
input_list.sort()
# print(input_list) # for debugging
for num in input_list:
if num >= 0:
print(num, end=' ')
|
Python
| 12
| 19.916666
| 38
|
/Lab_11.18.py
| 0.59761
| 0.561753
|
andrew-li729/CIS-2348-Homework-3
|
refs/heads/master
|
# Andrew Li
# 1824794
input_list = input().split(" ")
for word in input_list:
print(word, input_list.count(word))
|
Python
| 7
| 15.714286
| 39
|
/Lab_11.22.py
| 0.630252
| 0.571429
|
andrew-li729/CIS-2348-Homework-3
|
refs/heads/master
|
# Andrew Li
# 1824794
class ItemToPurchase:
def __init__(self, item_name="none", item_price=0, item_quantity=0):
self.item_name = item_name
self.item_price = item_price
self.item_quantity = item_quantity
def print_item_cost(self):
print("{} {} @ ${:.0f} = ${:.0f}".format(self.item_name, self.item_quantity, self.item_price, self.item_price * self.item_quantity))
def compute_total(self):
return self.item_price * self.item_quantity
if __name__ == '__main__':
print("Item 1")
item1_name = input("Enter the item name:\n")
item1_price = float(input("Enter the item price:\n"))
item1_quantity = int(input("Enter the item quantity:\n"))
item1 = ItemToPurchase(item1_name, item1_price, item1_quantity)
print()
print("Item 2")
item2_name = input("Enter the item name:\n")
item2_price = float(input("Enter the item price:\n"))
item2_quantity = int(input("Enter the item quantity:\n"))
item2 = ItemToPurchase(item2_name, item2_price, item2_quantity)
print()
print("TOTAL COST")
item1.print_item_cost()
item2.print_item_cost()
total = item1.compute_total() + item2.compute_total()
print()
print("Total: ${:.0f}".format(total))
|
Python
| 37
| 32.675674
| 140
|
/Lab_10.17.py
| 0.630819
| 0.605136
|
grizzlypeaksoftware/tankbot
|
refs/heads/master
|
import RPi.GPIO as GPIO
from time import sleep
def Init():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3,GPIO.OUT,initial=GPIO.LOW) #blue
GPIO.setup(5,GPIO.OUT,initial=GPIO.LOW) #green
GPIO.setup(16,GPIO.OUT,initial=GPIO.LOW) #yellow
GPIO.setup(18,GPIO.OUT,initial=GPIO.LOW) #orange
Welcome()
def Welcome():
Stop()
Forward()
sleep(.5)
Reverse()
sleep(.5)
Right()
sleep(1)
Left()
sleep(1)
Stop()
def No():
Stop()
Right()
sleep(.25)
Left()
sleep(.25)
Right()
sleep(.25)
Left()
sleep(.25)
Stop()
def Yes():
Stop()
Forward()
sleep(.25)
Reverse()
sleep(.25)
Forward()
sleep(.25)
Reverse()
sleep(.25)
Stop()
def Forward():
GPIO.output(3,GPIO.LOW)
GPIO.output(5,GPIO.HIGH)
GPIO.output(16,GPIO.LOW)
GPIO.output(18,GPIO.HIGH)
def Reverse():
GPIO.output(3,GPIO.HIGH)
GPIO.output(5,GPIO.LOW)
GPIO.output(16,GPIO.HIGH)
GPIO.output(18,GPIO.LOW)
def Left():
GPIO.output(3,GPIO.LOW)
GPIO.output(5,GPIO.HIGH)
GPIO.output(16,GPIO.HIGH)
GPIO.output(18,GPIO.LOW)
def Right():
GPIO.output(3,GPIO.HIGH)
GPIO.output(5,GPIO.LOW)
GPIO.output(16,GPIO.LOW)
GPIO.output(18,GPIO.HIGH)
def Stop():
#print("Stop Tankbot")
GPIO.output(3,GPIO.LOW)
GPIO.output(5,GPIO.LOW)
GPIO.output(16,GPIO.LOW)
GPIO.output(18,GPIO.LOW)
def Close():
GPIO.cleanup()
|
Python
| 85
| 14.42353
| 51
|
/tankbot.py
| 0.677863
| 0.635114
|
grizzlypeaksoftware/tankbot
|
refs/heads/master
|
import tankbot
import keyboard
import time as _time
tankbot.Init()
recorded = []
recording_started = False
def ControlSwitch(key, event):
global recording_started
#print(key)
#print(event.event_type)
if key == "s":
tankbot.Stop()
if key == "up":
tankbot.Forward()
if key == "down":
tankbot.Reverse()
if key == "right":
tankbot.Right()
if key == "left":
tankbot.Left()
if key == "1":
tankbot.No()
if key == "2":
tankbot.Yes()
if key == "3":
tankbot.Welcome()
if key == "f1":
keyboard.start_recording()
recording_started = True
if key == "f2":
try:
if recording_started == True:
recording_started = False
Playback(keyboard.stop_recording())
else:
Playback(recorded)
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
if key == "q":
tankbot.Stop()
return False
return True
def Playback(rec):
last_time = None
global recorded
recorded = rec
for event in rec:
if last_time is not None:
_time.sleep(event.time - last_time)
last_time = event.time
key = event.scan_code or event.name
if event.name != "f2":
check = ControlSwitch(event.name, event)
continueLoop = True
while continueLoop:
try:
key = keyboard.read_key()
event = keyboard.read_event()
if event.event_type == "up":
continueLoop = ControlSwitch(key, event)
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
tankbot.Close()
|
Python
| 81
| 19.790123
| 69
|
/bot.py
| 0.649644
| 0.646081
|
lopuhin/scrapy-s3-bench
|
refs/heads/master
|
# -*- coding: utf-8 -*-
BOT_NAME = 's3bench'
SPIDER_MODULES = ['s3bench.spiders']
NEWSPIDER_MODULE = 's3bench.spiders'
USER_AGENT = (
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/51.0.2704.84 Safari/537.36')
ROBOTSTXT_OBEY = False
CONCURRENT_REQUESTS = 32
CONCURRENT_REQUESTS_PER_DOMAIN = 4
DOWNLOAD_MAXSIZE = 1*1024*1024
ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1}
COOKIES_ENABLED = False
TELNETCONSOLE_ENABLED = False
CLOSESPIDER_TIMEOUT = 30
DOWNLOAD_TIMEOUT = 15
LOG_LEVEL = 'INFO'
|
Python
| 29
| 19.068966
| 60
|
/s3bench/settings.py
| 0.702749
| 0.621993
|
lopuhin/scrapy-s3-bench
|
refs/heads/master
|
# -*- coding: utf-8 -*-
import os.path
import scrapy
from scrapy.linkextractors import LinkExtractor
import vmprof
class Spider(scrapy.Spider):
name = 'spider'
def __init__(self):
with open(os.path.join(
os.path.dirname(__file__), '..', 'top-1k.txt')) as f:
self.start_urls = ['http://{}'.format(line.strip()) for line in f]
self.le = LinkExtractor()
self.images_le = LinkExtractor(
tags=['img'], attrs=['src'], deny_extensions=[])
self.files_le = LinkExtractor(
tags=['a'], attrs=['href'], deny_extensions=[])
# Set up profiling
self.profile_filename = _get_prof_filename('vmprof')
self.profile = open(self.profile_filename, 'wb')
vmprof.enable(self.profile.fileno())
super(Spider, self).__init__()
def parse(self, response):
get_urls = lambda le: {link.url for link in le.extract_links(response)}
page_urls = get_urls(self.le)
for url in page_urls:
yield scrapy.Request(url)
file_urls = (
get_urls(self.images_le) | get_urls(self.files_le) - page_urls)
yield {
'url': response.url,
'file_urls': file_urls,
}
def closed(self, _):
vmprof.disable()
self.profile.close()
self.logger.info('vmprof saved to {}'.format(self.profile_filename))
def _get_prof_filename(prefix):
i = 1
while True:
filename = '{}_{}.vmprof'.format(prefix, i)
if not os.path.exists(filename):
return filename
i += 1
|
Python
| 55
| 28.163637
| 79
|
/s3bench/spiders.py
| 0.561097
| 0.558603
|
akabaker/firmware_state
|
refs/heads/master
|
#!/usr/bin/python -tt
from elementtree import ElementTree
from subprocess import Popen, PIPE
from urllib2 import urlopen, URLError, HTTPError
from socket import gethostname
from email import MIMEMultipart, MIMEText
import smtplib
import yaml
import re
class Omreport:
"""
Use omreport to determine if system firmware is up-to-date
"""
def __init__(self):
"""
Grab XML output from omreport and store it
"""
self.storage_tree = self._system_xml('storage controller')
self.system_tree = self._system_xml('system summary')
self.model = self._system_model()
self.hostname = gethostname()
def _system_xml(self, report):
"""
Call omreport and storage output as an element tree
@param: Report is a string, command line options for omreport
"""
try:
output = Popen('/opt/dell/srvadmin/bin/omreport %s -fmt xml' % (report), stdout=PIPE, shell=True).communicate()[0]
except OSError, e:
print "Execution failure: %s" % (e)
return
try:
root = ElementTree.fromstring(output)
tree = ElementTree.ElementTree(root)
except Exception, e:
print "Exception: %s" % (e)
return
return tree
def _system_model(self):
"""
Use facter to determine productname, i.e., r710, 2950 ,etc
"""
try:
output = Popen("facter | awk '/productname/ {print $NF}'", stdout=PIPE, shell=True).communicate()[0]
except OSError, e:
print "Execution failure: %s" % (e)
return
return output.strip()
def notify(om, yaml_data, mail_config):
tmpl = '-%s out of date, system version: %s -- latest version: %s <br>'
msg = "<strong>%s</strong>: <br>" % (om.hostname)
if 'bios' in om.errors:
msg += (tmpl) % ('BIOS', om.bios_ver, yaml_data['bios'])
if 'perc' in om.errors:
for (key, val) in om.outofdate.items():
msg += (tmpl) % (key, val, yaml_data['percs'][key])
message = MIMEMultipart.MIMEMultipart('alternative')
message['from'] = mail_config['from']
message['to'] = mail_config['to']
message['subject'] = mail_config['subject']
body = MIMEText.MIMEText(msg, 'html')
message.attach(body)
s = smtplib.SMTP('localhost')
s.sendmail(message['from'], message['to'], message.as_string())
s.quit()
def main(types, mail_config):
"""
Params: dict that contains the name of controller type, dict containing mail configuration
Gather omreport data and compare to yaml data corresponding to this machines model
"""
om = Omreport()
om.errors = []
om.percs = {}
om.outofdate = {}
pattern = re.compile(r'%s' % (types['controller']), re.I)
url = "http://rhn.missouri.edu/pub/dell-yaml/%s.yaml" % (om.model)
try:
req = urlopen(url)
except URLError, e:
print ("URLError: %s") % (e)
except HTTPError, e:
print ("HTTPError: %s") % (e)
yaml_data = yaml.load(req)
# Gather PERC name and firmware version
for node in om.storage_tree.findall('//DCStorageObject'):
perc_name = node.find('Name').text
perc_ver = node.find('FirmwareVer').text
om.percs[perc_name] = perc_ver
# BIOS version is easy
om.bios_ver = om.system_tree.find('//SystemBIOS/Version').text
# Compare with yaml_data
for perc_name, version in om.percs.items():
if version < yaml_data['percs'][perc_name]:
om.errors.append('perc')
om.outofdate[perc_name] = version
if om.bios_ver < yaml_data['bios']:
om.errors.append('bios')
if om.errors:
notify(om, yaml_data, mail_config)
if __name__ == "__main__":
types = {'controller': 'perc'}
mail_config = {
'subject': 'Firmware_report',
'to': 'bakerlu@missouri.edu',
'from': 'root@%s' % (gethostname()),
}
main(types, mail_config)
|
Python
| 135
| 25.200001
| 117
|
/firmwarestate.py
| 0.666101
| 0.663274
|
Leovilhena/mailbox2fs
|
refs/heads/master
|
import os
import email
import imaplib
import logging
import traceback
from time import sleep
from typing import Tuple
from pathlib import Path
from functools import wraps
# Global variables
SERVER = os.environ.get('FASTMAIL_IMAP_HOST', 'imap.fastmail.com')
PORT = os.environ.get('FASTMAIL_IMAP_PORT', 993)
USER = os.environ.get('FASTMAIL_USER')
PASSWORD = Path('/run/secrets/fastmail_passwd').read_text()
REFRESH_RATE = int(os.environ.get('REFRESH_RATE', 10))
UID_SET = set()
MAILBOX_PATH = os.environ.get('MAILBOX_PATH', '/mailbox')
MAILBOX_HOME = os.environ.get('MAILBOX_HOME', 'home')
# Logging config
logging.basicConfig(format='[*] %(levelname)s: %(message)s', level=os.environ.get("LOGLEVEL", "INFO"))
def log(msg):
"""
Decoratorm for printing a message before running function
:param msg: Message to be printed before running function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
logging.info(msg)
return func(*args, **kwargs)
return wrapper
return decorator
def set_uid_track_file(file: str = '.uid_track') -> None:
"""
Creates or loads a .uid_track file to prevent emails to be written twice.
If the app restarts (or simply fetches again emails), it will assume that the emails
written on the volume are new ones, hence, assigning [number] sufix to them.
By tracking their uid we prevent them to be doubly written.
"""
global UID_SET
file = os.path.join(MAILBOX_PATH, file)
try:
with open(file, 'r') as fd:
UID_SET = set(line.strip() for line in fd.readlines())
except FileNotFoundError:
pass
@log('Connecting to IMAP server')
def get_imap_connection() -> imaplib.IMAP4_SSL:
"""
Get IMAP4 connection object with 'INBOX' mailbox selected
:return: maplib.IMAP4_SSL object
"""
connection = imaplib.IMAP4_SSL(SERVER, PORT)
connection.login(USER, PASSWORD)
connection.select() # selects INBOX by default
return connection
@log('Parsing header fields')
def parse_header_fields(connection: imaplib.IMAP4_SSL, email_index: str) -> Tuple[str, str, tuple, str]:
"""
Parses HEADER fields sender, subject, date and Message-Id (as uid) from RFC822 standard
:param connection: Connection to IMAP server
:param email_index: Number from index list of emails
:return: (sender, subject, date, uid)
"""
typ, data = connection.fetch(email_index, '(RFC822)')
if typ != 'OK':
raise imaplib.IMAP4.error(f'Server replied with {typ} on email {email_index} while parsing the headers')
msg = email.message_from_bytes(data[0][1])
sender = email.utils.parseaddr(msg['From'])[1]
subject = msg["Subject"]
date = email.utils.parsedate(msg['date'])
uid = msg['Message-ID']
return sender, subject, date, uid
@log('Parsing email body')
def parse_body(connection: imaplib.IMAP4_SSL, email_index: str) -> str:
"""
Parses email body without attachments
:param connection: Connection to IMAP server
:param email_index: Number from index list of emails
:return: body str
"""
typ, data = connection.fetch(email_index, '(UID BODY[TEXT])')
if typ != 'OK':
raise imaplib.IMAP4.error(f'Server replied with {typ} on email {email_index} while parsing the body')
body = email.message_from_bytes(data[0][1]).as_string()
body = remove_html_from_body(body)
return body
@log('Erasing HTML from raw email body')
def remove_html_from_body(body: str) -> str:
"""
Email body is duplicated with HTML part, this function removes the HTML part if exists and it's duplicated.
:param body: email body
:return: body str
"""
body_split = body.split('\n')
uid = body_split[1]
index = len(body_split)
for i, line in enumerate(body_split):
if uid == line:
index = i
parsed_body = '\n'.join(body_split[:index])
if parsed_body:
return parsed_body
return body
@log('Writing to file')
def write_to_file(file: str, body: str, uid: str, index: int = 0) -> str:
"""
Write body content to file and name it after it's subject
If the file doesn't exist the algorithm will create a new file with a number between square brackets
based on their uid.
:param file: email file name
:param body: email body
:param uid: email unique identifier
:param index: index to be added to file name if it already exists
:return: final email file name str
"""
_file = os.path.join(MAILBOX_PATH, file)
if not os.path.isfile(_file):
logging.info(f'New email: {_file}')
with open(_file, 'w+') as fd:
fd.write(body)
update_uid_track_file(uid)
else:
file_split = file.rsplit('[', 1)[0]
new_index = index + 1
new_file = f'{file_split}[{new_index}]' # format "subject[1]"
file = write_to_file(file=new_file, body=body, uid=uid, index=new_index) # recursion
return file
@log('Adding new uid to uid_track file')
def update_uid_track_file(uid: str, file: str = '.uid_track') -> None:
"""
Updates uid_track file with newly fetched uid's
:param uid: email unique identifier
:param file: uid_track file path
"""
file = os.path.join(MAILBOX_PATH, file)
with open(file, 'a+') as fd:
fd.write(f'{uid}\n')
logging.info(f'New {uid} added')
UID_SET.add(uid)
@log('Creating fs hardlink tree')
def create_fs_hardlink_tree(email_path: str, dest: str) -> None:
"""
Create directories and hardlinks at their end's according to their destination.
:param email_path: path to where email is saved
:param dest: path to where the hardlink will be created
"""
if not os.path.isdir(dest):
logging.info(f'Directory at {dest} already exists. Nothing to do')
os.makedirs(dest)
dest_path = os.path.join(dest, email_path)
src_path = os.path.join(MAILBOX_PATH, email_path)
print(f'[*****] Path is {dest_path}')
if not os.path.isfile(dest_path):
logging.info(f'Creating path at {dest_path}')
Path(src_path).link_to(dest_path)
def main():
try:
connection = get_imap_connection()
typ, _data = connection.search(None, 'ALL')
if typ != 'OK':
raise imaplib.IMAP4.error(f'Server replied with {typ}')
# Loop on every email fetched
for email_index in _data[0].split():
# Parse data
sender, subject, date, uid = parse_header_fields(connection, email_index)
if uid in UID_SET:
logging.info('No new emails')
continue
# Parse body
body = parse_body(connection, email_index)
# create file at base level MAILBOX_PATH
file = f'{sender}-{subject}'
email_path = write_to_file(file=file, body=body, uid=uid)
# create dir and symlink to email for /timeline/{year}/{month}/{day}/
dest_date = os.path.join(MAILBOX_PATH, MAILBOX_HOME, 'timeline/{}/{}/{}/'.format(*date))
create_fs_hardlink_tree(email_path=email_path, dest=dest_date)
# create dir and symlink to email for /sender/{email}/
dest_sender = os.path.join(MAILBOX_PATH, MAILBOX_HOME, 'sender/{}/'.format(sender))
create_fs_hardlink_tree(email_path=email_path, dest=dest_sender)
# TODO '/topics/{IMAP folder path}/'
_ = connection.close() # ('OK', [b'Completed'])
_ = connection.logout() # ('BYE', [b'LOGOUT received'])
except imaplib.IMAP4.error:
traceback.print_exc(limit=1)
if __name__ == '__main__':
set_uid_track_file()
while True:
main()
sleep(REFRESH_RATE)
|
Python
| 235
| 32.136169
| 112
|
/app/main.py
| 0.634262
| 0.629896
|
yoongyo/TsF
|
refs/heads/master
|
from .models import Post
from django import forms
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
'title',
'Tourtype',
'Country',
'City',
'Language',
'DetailContent',
'BriefContent',
'HashTag',
'MeetingPoint',
'MeetingTime',
'Map',
'Direction',
'CourseName',
'Duration',
'Price',
'Minimum',
'Maximum',
'Price_include',
'NotDate',
'GuestInfo',
]
def save(self, commit=True):
post = Post(**self.cleaned_data)
if commit:
post.save()
return post
|
Python
| 36
| 20.527779
| 40
|
/ch1/travel/forms.py
| 0.420645
| 0.420645
|
moozer/ProItsScripts
|
refs/heads/master
|
#!/usr/bin/env python
# pushes data to a given server
from ftplib import FTP, FTP_TLS
import sys
import os
import paramiko
FilesToPut = ['../php/basedata.php']
def Push( FtpServer, Username, Password, uploadlist = FilesToPut, port = 21, passive = False, Sftp = False ):
print "Login to %s:%s using %s:%s (%s)"%(FtpServer, port, Username, 'xxx',
'passive' if passive else 'active')
if Sftp:
paramiko.util.log_to_file('/tmp/paramiko.log')
transport = paramiko.Transport((FtpServer,int(port)))
transport.connect(username = Username, password = Password)
sftp = paramiko.SFTPClient.from_transport(transport)
for f in uploadlist:
print "uploading %s"%f
sftp.put(f, os.path.basename(f))
sftp.close()
transport.close()
else:
ftp = FTP()
ftp.connect( FtpServer, port )
ftp.login( Username, Password )
ftp.set_pasv( passive )
for f in uploadlist:
print "uploading %s"%f
fp = open( f, 'rb')
ftp.storbinary('STOR %s'%os.path.basename(f), fp) # send the file
ftp.quit()
if __name__ == "__main__":
if len(sys.argv) < 5:
print >> sys.stderr, "usage %s <server> <port> <username> <password>"%sys.argv[0]
exit( 1 )
FtpServer = sys.argv[1]
Port = sys.argv[2]
Username = sys.argv[3]
Passwd = sys.argv[4]
Push( FtpServer, Username, Passwd, port = Port )
print >> sys.stderr, "Done"
|
Python
| 51
| 29.274509
| 109
|
/scripts/PushToFtp.py
| 0.573187
| 0.567358
|
moozer/ProItsScripts
|
refs/heads/master
|
#!/usr/bin/env python
import sys
import urllib2
import json
def FetchBaseData( URL ):
print 'Fetching basedata from %s :'%(URL,)
# fetch data
req = urllib2.Request(URL)
response = urllib2.urlopen(req)
jsondata = response.read()
response.close()
# parsing json
data = json.loads( jsondata )
print 'Data fetched: hostname: %s, php version: %s, timestamp: %s'%(data['hostname'], data['version'], data['date'])
return data
if __name__ == '__main__':
# command line args.
if len(sys.argv) < 3:
print "usage %s <id> <URL>"%sys.argv[0]
exit( 1 )
GroupId = sys.argv[1]
URL = sys.argv[2]
# parsing json
data = FetchBaseData( URL )
|
Python
| 38
| 16.473684
| 117
|
/scripts/CheckBaseData.py
| 0.635277
| 0.623318
|
moozer/ProItsScripts
|
refs/heads/master
|
#!/usr/bin/env python
# reads config and pushes data
import ConfigParser
from CheckBaseData import FetchBaseData
Grouplist = "../grouplist.txt"
GroupNames = ["Group01", "Group02", "Group03", "Group04", "Group05", "Group06", "Group07", "Group08" ]
if __name__ == "__main__":
#config = ConfigParser.ConfigParser()
config = ConfigParser.SafeConfigParser()
config.read( Grouplist )
for group in GroupNames:
print "Group: %s"%group
try:
WebUrl = config.get(group, 'weburl' )
FetchBaseData( WebUrl+'basedata.php')
except Exception, e:
print "Something went wrong: %s"%e
|
Python
| 23
| 24.652174
| 102
|
/scripts/ReadAllBase.py
| 0.692047
| 0.664975
|
moozer/ProItsScripts
|
refs/heads/master
|
#!/usr/bin/env python
# reads config and pushes data
import ConfigParser
from PushToFtp import Push
Grouplist = "../grouplist.txt"
GroupNames = ["Group01", "Group02", "Group03", "Group04", "Group05", "Group06", "Group07", "Group08" ]
if __name__ == "__main__":
#config = ConfigParser.ConfigParser()
config = ConfigParser.SafeConfigParser( {'port': '21', 'passive': False, 'sftp': False })
config.read( Grouplist )
for group in GroupNames:
print "Group: %s"%group
try:
Username = config.get(group, 'user' )
FtpServer = config.get(group, 'ip' )
Passwd = config.get(group, 'pass' )
WebUrl = config.get(group, 'weburl' )
port = config.get(group, 'port' )
passive = config.get(group, 'passive' )
sftp = config.get(group, 'sftp')
Push( FtpServer, Username, Passwd, port=port,
passive=True if passive == 'True' else False,
Sftp=True if sftp == 'True' else False)
except Exception, e:
print "Something went wrong: %s"%e
|
Python
| 31
| 30.096775
| 102
|
/scripts/PushAll.py
| 0.658031
| 0.639378
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
from __future__ import print_function
import time
import io_stockx
from io_stockx.rest import ApiException
from pprint import pprint
class ExampleConstants:
AWS_API_KEY = "<API Key>"
STOCKX_USERNAME = "<StockX Username>"
STOCKX_PASSWORD = "<StockX Password>"
DEMO_PRODUCT_ID = "air-jordan-1-retro-high-off-white-chicago"
DEMO_CUSTOMER_ID = "1471698"
ENABLE_DEBUG = True
JWT_HEADER = "Jwt-Authorization"
|
Python
| 21
| 19.666666
| 65
|
/sdk/python/src/example_constants.py
| 0.699769
| 0.681293
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from io_stockx.api_client import ApiClient
class StockXApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def delete_portfolio(self, id, portfolio, **kwargs): # noqa: E501
"""Deletes a portfolio item from the market with the specified id. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_portfolio(id, portfolio, async=True)
>>> result = thread.get()
:param async bool
:param str id: The id of the portfolio item to delete. (required)
:param PortfolioIdDelRequest portfolio: The request information for the portfolio delete operation. (required)
:return: PortfolioIdDelResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.delete_portfolio_with_http_info(id, portfolio, **kwargs) # noqa: E501
else:
(data) = self.delete_portfolio_with_http_info(id, portfolio, **kwargs) # noqa: E501
return data
def delete_portfolio_with_http_info(self, id, portfolio, **kwargs): # noqa: E501
"""Deletes a portfolio item from the market with the specified id. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_portfolio_with_http_info(id, portfolio, async=True)
>>> result = thread.get()
:param async bool
:param str id: The id of the portfolio item to delete. (required)
:param PortfolioIdDelRequest portfolio: The request information for the portfolio delete operation. (required)
:return: PortfolioIdDelResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id', 'portfolio'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params or
params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `delete_portfolio`") # noqa: E501
# verify the required parameter 'portfolio' is set
if ('portfolio' not in params or
params['portfolio'] is None):
raise ValueError("Missing the required parameter `portfolio` when calling `delete_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in params:
path_params['id'] = params['id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'portfolio' in params:
body_params = params['portfolio']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/portfolio/{id}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PortfolioIdDelResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_webhook(self, id, **kwargs): # noqa: E501
"""delete_webhook # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_webhook(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.delete_webhook_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.delete_webhook_with_http_info(id, **kwargs) # noqa: E501
return data
def delete_webhook_with_http_info(self, id, **kwargs): # noqa: E501
"""delete_webhook # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_webhook_with_http_info(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_webhook" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params or
params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `delete_webhook`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in params:
path_params['id'] = params['id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/webhook/v1/webhooks/{id}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_open_orders(self, id, **kwargs): # noqa: E501
"""get_open_orders # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_open_orders(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: The customer id to lookup open orders with. (required)
:return: CustomersIdSellingCurrent
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_open_orders_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.get_open_orders_with_http_info(id, **kwargs) # noqa: E501
return data
def get_open_orders_with_http_info(self, id, **kwargs): # noqa: E501
"""get_open_orders # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_open_orders_with_http_info(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: The customer id to lookup open orders with. (required)
:return: CustomersIdSellingCurrent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_open_orders" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params or
params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `get_open_orders`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in params:
path_params['id'] = params['id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['JWT', 'api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/customers/{id}/selling/current', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CustomersIdSellingCurrent', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_portfolio(self, portfolio, **kwargs): # noqa: E501
"""Returns a market portfolio identified by request parameters. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_portfolio(portfolio, async=True)
>>> result = thread.get()
:param async bool
:param PortfolioRequest portfolio: Requests parameters for looking up a market portfolio. (required)
:return: PortfolioResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_portfolio_with_http_info(portfolio, **kwargs) # noqa: E501
else:
(data) = self.get_portfolio_with_http_info(portfolio, **kwargs) # noqa: E501
return data
def get_portfolio_with_http_info(self, portfolio, **kwargs): # noqa: E501
"""Returns a market portfolio identified by request parameters. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_portfolio_with_http_info(portfolio, async=True)
>>> result = thread.get()
:param async bool
:param PortfolioRequest portfolio: Requests parameters for looking up a market portfolio. (required)
:return: PortfolioResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['portfolio'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'portfolio' is set
if ('portfolio' not in params or
params['portfolio'] is None):
raise ValueError("Missing the required parameter `portfolio` when calling `get_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'portfolio' in params:
body_params = params['portfolio']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/portfolio', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PortfolioResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_portfolio_item(self, id, **kwargs): # noqa: E501
"""get_portfolio_item # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_portfolio_item(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: The id of the portfolio item to lookup. (required)
:return: PortfolioitemsIdGetResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_portfolio_item_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.get_portfolio_item_with_http_info(id, **kwargs) # noqa: E501
return data
def get_portfolio_item_with_http_info(self, id, **kwargs): # noqa: E501
"""get_portfolio_item # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_portfolio_item_with_http_info(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: The id of the portfolio item to lookup. (required)
:return: PortfolioitemsIdGetResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_portfolio_item" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params or
params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `get_portfolio_item`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in params:
path_params['id'] = params['id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['JWT', 'api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/portfolioitems/{id}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PortfolioitemsIdGetResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_product_by_id(self, id, **kwargs): # noqa: E501
"""get_product_by_id # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_product_by_id(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: The id of the product to return. (required)
:param str include:
:return: ProductResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_product_by_id_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.get_product_by_id_with_http_info(id, **kwargs) # noqa: E501
return data
def get_product_by_id_with_http_info(self, id, **kwargs): # noqa: E501
"""get_product_by_id # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_product_by_id_with_http_info(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: The id of the product to return. (required)
:param str include:
:return: ProductResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id', 'include'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_product_by_id" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params or
params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `get_product_by_id`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in params:
path_params['id'] = params['id'] # noqa: E501
query_params = []
if 'include' in params:
query_params.append(('include', params['include'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['JWT', 'api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/products/{id}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ProductResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_product_market_data(self, product_id, **kwargs): # noqa: E501
"""Provides historical market data for a given product. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_product_market_data(product_id, async=True)
>>> result = thread.get()
:param async bool
:param str product_id: The product's product UUID (required)
:param str sku: The product's SKU
:return: MarketData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_product_market_data_with_http_info(product_id, **kwargs) # noqa: E501
else:
(data) = self.get_product_market_data_with_http_info(product_id, **kwargs) # noqa: E501
return data
def get_product_market_data_with_http_info(self, product_id, **kwargs): # noqa: E501
"""Provides historical market data for a given product. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_product_market_data_with_http_info(product_id, async=True)
>>> result = thread.get()
:param async bool
:param str product_id: The product's product UUID (required)
:param str sku: The product's SKU
:return: MarketData
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['product_id', 'sku'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_product_market_data" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params or
params['product_id'] is None):
raise ValueError("Missing the required parameter `product_id` when calling `get_product_market_data`") # noqa: E501
collection_formats = {}
path_params = {}
if 'product_id' in params:
path_params['productId'] = params['product_id'] # noqa: E501
query_params = []
if 'sku' in params:
query_params.append(('sku', params['sku'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['JWT', 'api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/products/{productId}/market', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='MarketData', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_subscriptions(self, **kwargs): # noqa: E501
"""get_subscriptions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_subscriptions(async=True)
>>> result = thread.get()
:param async bool
:return: SubscriptionsResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_subscriptions_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_subscriptions_with_http_info(**kwargs) # noqa: E501
return data
def get_subscriptions_with_http_info(self, **kwargs): # noqa: E501
"""get_subscriptions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_subscriptions_with_http_info(async=True)
>>> result = thread.get()
:param async bool
:return: SubscriptionsResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_subscriptions" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/webhook/v1/subscriptions', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='SubscriptionsResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_webhook(self, id, **kwargs): # noqa: E501
"""get_webhook # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_webhook(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: (required)
:return: WebhooksIdGetResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_webhook_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.get_webhook_with_http_info(id, **kwargs) # noqa: E501
return data
def get_webhook_with_http_info(self, id, **kwargs): # noqa: E501
"""get_webhook # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_webhook_with_http_info(id, async=True)
>>> result = thread.get()
:param async bool
:param str id: (required)
:return: WebhooksIdGetResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_webhook" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params or
params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `get_webhook`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in params:
path_params['id'] = params['id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/webhook/v1/webhooks/{id}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='WebhooksIdGetResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_webhooks(self, **kwargs): # noqa: E501
"""get_webhooks # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_webhooks(async=True)
>>> result = thread.get()
:param async bool
:return: WebhooksGetResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_webhooks_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_webhooks_with_http_info(**kwargs) # noqa: E501
return data
def get_webhooks_with_http_info(self, **kwargs): # noqa: E501
"""get_webhooks # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_webhooks_with_http_info(async=True)
>>> result = thread.get()
:param async bool
:return: WebhooksGetResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_webhooks" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/webhook/v1/webhooks', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='WebhooksGetResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def login(self, login, **kwargs): # noqa: E501
"""Attempts to log the user in with a username and password. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.login(login, async=True)
>>> result = thread.get()
:param async bool
:param LoginRequest login: Object that contains the user's authentication credentials.' (required)
:return: LoginResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.login_with_http_info(login, **kwargs) # noqa: E501
else:
(data) = self.login_with_http_info(login, **kwargs) # noqa: E501
return data
def login_with_http_info(self, login, **kwargs): # noqa: E501
"""Attempts to log the user in with a username and password. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.login_with_http_info(login, async=True)
>>> result = thread.get()
:param async bool
:param LoginRequest login: Object that contains the user's authentication credentials.' (required)
:return: LoginResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['login'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method login" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'login' is set
if ('login' not in params or
params['login'] is None):
raise ValueError("Missing the required parameter `login` when calling `login`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'login' in params:
body_params = params['login']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/login', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='LoginResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def lookup_product(self, **kwargs): # noqa: E501
"""lookup_product # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.lookup_product(async=True)
>>> result = thread.get()
:param async bool
:param str identifier: The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago)
:param str size: The size of the product.
:return: ProductInfo
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.lookup_product_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.lookup_product_with_http_info(**kwargs) # noqa: E501
return data
def lookup_product_with_http_info(self, **kwargs): # noqa: E501
"""lookup_product # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.lookup_product_with_http_info(async=True)
>>> result = thread.get()
:param async bool
:param str identifier: The product identifier to lookup, e.g. (air-jordan-1-retro-high-off-white-chicago)
:param str size: The size of the product.
:return: ProductInfo
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['identifier', 'size'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method lookup_product" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'identifier' in params:
query_params.append(('identifier', params['identifier'])) # noqa: E501
if 'size' in params:
query_params.append(('size', params['size'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['JWT', 'api_key'] # noqa: E501
return self.api_client.call_api(
'/product/lookup', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ProductInfo', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def new_portfolio_ask(self, portfolio, **kwargs): # noqa: E501
"""Creates a new seller ask on the market for a given product. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.new_portfolio_ask(portfolio, async=True)
>>> result = thread.get()
:param async bool
:param PortfolioRequest portfolio: The portfolio request representing the ask to place on the market. (required)
:return: PortfolioResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.new_portfolio_ask_with_http_info(portfolio, **kwargs) # noqa: E501
else:
(data) = self.new_portfolio_ask_with_http_info(portfolio, **kwargs) # noqa: E501
return data
def new_portfolio_ask_with_http_info(self, portfolio, **kwargs): # noqa: E501
"""Creates a new seller ask on the market for a given product. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.new_portfolio_ask_with_http_info(portfolio, async=True)
>>> result = thread.get()
:param async bool
:param PortfolioRequest portfolio: The portfolio request representing the ask to place on the market. (required)
:return: PortfolioResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['portfolio'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method new_portfolio_ask" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'portfolio' is set
if ('portfolio' not in params or
params['portfolio'] is None):
raise ValueError("Missing the required parameter `portfolio` when calling `new_portfolio_ask`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'portfolio' in params:
body_params = params['portfolio']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/portfolio/ask', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PortfolioResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def new_portfolio_bid(self, portfolio, **kwargs): # noqa: E501
"""Creates a new buyer bid on the market for a given product. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.new_portfolio_bid(portfolio, async=True)
>>> result = thread.get()
:param async bool
:param PortfolioRequest portfolio: The portfolio request representing the bid to place on the market. (required)
:return: PortfolioResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.new_portfolio_bid_with_http_info(portfolio, **kwargs) # noqa: E501
else:
(data) = self.new_portfolio_bid_with_http_info(portfolio, **kwargs) # noqa: E501
return data
def new_portfolio_bid_with_http_info(self, portfolio, **kwargs): # noqa: E501
"""Creates a new buyer bid on the market for a given product. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.new_portfolio_bid_with_http_info(portfolio, async=True)
>>> result = thread.get()
:param async bool
:param PortfolioRequest portfolio: The portfolio request representing the bid to place on the market. (required)
:return: PortfolioResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['portfolio'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method new_portfolio_bid" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'portfolio' is set
if ('portfolio' not in params or
params['portfolio'] is None):
raise ValueError("Missing the required parameter `portfolio` when calling `new_portfolio_bid`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'portfolio' in params:
body_params = params['portfolio']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/v1/portfolio/bid', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='PortfolioResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def post_webhooks(self, portfolio, **kwargs): # noqa: E501
"""post_webhooks # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.post_webhooks(portfolio, async=True)
>>> result = thread.get()
:param async bool
:param WebhooksPostRequest portfolio: (required)
:return: WebhooksPostResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.post_webhooks_with_http_info(portfolio, **kwargs) # noqa: E501
else:
(data) = self.post_webhooks_with_http_info(portfolio, **kwargs) # noqa: E501
return data
def post_webhooks_with_http_info(self, portfolio, **kwargs): # noqa: E501
"""post_webhooks # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.post_webhooks_with_http_info(portfolio, async=True)
>>> result = thread.get()
:param async bool
:param WebhooksPostRequest portfolio: (required)
:return: WebhooksPostResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['portfolio'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method post_webhooks" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'portfolio' is set
if ('portfolio' not in params or
params['portfolio'] is None):
raise ValueError("Missing the required parameter `portfolio` when calling `post_webhooks`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'portfolio' in params:
body_params = params['portfolio']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_key'] # noqa: E501
return self.api_client.call_api(
'/webhook/v1/webhooks', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='WebhooksPostResponse', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def search(self, query, **kwargs): # noqa: E501
"""Searches for products by keyword. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.search(query, async=True)
>>> result = thread.get()
:param async bool
:param str query: The phrase or keyword to search with. (required)
:return: SearchResults
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.search_with_http_info(query, **kwargs) # noqa: E501
else:
(data) = self.search_with_http_info(query, **kwargs) # noqa: E501
return data
def search_with_http_info(self, query, **kwargs): # noqa: E501
"""Searches for products by keyword. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.search_with_http_info(query, async=True)
>>> result = thread.get()
:param async bool
:param str query: The phrase or keyword to search with. (required)
:return: SearchResults
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['query'] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method search" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'query' is set
if ('query' not in params or
params['query'] is None):
raise ValueError("Missing the required parameter `query` when calling `search`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if 'query' in params:
query_params.append(('query', params['query'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['JWT', 'api_key'] # noqa: E501
return self.api_client.call_api(
'/v2/search', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='SearchResults', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
Python
| 1,554
| 36.826256
| 176
|
/sdk/python/lib/build/lib/io_stockx/api/stock_x_api.py
| 0.572488
| 0.561686
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class MarketDataMarket(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'product_id': 'int',
'sku_uuid': 'str',
'product_uuid': 'str',
'lowest_ask': 'int',
'lowest_ask_size': 'str',
'parent_lowest_ask': 'int',
'number_of_asks': 'int',
'sales_this_period': 'int',
'sales_last_period': 'int',
'highest_bid': 'int',
'highest_bid_size': 'str',
'number_of_bids': 'int',
'annual_high': 'int',
'annual_low': 'int',
'deadstock_range_low': 'int',
'deadstock_range_high': 'int',
'volatility': 'float',
'deadstock_sold': 'int',
'price_premium': 'float',
'average_deadstock_price': 'int',
'last_sale': 'int',
'last_sale_size': 'str',
'sales_last72_hours': 'int',
'change_value': 'int',
'change_percentage': 'float',
'abs_change_percentage': 'float',
'total_dollars': 'int',
'updated_at': 'int',
'last_lowest_ask_time': 'int',
'last_highest_bid_time': 'int',
'last_sale_date': 'str',
'created_at': 'str',
'deadstock_sold_rank': 'int',
'price_premium_rank': 'int',
'average_deadstock_price_rank': 'int',
'featured': 'str'
}
attribute_map = {
'product_id': 'productId',
'sku_uuid': 'skuUuid',
'product_uuid': 'productUuid',
'lowest_ask': 'lowestAsk',
'lowest_ask_size': 'lowestAskSize',
'parent_lowest_ask': 'parentLowestAsk',
'number_of_asks': 'numberOfAsks',
'sales_this_period': 'salesThisPeriod',
'sales_last_period': 'salesLastPeriod',
'highest_bid': 'highestBid',
'highest_bid_size': 'highestBidSize',
'number_of_bids': 'numberOfBids',
'annual_high': 'annualHigh',
'annual_low': 'annualLow',
'deadstock_range_low': 'deadstockRangeLow',
'deadstock_range_high': 'deadstockRangeHigh',
'volatility': 'volatility',
'deadstock_sold': 'deadstockSold',
'price_premium': 'pricePremium',
'average_deadstock_price': 'averageDeadstockPrice',
'last_sale': 'lastSale',
'last_sale_size': 'lastSaleSize',
'sales_last72_hours': 'salesLast72Hours',
'change_value': 'changeValue',
'change_percentage': 'changePercentage',
'abs_change_percentage': 'absChangePercentage',
'total_dollars': 'totalDollars',
'updated_at': 'updatedAt',
'last_lowest_ask_time': 'lastLowestAskTime',
'last_highest_bid_time': 'lastHighestBidTime',
'last_sale_date': 'lastSaleDate',
'created_at': 'createdAt',
'deadstock_sold_rank': 'deadstockSoldRank',
'price_premium_rank': 'pricePremiumRank',
'average_deadstock_price_rank': 'averageDeadstockPriceRank',
'featured': 'featured'
}
def __init__(self, product_id=None, sku_uuid=None, product_uuid=None, lowest_ask=None, lowest_ask_size=None, parent_lowest_ask=None, number_of_asks=None, sales_this_period=None, sales_last_period=None, highest_bid=None, highest_bid_size=None, number_of_bids=None, annual_high=None, annual_low=None, deadstock_range_low=None, deadstock_range_high=None, volatility=None, deadstock_sold=None, price_premium=None, average_deadstock_price=None, last_sale=None, last_sale_size=None, sales_last72_hours=None, change_value=None, change_percentage=None, abs_change_percentage=None, total_dollars=None, updated_at=None, last_lowest_ask_time=None, last_highest_bid_time=None, last_sale_date=None, created_at=None, deadstock_sold_rank=None, price_premium_rank=None, average_deadstock_price_rank=None, featured=None): # noqa: E501
"""MarketDataMarket - a model defined in Swagger""" # noqa: E501
self._product_id = None
self._sku_uuid = None
self._product_uuid = None
self._lowest_ask = None
self._lowest_ask_size = None
self._parent_lowest_ask = None
self._number_of_asks = None
self._sales_this_period = None
self._sales_last_period = None
self._highest_bid = None
self._highest_bid_size = None
self._number_of_bids = None
self._annual_high = None
self._annual_low = None
self._deadstock_range_low = None
self._deadstock_range_high = None
self._volatility = None
self._deadstock_sold = None
self._price_premium = None
self._average_deadstock_price = None
self._last_sale = None
self._last_sale_size = None
self._sales_last72_hours = None
self._change_value = None
self._change_percentage = None
self._abs_change_percentage = None
self._total_dollars = None
self._updated_at = None
self._last_lowest_ask_time = None
self._last_highest_bid_time = None
self._last_sale_date = None
self._created_at = None
self._deadstock_sold_rank = None
self._price_premium_rank = None
self._average_deadstock_price_rank = None
self._featured = None
self.discriminator = None
if product_id is not None:
self.product_id = product_id
if sku_uuid is not None:
self.sku_uuid = sku_uuid
if product_uuid is not None:
self.product_uuid = product_uuid
if lowest_ask is not None:
self.lowest_ask = lowest_ask
if lowest_ask_size is not None:
self.lowest_ask_size = lowest_ask_size
if parent_lowest_ask is not None:
self.parent_lowest_ask = parent_lowest_ask
if number_of_asks is not None:
self.number_of_asks = number_of_asks
if sales_this_period is not None:
self.sales_this_period = sales_this_period
if sales_last_period is not None:
self.sales_last_period = sales_last_period
if highest_bid is not None:
self.highest_bid = highest_bid
if highest_bid_size is not None:
self.highest_bid_size = highest_bid_size
if number_of_bids is not None:
self.number_of_bids = number_of_bids
if annual_high is not None:
self.annual_high = annual_high
if annual_low is not None:
self.annual_low = annual_low
if deadstock_range_low is not None:
self.deadstock_range_low = deadstock_range_low
if deadstock_range_high is not None:
self.deadstock_range_high = deadstock_range_high
if volatility is not None:
self.volatility = volatility
if deadstock_sold is not None:
self.deadstock_sold = deadstock_sold
if price_premium is not None:
self.price_premium = price_premium
if average_deadstock_price is not None:
self.average_deadstock_price = average_deadstock_price
if last_sale is not None:
self.last_sale = last_sale
if last_sale_size is not None:
self.last_sale_size = last_sale_size
if sales_last72_hours is not None:
self.sales_last72_hours = sales_last72_hours
if change_value is not None:
self.change_value = change_value
if change_percentage is not None:
self.change_percentage = change_percentage
if abs_change_percentage is not None:
self.abs_change_percentage = abs_change_percentage
if total_dollars is not None:
self.total_dollars = total_dollars
if updated_at is not None:
self.updated_at = updated_at
if last_lowest_ask_time is not None:
self.last_lowest_ask_time = last_lowest_ask_time
if last_highest_bid_time is not None:
self.last_highest_bid_time = last_highest_bid_time
if last_sale_date is not None:
self.last_sale_date = last_sale_date
if created_at is not None:
self.created_at = created_at
if deadstock_sold_rank is not None:
self.deadstock_sold_rank = deadstock_sold_rank
if price_premium_rank is not None:
self.price_premium_rank = price_premium_rank
if average_deadstock_price_rank is not None:
self.average_deadstock_price_rank = average_deadstock_price_rank
if featured is not None:
self.featured = featured
@property
def product_id(self):
"""Gets the product_id of this MarketDataMarket. # noqa: E501
:return: The product_id of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._product_id
@product_id.setter
def product_id(self, product_id):
"""Sets the product_id of this MarketDataMarket.
:param product_id: The product_id of this MarketDataMarket. # noqa: E501
:type: int
"""
self._product_id = product_id
@property
def sku_uuid(self):
"""Gets the sku_uuid of this MarketDataMarket. # noqa: E501
:return: The sku_uuid of this MarketDataMarket. # noqa: E501
:rtype: str
"""
return self._sku_uuid
@sku_uuid.setter
def sku_uuid(self, sku_uuid):
"""Sets the sku_uuid of this MarketDataMarket.
:param sku_uuid: The sku_uuid of this MarketDataMarket. # noqa: E501
:type: str
"""
self._sku_uuid = sku_uuid
@property
def product_uuid(self):
"""Gets the product_uuid of this MarketDataMarket. # noqa: E501
:return: The product_uuid of this MarketDataMarket. # noqa: E501
:rtype: str
"""
return self._product_uuid
@product_uuid.setter
def product_uuid(self, product_uuid):
"""Sets the product_uuid of this MarketDataMarket.
:param product_uuid: The product_uuid of this MarketDataMarket. # noqa: E501
:type: str
"""
self._product_uuid = product_uuid
@property
def lowest_ask(self):
"""Gets the lowest_ask of this MarketDataMarket. # noqa: E501
:return: The lowest_ask of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._lowest_ask
@lowest_ask.setter
def lowest_ask(self, lowest_ask):
"""Sets the lowest_ask of this MarketDataMarket.
:param lowest_ask: The lowest_ask of this MarketDataMarket. # noqa: E501
:type: int
"""
self._lowest_ask = lowest_ask
@property
def lowest_ask_size(self):
"""Gets the lowest_ask_size of this MarketDataMarket. # noqa: E501
:return: The lowest_ask_size of this MarketDataMarket. # noqa: E501
:rtype: str
"""
return self._lowest_ask_size
@lowest_ask_size.setter
def lowest_ask_size(self, lowest_ask_size):
"""Sets the lowest_ask_size of this MarketDataMarket.
:param lowest_ask_size: The lowest_ask_size of this MarketDataMarket. # noqa: E501
:type: str
"""
self._lowest_ask_size = lowest_ask_size
@property
def parent_lowest_ask(self):
"""Gets the parent_lowest_ask of this MarketDataMarket. # noqa: E501
:return: The parent_lowest_ask of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._parent_lowest_ask
@parent_lowest_ask.setter
def parent_lowest_ask(self, parent_lowest_ask):
"""Sets the parent_lowest_ask of this MarketDataMarket.
:param parent_lowest_ask: The parent_lowest_ask of this MarketDataMarket. # noqa: E501
:type: int
"""
self._parent_lowest_ask = parent_lowest_ask
@property
def number_of_asks(self):
"""Gets the number_of_asks of this MarketDataMarket. # noqa: E501
:return: The number_of_asks of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._number_of_asks
@number_of_asks.setter
def number_of_asks(self, number_of_asks):
"""Sets the number_of_asks of this MarketDataMarket.
:param number_of_asks: The number_of_asks of this MarketDataMarket. # noqa: E501
:type: int
"""
self._number_of_asks = number_of_asks
@property
def sales_this_period(self):
"""Gets the sales_this_period of this MarketDataMarket. # noqa: E501
:return: The sales_this_period of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._sales_this_period
@sales_this_period.setter
def sales_this_period(self, sales_this_period):
"""Sets the sales_this_period of this MarketDataMarket.
:param sales_this_period: The sales_this_period of this MarketDataMarket. # noqa: E501
:type: int
"""
self._sales_this_period = sales_this_period
@property
def sales_last_period(self):
"""Gets the sales_last_period of this MarketDataMarket. # noqa: E501
:return: The sales_last_period of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._sales_last_period
@sales_last_period.setter
def sales_last_period(self, sales_last_period):
"""Sets the sales_last_period of this MarketDataMarket.
:param sales_last_period: The sales_last_period of this MarketDataMarket. # noqa: E501
:type: int
"""
self._sales_last_period = sales_last_period
@property
def highest_bid(self):
"""Gets the highest_bid of this MarketDataMarket. # noqa: E501
:return: The highest_bid of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._highest_bid
@highest_bid.setter
def highest_bid(self, highest_bid):
"""Sets the highest_bid of this MarketDataMarket.
:param highest_bid: The highest_bid of this MarketDataMarket. # noqa: E501
:type: int
"""
self._highest_bid = highest_bid
@property
def highest_bid_size(self):
"""Gets the highest_bid_size of this MarketDataMarket. # noqa: E501
:return: The highest_bid_size of this MarketDataMarket. # noqa: E501
:rtype: str
"""
return self._highest_bid_size
@highest_bid_size.setter
def highest_bid_size(self, highest_bid_size):
"""Sets the highest_bid_size of this MarketDataMarket.
:param highest_bid_size: The highest_bid_size of this MarketDataMarket. # noqa: E501
:type: str
"""
self._highest_bid_size = highest_bid_size
@property
def number_of_bids(self):
"""Gets the number_of_bids of this MarketDataMarket. # noqa: E501
:return: The number_of_bids of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._number_of_bids
@number_of_bids.setter
def number_of_bids(self, number_of_bids):
"""Sets the number_of_bids of this MarketDataMarket.
:param number_of_bids: The number_of_bids of this MarketDataMarket. # noqa: E501
:type: int
"""
self._number_of_bids = number_of_bids
@property
def annual_high(self):
"""Gets the annual_high of this MarketDataMarket. # noqa: E501
:return: The annual_high of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._annual_high
@annual_high.setter
def annual_high(self, annual_high):
"""Sets the annual_high of this MarketDataMarket.
:param annual_high: The annual_high of this MarketDataMarket. # noqa: E501
:type: int
"""
self._annual_high = annual_high
@property
def annual_low(self):
"""Gets the annual_low of this MarketDataMarket. # noqa: E501
:return: The annual_low of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._annual_low
@annual_low.setter
def annual_low(self, annual_low):
"""Sets the annual_low of this MarketDataMarket.
:param annual_low: The annual_low of this MarketDataMarket. # noqa: E501
:type: int
"""
self._annual_low = annual_low
@property
def deadstock_range_low(self):
"""Gets the deadstock_range_low of this MarketDataMarket. # noqa: E501
:return: The deadstock_range_low of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._deadstock_range_low
@deadstock_range_low.setter
def deadstock_range_low(self, deadstock_range_low):
"""Sets the deadstock_range_low of this MarketDataMarket.
:param deadstock_range_low: The deadstock_range_low of this MarketDataMarket. # noqa: E501
:type: int
"""
self._deadstock_range_low = deadstock_range_low
@property
def deadstock_range_high(self):
"""Gets the deadstock_range_high of this MarketDataMarket. # noqa: E501
:return: The deadstock_range_high of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._deadstock_range_high
@deadstock_range_high.setter
def deadstock_range_high(self, deadstock_range_high):
"""Sets the deadstock_range_high of this MarketDataMarket.
:param deadstock_range_high: The deadstock_range_high of this MarketDataMarket. # noqa: E501
:type: int
"""
self._deadstock_range_high = deadstock_range_high
@property
def volatility(self):
"""Gets the volatility of this MarketDataMarket. # noqa: E501
:return: The volatility of this MarketDataMarket. # noqa: E501
:rtype: float
"""
return self._volatility
@volatility.setter
def volatility(self, volatility):
"""Sets the volatility of this MarketDataMarket.
:param volatility: The volatility of this MarketDataMarket. # noqa: E501
:type: float
"""
self._volatility = volatility
@property
def deadstock_sold(self):
"""Gets the deadstock_sold of this MarketDataMarket. # noqa: E501
:return: The deadstock_sold of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._deadstock_sold
@deadstock_sold.setter
def deadstock_sold(self, deadstock_sold):
"""Sets the deadstock_sold of this MarketDataMarket.
:param deadstock_sold: The deadstock_sold of this MarketDataMarket. # noqa: E501
:type: int
"""
self._deadstock_sold = deadstock_sold
@property
def price_premium(self):
"""Gets the price_premium of this MarketDataMarket. # noqa: E501
:return: The price_premium of this MarketDataMarket. # noqa: E501
:rtype: float
"""
return self._price_premium
@price_premium.setter
def price_premium(self, price_premium):
"""Sets the price_premium of this MarketDataMarket.
:param price_premium: The price_premium of this MarketDataMarket. # noqa: E501
:type: float
"""
self._price_premium = price_premium
@property
def average_deadstock_price(self):
"""Gets the average_deadstock_price of this MarketDataMarket. # noqa: E501
:return: The average_deadstock_price of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._average_deadstock_price
@average_deadstock_price.setter
def average_deadstock_price(self, average_deadstock_price):
"""Sets the average_deadstock_price of this MarketDataMarket.
:param average_deadstock_price: The average_deadstock_price of this MarketDataMarket. # noqa: E501
:type: int
"""
self._average_deadstock_price = average_deadstock_price
@property
def last_sale(self):
"""Gets the last_sale of this MarketDataMarket. # noqa: E501
:return: The last_sale of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._last_sale
@last_sale.setter
def last_sale(self, last_sale):
"""Sets the last_sale of this MarketDataMarket.
:param last_sale: The last_sale of this MarketDataMarket. # noqa: E501
:type: int
"""
self._last_sale = last_sale
@property
def last_sale_size(self):
"""Gets the last_sale_size of this MarketDataMarket. # noqa: E501
:return: The last_sale_size of this MarketDataMarket. # noqa: E501
:rtype: str
"""
return self._last_sale_size
@last_sale_size.setter
def last_sale_size(self, last_sale_size):
"""Sets the last_sale_size of this MarketDataMarket.
:param last_sale_size: The last_sale_size of this MarketDataMarket. # noqa: E501
:type: str
"""
self._last_sale_size = last_sale_size
@property
def sales_last72_hours(self):
"""Gets the sales_last72_hours of this MarketDataMarket. # noqa: E501
:return: The sales_last72_hours of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._sales_last72_hours
@sales_last72_hours.setter
def sales_last72_hours(self, sales_last72_hours):
"""Sets the sales_last72_hours of this MarketDataMarket.
:param sales_last72_hours: The sales_last72_hours of this MarketDataMarket. # noqa: E501
:type: int
"""
self._sales_last72_hours = sales_last72_hours
@property
def change_value(self):
"""Gets the change_value of this MarketDataMarket. # noqa: E501
:return: The change_value of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._change_value
@change_value.setter
def change_value(self, change_value):
"""Sets the change_value of this MarketDataMarket.
:param change_value: The change_value of this MarketDataMarket. # noqa: E501
:type: int
"""
self._change_value = change_value
@property
def change_percentage(self):
"""Gets the change_percentage of this MarketDataMarket. # noqa: E501
:return: The change_percentage of this MarketDataMarket. # noqa: E501
:rtype: float
"""
return self._change_percentage
@change_percentage.setter
def change_percentage(self, change_percentage):
"""Sets the change_percentage of this MarketDataMarket.
:param change_percentage: The change_percentage of this MarketDataMarket. # noqa: E501
:type: float
"""
self._change_percentage = change_percentage
@property
def abs_change_percentage(self):
"""Gets the abs_change_percentage of this MarketDataMarket. # noqa: E501
:return: The abs_change_percentage of this MarketDataMarket. # noqa: E501
:rtype: float
"""
return self._abs_change_percentage
@abs_change_percentage.setter
def abs_change_percentage(self, abs_change_percentage):
"""Sets the abs_change_percentage of this MarketDataMarket.
:param abs_change_percentage: The abs_change_percentage of this MarketDataMarket. # noqa: E501
:type: float
"""
self._abs_change_percentage = abs_change_percentage
@property
def total_dollars(self):
"""Gets the total_dollars of this MarketDataMarket. # noqa: E501
:return: The total_dollars of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._total_dollars
@total_dollars.setter
def total_dollars(self, total_dollars):
"""Sets the total_dollars of this MarketDataMarket.
:param total_dollars: The total_dollars of this MarketDataMarket. # noqa: E501
:type: int
"""
self._total_dollars = total_dollars
@property
def updated_at(self):
"""Gets the updated_at of this MarketDataMarket. # noqa: E501
:return: The updated_at of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._updated_at
@updated_at.setter
def updated_at(self, updated_at):
"""Sets the updated_at of this MarketDataMarket.
:param updated_at: The updated_at of this MarketDataMarket. # noqa: E501
:type: int
"""
self._updated_at = updated_at
@property
def last_lowest_ask_time(self):
"""Gets the last_lowest_ask_time of this MarketDataMarket. # noqa: E501
:return: The last_lowest_ask_time of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._last_lowest_ask_time
@last_lowest_ask_time.setter
def last_lowest_ask_time(self, last_lowest_ask_time):
"""Sets the last_lowest_ask_time of this MarketDataMarket.
:param last_lowest_ask_time: The last_lowest_ask_time of this MarketDataMarket. # noqa: E501
:type: int
"""
self._last_lowest_ask_time = last_lowest_ask_time
@property
def last_highest_bid_time(self):
"""Gets the last_highest_bid_time of this MarketDataMarket. # noqa: E501
:return: The last_highest_bid_time of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._last_highest_bid_time
@last_highest_bid_time.setter
def last_highest_bid_time(self, last_highest_bid_time):
"""Sets the last_highest_bid_time of this MarketDataMarket.
:param last_highest_bid_time: The last_highest_bid_time of this MarketDataMarket. # noqa: E501
:type: int
"""
self._last_highest_bid_time = last_highest_bid_time
@property
def last_sale_date(self):
"""Gets the last_sale_date of this MarketDataMarket. # noqa: E501
:return: The last_sale_date of this MarketDataMarket. # noqa: E501
:rtype: str
"""
return self._last_sale_date
@last_sale_date.setter
def last_sale_date(self, last_sale_date):
"""Sets the last_sale_date of this MarketDataMarket.
:param last_sale_date: The last_sale_date of this MarketDataMarket. # noqa: E501
:type: str
"""
self._last_sale_date = last_sale_date
@property
def created_at(self):
"""Gets the created_at of this MarketDataMarket. # noqa: E501
:return: The created_at of this MarketDataMarket. # noqa: E501
:rtype: str
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
"""Sets the created_at of this MarketDataMarket.
:param created_at: The created_at of this MarketDataMarket. # noqa: E501
:type: str
"""
self._created_at = created_at
@property
def deadstock_sold_rank(self):
"""Gets the deadstock_sold_rank of this MarketDataMarket. # noqa: E501
:return: The deadstock_sold_rank of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._deadstock_sold_rank
@deadstock_sold_rank.setter
def deadstock_sold_rank(self, deadstock_sold_rank):
"""Sets the deadstock_sold_rank of this MarketDataMarket.
:param deadstock_sold_rank: The deadstock_sold_rank of this MarketDataMarket. # noqa: E501
:type: int
"""
self._deadstock_sold_rank = deadstock_sold_rank
@property
def price_premium_rank(self):
"""Gets the price_premium_rank of this MarketDataMarket. # noqa: E501
:return: The price_premium_rank of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._price_premium_rank
@price_premium_rank.setter
def price_premium_rank(self, price_premium_rank):
"""Sets the price_premium_rank of this MarketDataMarket.
:param price_premium_rank: The price_premium_rank of this MarketDataMarket. # noqa: E501
:type: int
"""
self._price_premium_rank = price_premium_rank
@property
def average_deadstock_price_rank(self):
"""Gets the average_deadstock_price_rank of this MarketDataMarket. # noqa: E501
:return: The average_deadstock_price_rank of this MarketDataMarket. # noqa: E501
:rtype: int
"""
return self._average_deadstock_price_rank
@average_deadstock_price_rank.setter
def average_deadstock_price_rank(self, average_deadstock_price_rank):
"""Sets the average_deadstock_price_rank of this MarketDataMarket.
:param average_deadstock_price_rank: The average_deadstock_price_rank of this MarketDataMarket. # noqa: E501
:type: int
"""
self._average_deadstock_price_rank = average_deadstock_price_rank
@property
def featured(self):
"""Gets the featured of this MarketDataMarket. # noqa: E501
:return: The featured of this MarketDataMarket. # noqa: E501
:rtype: str
"""
return self._featured
@featured.setter
def featured(self, featured):
"""Sets the featured of this MarketDataMarket.
:param featured: The featured of this MarketDataMarket. # noqa: E501
:type: str
"""
self._featured = featured
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, MarketDataMarket):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 1,022
| 29.807241
| 822
|
/sdk/python/lib/io_stockx/models/market_data_market.py
| 0.608099
| 0.595935
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from io_stockx.models.product_info_attributes_traits import ProductInfoAttributesTraits # noqa: F401,E501
class ProductInfoAttributes(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'product_uuid': 'str',
'sku': 'str',
'traits': 'ProductInfoAttributesTraits'
}
attribute_map = {
'product_uuid': 'product_uuid',
'sku': 'sku',
'traits': 'traits'
}
def __init__(self, product_uuid=None, sku=None, traits=None): # noqa: E501
"""ProductInfoAttributes - a model defined in Swagger""" # noqa: E501
self._product_uuid = None
self._sku = None
self._traits = None
self.discriminator = None
if product_uuid is not None:
self.product_uuid = product_uuid
if sku is not None:
self.sku = sku
if traits is not None:
self.traits = traits
@property
def product_uuid(self):
"""Gets the product_uuid of this ProductInfoAttributes. # noqa: E501
:return: The product_uuid of this ProductInfoAttributes. # noqa: E501
:rtype: str
"""
return self._product_uuid
@product_uuid.setter
def product_uuid(self, product_uuid):
"""Sets the product_uuid of this ProductInfoAttributes.
:param product_uuid: The product_uuid of this ProductInfoAttributes. # noqa: E501
:type: str
"""
self._product_uuid = product_uuid
@property
def sku(self):
"""Gets the sku of this ProductInfoAttributes. # noqa: E501
:return: The sku of this ProductInfoAttributes. # noqa: E501
:rtype: str
"""
return self._sku
@sku.setter
def sku(self, sku):
"""Sets the sku of this ProductInfoAttributes.
:param sku: The sku of this ProductInfoAttributes. # noqa: E501
:type: str
"""
self._sku = sku
@property
def traits(self):
"""Gets the traits of this ProductInfoAttributes. # noqa: E501
:return: The traits of this ProductInfoAttributes. # noqa: E501
:rtype: ProductInfoAttributesTraits
"""
return self._traits
@traits.setter
def traits(self, traits):
"""Sets the traits of this ProductInfoAttributes.
:param traits: The traits of this ProductInfoAttributes. # noqa: E501
:type: ProductInfoAttributesTraits
"""
self._traits = traits
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ProductInfoAttributes):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 166
| 26.728916
| 176
|
/sdk/python/lib/build/lib/io_stockx/models/product_info_attributes.py
| 0.571149
| 0.559852
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PortfolioRequestPortfolioItem(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'amount': 'str',
'expires_at': 'str',
'matched_with_date': 'str',
'condition': 'str',
'action': 'int',
'sku_uuid': 'str'
}
attribute_map = {
'amount': 'amount',
'expires_at': 'expiresAt',
'matched_with_date': 'matchedWithDate',
'condition': 'condition',
'action': 'action',
'sku_uuid': 'skuUuid'
}
def __init__(self, amount=None, expires_at=None, matched_with_date=None, condition=None, action=None, sku_uuid=None): # noqa: E501
"""PortfolioRequestPortfolioItem - a model defined in Swagger""" # noqa: E501
self._amount = None
self._expires_at = None
self._matched_with_date = None
self._condition = None
self._action = None
self._sku_uuid = None
self.discriminator = None
if amount is not None:
self.amount = amount
if expires_at is not None:
self.expires_at = expires_at
if matched_with_date is not None:
self.matched_with_date = matched_with_date
if condition is not None:
self.condition = condition
if action is not None:
self.action = action
if sku_uuid is not None:
self.sku_uuid = sku_uuid
@property
def amount(self):
"""Gets the amount of this PortfolioRequestPortfolioItem. # noqa: E501
:return: The amount of this PortfolioRequestPortfolioItem. # noqa: E501
:rtype: str
"""
return self._amount
@amount.setter
def amount(self, amount):
"""Sets the amount of this PortfolioRequestPortfolioItem.
:param amount: The amount of this PortfolioRequestPortfolioItem. # noqa: E501
:type: str
"""
self._amount = amount
@property
def expires_at(self):
"""Gets the expires_at of this PortfolioRequestPortfolioItem. # noqa: E501
:return: The expires_at of this PortfolioRequestPortfolioItem. # noqa: E501
:rtype: str
"""
return self._expires_at
@expires_at.setter
def expires_at(self, expires_at):
"""Sets the expires_at of this PortfolioRequestPortfolioItem.
:param expires_at: The expires_at of this PortfolioRequestPortfolioItem. # noqa: E501
:type: str
"""
self._expires_at = expires_at
@property
def matched_with_date(self):
"""Gets the matched_with_date of this PortfolioRequestPortfolioItem. # noqa: E501
:return: The matched_with_date of this PortfolioRequestPortfolioItem. # noqa: E501
:rtype: str
"""
return self._matched_with_date
@matched_with_date.setter
def matched_with_date(self, matched_with_date):
"""Sets the matched_with_date of this PortfolioRequestPortfolioItem.
:param matched_with_date: The matched_with_date of this PortfolioRequestPortfolioItem. # noqa: E501
:type: str
"""
self._matched_with_date = matched_with_date
@property
def condition(self):
"""Gets the condition of this PortfolioRequestPortfolioItem. # noqa: E501
:return: The condition of this PortfolioRequestPortfolioItem. # noqa: E501
:rtype: str
"""
return self._condition
@condition.setter
def condition(self, condition):
"""Sets the condition of this PortfolioRequestPortfolioItem.
:param condition: The condition of this PortfolioRequestPortfolioItem. # noqa: E501
:type: str
"""
self._condition = condition
@property
def action(self):
"""Gets the action of this PortfolioRequestPortfolioItem. # noqa: E501
:return: The action of this PortfolioRequestPortfolioItem. # noqa: E501
:rtype: int
"""
return self._action
@action.setter
def action(self, action):
"""Sets the action of this PortfolioRequestPortfolioItem.
:param action: The action of this PortfolioRequestPortfolioItem. # noqa: E501
:type: int
"""
self._action = action
@property
def sku_uuid(self):
"""Gets the sku_uuid of this PortfolioRequestPortfolioItem. # noqa: E501
:return: The sku_uuid of this PortfolioRequestPortfolioItem. # noqa: E501
:rtype: str
"""
return self._sku_uuid
@sku_uuid.setter
def sku_uuid(self, sku_uuid):
"""Sets the sku_uuid of this PortfolioRequestPortfolioItem.
:param sku_uuid: The sku_uuid of this PortfolioRequestPortfolioItem. # noqa: E501
:type: str
"""
self._sku_uuid = sku_uuid
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PortfolioRequestPortfolioItem):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 242
| 27.652893
| 176
|
/sdk/python/lib/io_stockx/models/portfolio_request_portfolio_item.py
| 0.587395
| 0.576868
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class AddressObject(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'first_name': 'str',
'last_name': 'str',
'telephone': 'str',
'street_address': 'str',
'extended_address': 'str',
'locality': 'str',
'region': 'str',
'postal_code': 'str',
'country_code_alpha2': 'str'
}
attribute_map = {
'first_name': 'firstName',
'last_name': 'lastName',
'telephone': 'telephone',
'street_address': 'streetAddress',
'extended_address': 'extendedAddress',
'locality': 'locality',
'region': 'region',
'postal_code': 'postalCode',
'country_code_alpha2': 'countryCodeAlpha2'
}
def __init__(self, first_name=None, last_name=None, telephone=None, street_address=None, extended_address=None, locality=None, region=None, postal_code=None, country_code_alpha2=None): # noqa: E501
"""AddressObject - a model defined in Swagger""" # noqa: E501
self._first_name = None
self._last_name = None
self._telephone = None
self._street_address = None
self._extended_address = None
self._locality = None
self._region = None
self._postal_code = None
self._country_code_alpha2 = None
self.discriminator = None
if first_name is not None:
self.first_name = first_name
if last_name is not None:
self.last_name = last_name
if telephone is not None:
self.telephone = telephone
if street_address is not None:
self.street_address = street_address
if extended_address is not None:
self.extended_address = extended_address
if locality is not None:
self.locality = locality
if region is not None:
self.region = region
if postal_code is not None:
self.postal_code = postal_code
if country_code_alpha2 is not None:
self.country_code_alpha2 = country_code_alpha2
@property
def first_name(self):
"""Gets the first_name of this AddressObject. # noqa: E501
:return: The first_name of this AddressObject. # noqa: E501
:rtype: str
"""
return self._first_name
@first_name.setter
def first_name(self, first_name):
"""Sets the first_name of this AddressObject.
:param first_name: The first_name of this AddressObject. # noqa: E501
:type: str
"""
self._first_name = first_name
@property
def last_name(self):
"""Gets the last_name of this AddressObject. # noqa: E501
:return: The last_name of this AddressObject. # noqa: E501
:rtype: str
"""
return self._last_name
@last_name.setter
def last_name(self, last_name):
"""Sets the last_name of this AddressObject.
:param last_name: The last_name of this AddressObject. # noqa: E501
:type: str
"""
self._last_name = last_name
@property
def telephone(self):
"""Gets the telephone of this AddressObject. # noqa: E501
:return: The telephone of this AddressObject. # noqa: E501
:rtype: str
"""
return self._telephone
@telephone.setter
def telephone(self, telephone):
"""Sets the telephone of this AddressObject.
:param telephone: The telephone of this AddressObject. # noqa: E501
:type: str
"""
self._telephone = telephone
@property
def street_address(self):
"""Gets the street_address of this AddressObject. # noqa: E501
:return: The street_address of this AddressObject. # noqa: E501
:rtype: str
"""
return self._street_address
@street_address.setter
def street_address(self, street_address):
"""Sets the street_address of this AddressObject.
:param street_address: The street_address of this AddressObject. # noqa: E501
:type: str
"""
self._street_address = street_address
@property
def extended_address(self):
"""Gets the extended_address of this AddressObject. # noqa: E501
:return: The extended_address of this AddressObject. # noqa: E501
:rtype: str
"""
return self._extended_address
@extended_address.setter
def extended_address(self, extended_address):
"""Sets the extended_address of this AddressObject.
:param extended_address: The extended_address of this AddressObject. # noqa: E501
:type: str
"""
self._extended_address = extended_address
@property
def locality(self):
"""Gets the locality of this AddressObject. # noqa: E501
:return: The locality of this AddressObject. # noqa: E501
:rtype: str
"""
return self._locality
@locality.setter
def locality(self, locality):
"""Sets the locality of this AddressObject.
:param locality: The locality of this AddressObject. # noqa: E501
:type: str
"""
self._locality = locality
@property
def region(self):
"""Gets the region of this AddressObject. # noqa: E501
:return: The region of this AddressObject. # noqa: E501
:rtype: str
"""
return self._region
@region.setter
def region(self, region):
"""Sets the region of this AddressObject.
:param region: The region of this AddressObject. # noqa: E501
:type: str
"""
self._region = region
@property
def postal_code(self):
"""Gets the postal_code of this AddressObject. # noqa: E501
:return: The postal_code of this AddressObject. # noqa: E501
:rtype: str
"""
return self._postal_code
@postal_code.setter
def postal_code(self, postal_code):
"""Sets the postal_code of this AddressObject.
:param postal_code: The postal_code of this AddressObject. # noqa: E501
:type: str
"""
self._postal_code = postal_code
@property
def country_code_alpha2(self):
"""Gets the country_code_alpha2 of this AddressObject. # noqa: E501
:return: The country_code_alpha2 of this AddressObject. # noqa: E501
:rtype: str
"""
return self._country_code_alpha2
@country_code_alpha2.setter
def country_code_alpha2(self, country_code_alpha2):
"""Sets the country_code_alpha2 of this AddressObject.
:param country_code_alpha2: The country_code_alpha2 of this AddressObject. # noqa: E501
:type: str
"""
self._country_code_alpha2 = country_code_alpha2
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, AddressObject):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 320
| 26.88125
| 202
|
/sdk/python/lib/io_stockx/models/address_object.py
| 0.577785
| 0.564335
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import io_stockx
from io_stockx.api.stock_x_api import StockXApi # noqa: E501
from io_stockx.rest import ApiException
class TestStockXApi(unittest.TestCase):
"""StockXApi unit test stubs"""
def setUp(self):
self.api = io_stockx.api.stock_x_api.StockXApi() # noqa: E501
def tearDown(self):
pass
def test_delete_portfolio(self):
"""Test case for delete_portfolio
Deletes a portfolio item from the market with the specified id. # noqa: E501
"""
pass
def test_delete_webhook(self):
"""Test case for delete_webhook
"""
pass
def test_get_open_orders(self):
"""Test case for get_open_orders
"""
pass
def test_get_portfolio(self):
"""Test case for get_portfolio
Returns a market portfolio identified by request parameters. # noqa: E501
"""
pass
def test_get_portfolio_item(self):
"""Test case for get_portfolio_item
"""
pass
def test_get_product_by_id(self):
"""Test case for get_product_by_id
"""
pass
def test_get_product_market_data(self):
"""Test case for get_product_market_data
Provides historical market data for a given product. # noqa: E501
"""
pass
def test_get_subscriptions(self):
"""Test case for get_subscriptions
"""
pass
def test_get_webhook(self):
"""Test case for get_webhook
"""
pass
def test_get_webhooks(self):
"""Test case for get_webhooks
"""
pass
def test_login(self):
"""Test case for login
Attempts to log the user in with a username and password. # noqa: E501
"""
pass
def test_lookup_product(self):
"""Test case for lookup_product
"""
pass
def test_new_portfolio_ask(self):
"""Test case for new_portfolio_ask
Creates a new seller ask on the market for a given product. # noqa: E501
"""
pass
def test_new_portfolio_bid(self):
"""Test case for new_portfolio_bid
Creates a new buyer bid on the market for a given product. # noqa: E501
"""
pass
def test_post_webhooks(self):
"""Test case for post_webhooks
"""
pass
def test_search(self):
"""Test case for search
Searches for products by keyword. # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
|
Python
| 137
| 20.489052
| 176
|
/sdk/python/lib/test/test_stock_x_api.py
| 0.584579
| 0.57303
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PortfolioIdDelResponsePortfolioItemMerchant(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'int',
'customer_id': 'int',
'is_robot': 'int',
'name': 'str',
'paypal_email': 'str',
'take': 'float',
'created_at': 'str',
'created_at_time': 'int',
'updated_at': 'str',
'updated_at_time': 'int'
}
attribute_map = {
'id': 'id',
'customer_id': 'customerId',
'is_robot': 'isRobot',
'name': 'name',
'paypal_email': 'paypalEmail',
'take': 'take',
'created_at': 'createdAt',
'created_at_time': 'createdAtTime',
'updated_at': 'updatedAt',
'updated_at_time': 'updatedAtTime'
}
def __init__(self, id=None, customer_id=None, is_robot=None, name=None, paypal_email=None, take=None, created_at=None, created_at_time=None, updated_at=None, updated_at_time=None): # noqa: E501
"""PortfolioIdDelResponsePortfolioItemMerchant - a model defined in Swagger""" # noqa: E501
self._id = None
self._customer_id = None
self._is_robot = None
self._name = None
self._paypal_email = None
self._take = None
self._created_at = None
self._created_at_time = None
self._updated_at = None
self._updated_at_time = None
self.discriminator = None
self.id = id
self.customer_id = customer_id
self.is_robot = is_robot
self.name = name
self.paypal_email = paypal_email
self.take = take
self.created_at = created_at
self.created_at_time = created_at_time
self.updated_at = updated_at
self.updated_at_time = updated_at_time
@property
def id(self):
"""Gets the id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: int
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this PortfolioIdDelResponsePortfolioItemMerchant.
:param id: The id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: int
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501
self._id = id
@property
def customer_id(self):
"""Gets the customer_id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The customer_id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: int
"""
return self._customer_id
@customer_id.setter
def customer_id(self, customer_id):
"""Sets the customer_id of this PortfolioIdDelResponsePortfolioItemMerchant.
:param customer_id: The customer_id of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: int
"""
if customer_id is None:
raise ValueError("Invalid value for `customer_id`, must not be `None`") # noqa: E501
self._customer_id = customer_id
@property
def is_robot(self):
"""Gets the is_robot of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The is_robot of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: int
"""
return self._is_robot
@is_robot.setter
def is_robot(self, is_robot):
"""Sets the is_robot of this PortfolioIdDelResponsePortfolioItemMerchant.
:param is_robot: The is_robot of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: int
"""
if is_robot is None:
raise ValueError("Invalid value for `is_robot`, must not be `None`") # noqa: E501
self._is_robot = is_robot
@property
def name(self):
"""Gets the name of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The name of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this PortfolioIdDelResponsePortfolioItemMerchant.
:param name: The name of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: str
"""
if name is None:
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = name
@property
def paypal_email(self):
"""Gets the paypal_email of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The paypal_email of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: str
"""
return self._paypal_email
@paypal_email.setter
def paypal_email(self, paypal_email):
"""Sets the paypal_email of this PortfolioIdDelResponsePortfolioItemMerchant.
:param paypal_email: The paypal_email of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: str
"""
if paypal_email is None:
raise ValueError("Invalid value for `paypal_email`, must not be `None`") # noqa: E501
self._paypal_email = paypal_email
@property
def take(self):
"""Gets the take of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The take of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: float
"""
return self._take
@take.setter
def take(self, take):
"""Sets the take of this PortfolioIdDelResponsePortfolioItemMerchant.
:param take: The take of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: float
"""
if take is None:
raise ValueError("Invalid value for `take`, must not be `None`") # noqa: E501
self._take = take
@property
def created_at(self):
"""Gets the created_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The created_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: str
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
"""Sets the created_at of this PortfolioIdDelResponsePortfolioItemMerchant.
:param created_at: The created_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: str
"""
if created_at is None:
raise ValueError("Invalid value for `created_at`, must not be `None`") # noqa: E501
self._created_at = created_at
@property
def created_at_time(self):
"""Gets the created_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The created_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: int
"""
return self._created_at_time
@created_at_time.setter
def created_at_time(self, created_at_time):
"""Sets the created_at_time of this PortfolioIdDelResponsePortfolioItemMerchant.
:param created_at_time: The created_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: int
"""
if created_at_time is None:
raise ValueError("Invalid value for `created_at_time`, must not be `None`") # noqa: E501
self._created_at_time = created_at_time
@property
def updated_at(self):
"""Gets the updated_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The updated_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: str
"""
return self._updated_at
@updated_at.setter
def updated_at(self, updated_at):
"""Sets the updated_at of this PortfolioIdDelResponsePortfolioItemMerchant.
:param updated_at: The updated_at of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: str
"""
if updated_at is None:
raise ValueError("Invalid value for `updated_at`, must not be `None`") # noqa: E501
self._updated_at = updated_at
@property
def updated_at_time(self):
"""Gets the updated_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:return: The updated_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:rtype: int
"""
return self._updated_at_time
@updated_at_time.setter
def updated_at_time(self, updated_at_time):
"""Sets the updated_at_time of this PortfolioIdDelResponsePortfolioItemMerchant.
:param updated_at_time: The updated_at_time of this PortfolioIdDelResponsePortfolioItemMerchant. # noqa: E501
:type: int
"""
if updated_at_time is None:
raise ValueError("Invalid value for `updated_at_time`, must not be `None`") # noqa: E501
self._updated_at_time = updated_at_time
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PortfolioIdDelResponsePortfolioItemMerchant):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 356
| 30.960674
| 198
|
/sdk/python/lib/io_stockx/models/portfolio_id_del_response_portfolio_item_merchant.py
| 0.612674
| 0.600457
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class SearchHitSearchableTraits(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'style': 'str',
'colorway': 'str',
'retail_price': 'int',
'release_date': 'str'
}
attribute_map = {
'style': 'Style',
'colorway': 'Colorway',
'retail_price': 'Retail Price',
'release_date': 'Release Date'
}
def __init__(self, style=None, colorway=None, retail_price=None, release_date=None): # noqa: E501
"""SearchHitSearchableTraits - a model defined in Swagger""" # noqa: E501
self._style = None
self._colorway = None
self._retail_price = None
self._release_date = None
self.discriminator = None
if style is not None:
self.style = style
if colorway is not None:
self.colorway = colorway
if retail_price is not None:
self.retail_price = retail_price
if release_date is not None:
self.release_date = release_date
@property
def style(self):
"""Gets the style of this SearchHitSearchableTraits. # noqa: E501
:return: The style of this SearchHitSearchableTraits. # noqa: E501
:rtype: str
"""
return self._style
@style.setter
def style(self, style):
"""Sets the style of this SearchHitSearchableTraits.
:param style: The style of this SearchHitSearchableTraits. # noqa: E501
:type: str
"""
self._style = style
@property
def colorway(self):
"""Gets the colorway of this SearchHitSearchableTraits. # noqa: E501
:return: The colorway of this SearchHitSearchableTraits. # noqa: E501
:rtype: str
"""
return self._colorway
@colorway.setter
def colorway(self, colorway):
"""Sets the colorway of this SearchHitSearchableTraits.
:param colorway: The colorway of this SearchHitSearchableTraits. # noqa: E501
:type: str
"""
self._colorway = colorway
@property
def retail_price(self):
"""Gets the retail_price of this SearchHitSearchableTraits. # noqa: E501
:return: The retail_price of this SearchHitSearchableTraits. # noqa: E501
:rtype: int
"""
return self._retail_price
@retail_price.setter
def retail_price(self, retail_price):
"""Sets the retail_price of this SearchHitSearchableTraits.
:param retail_price: The retail_price of this SearchHitSearchableTraits. # noqa: E501
:type: int
"""
self._retail_price = retail_price
@property
def release_date(self):
"""Gets the release_date of this SearchHitSearchableTraits. # noqa: E501
:return: The release_date of this SearchHitSearchableTraits. # noqa: E501
:rtype: str
"""
return self._release_date
@release_date.setter
def release_date(self, release_date):
"""Sets the release_date of this SearchHitSearchableTraits.
:param release_date: The release_date of this SearchHitSearchableTraits. # noqa: E501
:type: str
"""
self._release_date = release_date
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, SearchHitSearchableTraits):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 190
| 27.168421
| 176
|
/sdk/python/lib/build/lib/io_stockx/models/search_hit_searchable_traits.py
| 0.577915
| 0.567638
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class CustomerObjectMerchant(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'merchant_id': 'str',
'paypal_email': 'str',
'preferred_payout': 'str',
'account_name': 'str'
}
attribute_map = {
'merchant_id': 'merchantId',
'paypal_email': 'paypalEmail',
'preferred_payout': 'preferredPayout',
'account_name': 'accountName'
}
def __init__(self, merchant_id=None, paypal_email=None, preferred_payout=None, account_name=None): # noqa: E501
"""CustomerObjectMerchant - a model defined in Swagger""" # noqa: E501
self._merchant_id = None
self._paypal_email = None
self._preferred_payout = None
self._account_name = None
self.discriminator = None
if merchant_id is not None:
self.merchant_id = merchant_id
if paypal_email is not None:
self.paypal_email = paypal_email
if preferred_payout is not None:
self.preferred_payout = preferred_payout
if account_name is not None:
self.account_name = account_name
@property
def merchant_id(self):
"""Gets the merchant_id of this CustomerObjectMerchant. # noqa: E501
:return: The merchant_id of this CustomerObjectMerchant. # noqa: E501
:rtype: str
"""
return self._merchant_id
@merchant_id.setter
def merchant_id(self, merchant_id):
"""Sets the merchant_id of this CustomerObjectMerchant.
:param merchant_id: The merchant_id of this CustomerObjectMerchant. # noqa: E501
:type: str
"""
self._merchant_id = merchant_id
@property
def paypal_email(self):
"""Gets the paypal_email of this CustomerObjectMerchant. # noqa: E501
:return: The paypal_email of this CustomerObjectMerchant. # noqa: E501
:rtype: str
"""
return self._paypal_email
@paypal_email.setter
def paypal_email(self, paypal_email):
"""Sets the paypal_email of this CustomerObjectMerchant.
:param paypal_email: The paypal_email of this CustomerObjectMerchant. # noqa: E501
:type: str
"""
self._paypal_email = paypal_email
@property
def preferred_payout(self):
"""Gets the preferred_payout of this CustomerObjectMerchant. # noqa: E501
:return: The preferred_payout of this CustomerObjectMerchant. # noqa: E501
:rtype: str
"""
return self._preferred_payout
@preferred_payout.setter
def preferred_payout(self, preferred_payout):
"""Sets the preferred_payout of this CustomerObjectMerchant.
:param preferred_payout: The preferred_payout of this CustomerObjectMerchant. # noqa: E501
:type: str
"""
self._preferred_payout = preferred_payout
@property
def account_name(self):
"""Gets the account_name of this CustomerObjectMerchant. # noqa: E501
:return: The account_name of this CustomerObjectMerchant. # noqa: E501
:rtype: str
"""
return self._account_name
@account_name.setter
def account_name(self, account_name):
"""Sets the account_name of this CustomerObjectMerchant.
:param account_name: The account_name of this CustomerObjectMerchant. # noqa: E501
:type: str
"""
self._account_name = account_name
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CustomerObjectMerchant):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 190
| 28.321053
| 176
|
/sdk/python/lib/io_stockx/models/customer_object_merchant.py
| 0.588045
| 0.578173
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from io_stockx.models.address_object import AddressObject # noqa: F401,E501
class BillingObject(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'card_type': 'str',
'token': 'str',
'last4': 'str',
'account_email': 'str',
'expiration_date': 'str',
'cardholder_name': 'str',
'address': 'AddressObject'
}
attribute_map = {
'card_type': 'cardType',
'token': 'token',
'last4': 'last4',
'account_email': 'accountEmail',
'expiration_date': 'expirationDate',
'cardholder_name': 'cardholderName',
'address': 'Address'
}
def __init__(self, card_type=None, token=None, last4=None, account_email=None, expiration_date=None, cardholder_name=None, address=None): # noqa: E501
"""BillingObject - a model defined in Swagger""" # noqa: E501
self._card_type = None
self._token = None
self._last4 = None
self._account_email = None
self._expiration_date = None
self._cardholder_name = None
self._address = None
self.discriminator = None
if card_type is not None:
self.card_type = card_type
if token is not None:
self.token = token
if last4 is not None:
self.last4 = last4
if account_email is not None:
self.account_email = account_email
if expiration_date is not None:
self.expiration_date = expiration_date
if cardholder_name is not None:
self.cardholder_name = cardholder_name
if address is not None:
self.address = address
@property
def card_type(self):
"""Gets the card_type of this BillingObject. # noqa: E501
:return: The card_type of this BillingObject. # noqa: E501
:rtype: str
"""
return self._card_type
@card_type.setter
def card_type(self, card_type):
"""Sets the card_type of this BillingObject.
:param card_type: The card_type of this BillingObject. # noqa: E501
:type: str
"""
self._card_type = card_type
@property
def token(self):
"""Gets the token of this BillingObject. # noqa: E501
:return: The token of this BillingObject. # noqa: E501
:rtype: str
"""
return self._token
@token.setter
def token(self, token):
"""Sets the token of this BillingObject.
:param token: The token of this BillingObject. # noqa: E501
:type: str
"""
self._token = token
@property
def last4(self):
"""Gets the last4 of this BillingObject. # noqa: E501
:return: The last4 of this BillingObject. # noqa: E501
:rtype: str
"""
return self._last4
@last4.setter
def last4(self, last4):
"""Sets the last4 of this BillingObject.
:param last4: The last4 of this BillingObject. # noqa: E501
:type: str
"""
self._last4 = last4
@property
def account_email(self):
"""Gets the account_email of this BillingObject. # noqa: E501
:return: The account_email of this BillingObject. # noqa: E501
:rtype: str
"""
return self._account_email
@account_email.setter
def account_email(self, account_email):
"""Sets the account_email of this BillingObject.
:param account_email: The account_email of this BillingObject. # noqa: E501
:type: str
"""
self._account_email = account_email
@property
def expiration_date(self):
"""Gets the expiration_date of this BillingObject. # noqa: E501
:return: The expiration_date of this BillingObject. # noqa: E501
:rtype: str
"""
return self._expiration_date
@expiration_date.setter
def expiration_date(self, expiration_date):
"""Sets the expiration_date of this BillingObject.
:param expiration_date: The expiration_date of this BillingObject. # noqa: E501
:type: str
"""
self._expiration_date = expiration_date
@property
def cardholder_name(self):
"""Gets the cardholder_name of this BillingObject. # noqa: E501
:return: The cardholder_name of this BillingObject. # noqa: E501
:rtype: str
"""
return self._cardholder_name
@cardholder_name.setter
def cardholder_name(self, cardholder_name):
"""Sets the cardholder_name of this BillingObject.
:param cardholder_name: The cardholder_name of this BillingObject. # noqa: E501
:type: str
"""
self._cardholder_name = cardholder_name
@property
def address(self):
"""Gets the address of this BillingObject. # noqa: E501
:return: The address of this BillingObject. # noqa: E501
:rtype: AddressObject
"""
return self._address
@address.setter
def address(self, address):
"""Sets the address of this BillingObject.
:param address: The address of this BillingObject. # noqa: E501
:type: AddressObject
"""
self._address = address
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, BillingObject):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 270
| 26.299999
| 176
|
/sdk/python/lib/build/lib/io_stockx/models/billing_object.py
| 0.571293
| 0.556641
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PortfolioIdDelRequest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'chain_id': 'str',
'notes': 'str'
}
attribute_map = {
'chain_id': 'chain_id',
'notes': 'notes'
}
def __init__(self, chain_id=None, notes=None): # noqa: E501
"""PortfolioIdDelRequest - a model defined in Swagger""" # noqa: E501
self._chain_id = None
self._notes = None
self.discriminator = None
self.chain_id = chain_id
self.notes = notes
@property
def chain_id(self):
"""Gets the chain_id of this PortfolioIdDelRequest. # noqa: E501
:return: The chain_id of this PortfolioIdDelRequest. # noqa: E501
:rtype: str
"""
return self._chain_id
@chain_id.setter
def chain_id(self, chain_id):
"""Sets the chain_id of this PortfolioIdDelRequest.
:param chain_id: The chain_id of this PortfolioIdDelRequest. # noqa: E501
:type: str
"""
if chain_id is None:
raise ValueError("Invalid value for `chain_id`, must not be `None`") # noqa: E501
self._chain_id = chain_id
@property
def notes(self):
"""Gets the notes of this PortfolioIdDelRequest. # noqa: E501
:return: The notes of this PortfolioIdDelRequest. # noqa: E501
:rtype: str
"""
return self._notes
@notes.setter
def notes(self, notes):
"""Sets the notes of this PortfolioIdDelRequest.
:param notes: The notes of this PortfolioIdDelRequest. # noqa: E501
:type: str
"""
if notes is None:
raise ValueError("Invalid value for `notes`, must not be `None`") # noqa: E501
self._notes = notes
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PortfolioIdDelRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 140
| 26.864286
| 176
|
/sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_request.py
| 0.554986
| 0.543963
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PortfolioIdDelResponsePortfolioItemProductShipping(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'total_days_to_ship': 'int',
'has_additional_days_to_ship': 'bool',
'delivery_days_lower_bound': 'int',
'delivery_days_upper_bound': 'int'
}
attribute_map = {
'total_days_to_ship': 'totalDaysToShip',
'has_additional_days_to_ship': 'hasAdditionalDaysToShip',
'delivery_days_lower_bound': 'deliveryDaysLowerBound',
'delivery_days_upper_bound': 'deliveryDaysUpperBound'
}
def __init__(self, total_days_to_ship=None, has_additional_days_to_ship=None, delivery_days_lower_bound=None, delivery_days_upper_bound=None): # noqa: E501
"""PortfolioIdDelResponsePortfolioItemProductShipping - a model defined in Swagger""" # noqa: E501
self._total_days_to_ship = None
self._has_additional_days_to_ship = None
self._delivery_days_lower_bound = None
self._delivery_days_upper_bound = None
self.discriminator = None
self.total_days_to_ship = total_days_to_ship
self.has_additional_days_to_ship = has_additional_days_to_ship
self.delivery_days_lower_bound = delivery_days_lower_bound
self.delivery_days_upper_bound = delivery_days_upper_bound
@property
def total_days_to_ship(self):
"""Gets the total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:return: The total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:rtype: int
"""
return self._total_days_to_ship
@total_days_to_ship.setter
def total_days_to_ship(self, total_days_to_ship):
"""Sets the total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping.
:param total_days_to_ship: The total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:type: int
"""
if total_days_to_ship is None:
raise ValueError("Invalid value for `total_days_to_ship`, must not be `None`") # noqa: E501
self._total_days_to_ship = total_days_to_ship
@property
def has_additional_days_to_ship(self):
"""Gets the has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:return: The has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:rtype: bool
"""
return self._has_additional_days_to_ship
@has_additional_days_to_ship.setter
def has_additional_days_to_ship(self, has_additional_days_to_ship):
"""Sets the has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping.
:param has_additional_days_to_ship: The has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:type: bool
"""
if has_additional_days_to_ship is None:
raise ValueError("Invalid value for `has_additional_days_to_ship`, must not be `None`") # noqa: E501
self._has_additional_days_to_ship = has_additional_days_to_ship
@property
def delivery_days_lower_bound(self):
"""Gets the delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:return: The delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:rtype: int
"""
return self._delivery_days_lower_bound
@delivery_days_lower_bound.setter
def delivery_days_lower_bound(self, delivery_days_lower_bound):
"""Sets the delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping.
:param delivery_days_lower_bound: The delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:type: int
"""
if delivery_days_lower_bound is None:
raise ValueError("Invalid value for `delivery_days_lower_bound`, must not be `None`") # noqa: E501
self._delivery_days_lower_bound = delivery_days_lower_bound
@property
def delivery_days_upper_bound(self):
"""Gets the delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:return: The delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:rtype: int
"""
return self._delivery_days_upper_bound
@delivery_days_upper_bound.setter
def delivery_days_upper_bound(self, delivery_days_upper_bound):
"""Sets the delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping.
:param delivery_days_upper_bound: The delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501
:type: int
"""
if delivery_days_upper_bound is None:
raise ValueError("Invalid value for `delivery_days_upper_bound`, must not be `None`") # noqa: E501
self._delivery_days_upper_bound = delivery_days_upper_bound
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PortfolioIdDelResponsePortfolioItemProductShipping):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 194
| 37.082474
| 176
|
/sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_response_portfolio_item_product_shipping.py
| 0.647672
| 0.638603
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from io_stockx.models.portfolio_id_del_response_portfolio_item_product_media import PortfolioIdDelResponsePortfolioItemProductMedia # noqa: F401,E501
from io_stockx.models.portfolio_id_del_response_portfolio_item_product_meta import PortfolioIdDelResponsePortfolioItemProductMeta # noqa: F401,E501
from io_stockx.models.portfolio_id_del_response_portfolio_item_product_shipping import PortfolioIdDelResponsePortfolioItemProductShipping # noqa: F401,E501
from io_stockx.models.portfolioitems_id_get_response_portfolio_item_product_market import PortfolioitemsIdGetResponsePortfolioItemProductMarket # noqa: F401,E501
class PortfolioitemsIdGetResponsePortfolioItemProduct(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'str',
'uuid': 'str',
'brand': 'str',
'category': 'str',
'charity_condition': 'int',
'colorway': 'str',
'condition': 'str',
'country_of_manufacture': 'str',
'gender': 'str',
'content_group': 'str',
'minimum_bid': 'int',
'media': 'PortfolioIdDelResponsePortfolioItemProductMedia',
'name': 'str',
'primary_category': 'str',
'secondary_category': 'str',
'product_category': 'str',
'release_date': 'str',
'retail_price': 'int',
'shoe': 'str',
'short_description': 'str',
'style_id': 'str',
'ticker_symbol': 'str',
'title': 'str',
'data_type': 'str',
'type': 'int',
'size_title': 'str',
'size_descriptor': 'str',
'size_all_descriptor': 'str',
'url_key': 'str',
'year': 'str',
'shipping_group': 'str',
'a_lim': 'int',
'meta': 'PortfolioIdDelResponsePortfolioItemProductMeta',
'shipping': 'PortfolioIdDelResponsePortfolioItemProductShipping',
'children': 'object',
'parent_id': 'str',
'parent_uuid': 'str',
'size_sort_order': 'int',
'shoe_size': 'str',
'market': 'PortfolioitemsIdGetResponsePortfolioItemProductMarket',
'upc': 'str'
}
attribute_map = {
'id': 'id',
'uuid': 'uuid',
'brand': 'brand',
'category': 'category',
'charity_condition': 'charityCondition',
'colorway': 'colorway',
'condition': 'condition',
'country_of_manufacture': 'countryOfManufacture',
'gender': 'gender',
'content_group': 'contentGroup',
'minimum_bid': 'minimumBid',
'media': 'media',
'name': 'name',
'primary_category': 'primaryCategory',
'secondary_category': 'secondaryCategory',
'product_category': 'productCategory',
'release_date': 'releaseDate',
'retail_price': 'retailPrice',
'shoe': 'shoe',
'short_description': 'shortDescription',
'style_id': 'styleId',
'ticker_symbol': 'tickerSymbol',
'title': 'title',
'data_type': 'dataType',
'type': 'type',
'size_title': 'sizeTitle',
'size_descriptor': 'sizeDescriptor',
'size_all_descriptor': 'sizeAllDescriptor',
'url_key': 'urlKey',
'year': 'year',
'shipping_group': 'shippingGroup',
'a_lim': 'aLim',
'meta': 'meta',
'shipping': 'shipping',
'children': 'children',
'parent_id': 'parentId',
'parent_uuid': 'parentUuid',
'size_sort_order': 'sizeSortOrder',
'shoe_size': 'shoeSize',
'market': 'market',
'upc': 'upc'
}
def __init__(self, id=None, uuid=None, brand=None, category=None, charity_condition=None, colorway=None, condition=None, country_of_manufacture=None, gender=None, content_group=None, minimum_bid=None, media=None, name=None, primary_category=None, secondary_category=None, product_category=None, release_date=None, retail_price=None, shoe=None, short_description=None, style_id=None, ticker_symbol=None, title=None, data_type=None, type=None, size_title=None, size_descriptor=None, size_all_descriptor=None, url_key=None, year=None, shipping_group=None, a_lim=None, meta=None, shipping=None, children=None, parent_id=None, parent_uuid=None, size_sort_order=None, shoe_size=None, market=None, upc=None): # noqa: E501
"""PortfolioitemsIdGetResponsePortfolioItemProduct - a model defined in Swagger""" # noqa: E501
self._id = None
self._uuid = None
self._brand = None
self._category = None
self._charity_condition = None
self._colorway = None
self._condition = None
self._country_of_manufacture = None
self._gender = None
self._content_group = None
self._minimum_bid = None
self._media = None
self._name = None
self._primary_category = None
self._secondary_category = None
self._product_category = None
self._release_date = None
self._retail_price = None
self._shoe = None
self._short_description = None
self._style_id = None
self._ticker_symbol = None
self._title = None
self._data_type = None
self._type = None
self._size_title = None
self._size_descriptor = None
self._size_all_descriptor = None
self._url_key = None
self._year = None
self._shipping_group = None
self._a_lim = None
self._meta = None
self._shipping = None
self._children = None
self._parent_id = None
self._parent_uuid = None
self._size_sort_order = None
self._shoe_size = None
self._market = None
self._upc = None
self.discriminator = None
self.id = id
self.uuid = uuid
self.brand = brand
self.category = category
self.charity_condition = charity_condition
self.colorway = colorway
self.condition = condition
self.country_of_manufacture = country_of_manufacture
self.gender = gender
self.content_group = content_group
self.minimum_bid = minimum_bid
self.media = media
self.name = name
self.primary_category = primary_category
self.secondary_category = secondary_category
self.product_category = product_category
self.release_date = release_date
self.retail_price = retail_price
self.shoe = shoe
self.short_description = short_description
self.style_id = style_id
self.ticker_symbol = ticker_symbol
self.title = title
self.data_type = data_type
self.type = type
self.size_title = size_title
self.size_descriptor = size_descriptor
self.size_all_descriptor = size_all_descriptor
self.url_key = url_key
self.year = year
self.shipping_group = shipping_group
self.a_lim = a_lim
self.meta = meta
self.shipping = shipping
self.children = children
self.parent_id = parent_id
self.parent_uuid = parent_uuid
self.size_sort_order = size_sort_order
self.shoe_size = shoe_size
self.market = market
self.upc = upc
@property
def id(self):
"""Gets the id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param id: The id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501
self._id = id
@property
def uuid(self):
"""Gets the uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._uuid
@uuid.setter
def uuid(self, uuid):
"""Sets the uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param uuid: The uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if uuid is None:
raise ValueError("Invalid value for `uuid`, must not be `None`") # noqa: E501
self._uuid = uuid
@property
def brand(self):
"""Gets the brand of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The brand of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._brand
@brand.setter
def brand(self, brand):
"""Sets the brand of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param brand: The brand of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if brand is None:
raise ValueError("Invalid value for `brand`, must not be `None`") # noqa: E501
self._brand = brand
@property
def category(self):
"""Gets the category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._category
@category.setter
def category(self, category):
"""Sets the category of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param category: The category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if category is None:
raise ValueError("Invalid value for `category`, must not be `None`") # noqa: E501
self._category = category
@property
def charity_condition(self):
"""Gets the charity_condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The charity_condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: int
"""
return self._charity_condition
@charity_condition.setter
def charity_condition(self, charity_condition):
"""Sets the charity_condition of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param charity_condition: The charity_condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: int
"""
if charity_condition is None:
raise ValueError("Invalid value for `charity_condition`, must not be `None`") # noqa: E501
self._charity_condition = charity_condition
@property
def colorway(self):
"""Gets the colorway of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The colorway of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._colorway
@colorway.setter
def colorway(self, colorway):
"""Sets the colorway of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param colorway: The colorway of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if colorway is None:
raise ValueError("Invalid value for `colorway`, must not be `None`") # noqa: E501
self._colorway = colorway
@property
def condition(self):
"""Gets the condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._condition
@condition.setter
def condition(self, condition):
"""Sets the condition of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param condition: The condition of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if condition is None:
raise ValueError("Invalid value for `condition`, must not be `None`") # noqa: E501
self._condition = condition
@property
def country_of_manufacture(self):
"""Gets the country_of_manufacture of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The country_of_manufacture of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._country_of_manufacture
@country_of_manufacture.setter
def country_of_manufacture(self, country_of_manufacture):
"""Sets the country_of_manufacture of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param country_of_manufacture: The country_of_manufacture of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if country_of_manufacture is None:
raise ValueError("Invalid value for `country_of_manufacture`, must not be `None`") # noqa: E501
self._country_of_manufacture = country_of_manufacture
@property
def gender(self):
"""Gets the gender of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The gender of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._gender
@gender.setter
def gender(self, gender):
"""Sets the gender of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param gender: The gender of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if gender is None:
raise ValueError("Invalid value for `gender`, must not be `None`") # noqa: E501
self._gender = gender
@property
def content_group(self):
"""Gets the content_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The content_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._content_group
@content_group.setter
def content_group(self, content_group):
"""Sets the content_group of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param content_group: The content_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if content_group is None:
raise ValueError("Invalid value for `content_group`, must not be `None`") # noqa: E501
self._content_group = content_group
@property
def minimum_bid(self):
"""Gets the minimum_bid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The minimum_bid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: int
"""
return self._minimum_bid
@minimum_bid.setter
def minimum_bid(self, minimum_bid):
"""Sets the minimum_bid of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param minimum_bid: The minimum_bid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: int
"""
if minimum_bid is None:
raise ValueError("Invalid value for `minimum_bid`, must not be `None`") # noqa: E501
self._minimum_bid = minimum_bid
@property
def media(self):
"""Gets the media of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The media of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: PortfolioIdDelResponsePortfolioItemProductMedia
"""
return self._media
@media.setter
def media(self, media):
"""Sets the media of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param media: The media of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: PortfolioIdDelResponsePortfolioItemProductMedia
"""
if media is None:
raise ValueError("Invalid value for `media`, must not be `None`") # noqa: E501
self._media = media
@property
def name(self):
"""Gets the name of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The name of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param name: The name of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if name is None:
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = name
@property
def primary_category(self):
"""Gets the primary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The primary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._primary_category
@primary_category.setter
def primary_category(self, primary_category):
"""Sets the primary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param primary_category: The primary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if primary_category is None:
raise ValueError("Invalid value for `primary_category`, must not be `None`") # noqa: E501
self._primary_category = primary_category
@property
def secondary_category(self):
"""Gets the secondary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The secondary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._secondary_category
@secondary_category.setter
def secondary_category(self, secondary_category):
"""Sets the secondary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param secondary_category: The secondary_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if secondary_category is None:
raise ValueError("Invalid value for `secondary_category`, must not be `None`") # noqa: E501
self._secondary_category = secondary_category
@property
def product_category(self):
"""Gets the product_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The product_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._product_category
@product_category.setter
def product_category(self, product_category):
"""Sets the product_category of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param product_category: The product_category of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if product_category is None:
raise ValueError("Invalid value for `product_category`, must not be `None`") # noqa: E501
self._product_category = product_category
@property
def release_date(self):
"""Gets the release_date of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The release_date of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._release_date
@release_date.setter
def release_date(self, release_date):
"""Sets the release_date of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param release_date: The release_date of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if release_date is None:
raise ValueError("Invalid value for `release_date`, must not be `None`") # noqa: E501
self._release_date = release_date
@property
def retail_price(self):
"""Gets the retail_price of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The retail_price of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: int
"""
return self._retail_price
@retail_price.setter
def retail_price(self, retail_price):
"""Sets the retail_price of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param retail_price: The retail_price of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: int
"""
if retail_price is None:
raise ValueError("Invalid value for `retail_price`, must not be `None`") # noqa: E501
self._retail_price = retail_price
@property
def shoe(self):
"""Gets the shoe of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The shoe of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._shoe
@shoe.setter
def shoe(self, shoe):
"""Sets the shoe of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param shoe: The shoe of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if shoe is None:
raise ValueError("Invalid value for `shoe`, must not be `None`") # noqa: E501
self._shoe = shoe
@property
def short_description(self):
"""Gets the short_description of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The short_description of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._short_description
@short_description.setter
def short_description(self, short_description):
"""Sets the short_description of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param short_description: The short_description of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if short_description is None:
raise ValueError("Invalid value for `short_description`, must not be `None`") # noqa: E501
self._short_description = short_description
@property
def style_id(self):
"""Gets the style_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The style_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._style_id
@style_id.setter
def style_id(self, style_id):
"""Sets the style_id of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param style_id: The style_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if style_id is None:
raise ValueError("Invalid value for `style_id`, must not be `None`") # noqa: E501
self._style_id = style_id
@property
def ticker_symbol(self):
"""Gets the ticker_symbol of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The ticker_symbol of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._ticker_symbol
@ticker_symbol.setter
def ticker_symbol(self, ticker_symbol):
"""Sets the ticker_symbol of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param ticker_symbol: The ticker_symbol of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if ticker_symbol is None:
raise ValueError("Invalid value for `ticker_symbol`, must not be `None`") # noqa: E501
self._ticker_symbol = ticker_symbol
@property
def title(self):
"""Gets the title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._title
@title.setter
def title(self, title):
"""Sets the title of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param title: The title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if title is None:
raise ValueError("Invalid value for `title`, must not be `None`") # noqa: E501
self._title = title
@property
def data_type(self):
"""Gets the data_type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The data_type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._data_type
@data_type.setter
def data_type(self, data_type):
"""Sets the data_type of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param data_type: The data_type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if data_type is None:
raise ValueError("Invalid value for `data_type`, must not be `None`") # noqa: E501
self._data_type = data_type
@property
def type(self):
"""Gets the type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: int
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param type: The type of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: int
"""
if type is None:
raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501
self._type = type
@property
def size_title(self):
"""Gets the size_title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The size_title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._size_title
@size_title.setter
def size_title(self, size_title):
"""Sets the size_title of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param size_title: The size_title of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if size_title is None:
raise ValueError("Invalid value for `size_title`, must not be `None`") # noqa: E501
self._size_title = size_title
@property
def size_descriptor(self):
"""Gets the size_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The size_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._size_descriptor
@size_descriptor.setter
def size_descriptor(self, size_descriptor):
"""Sets the size_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param size_descriptor: The size_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if size_descriptor is None:
raise ValueError("Invalid value for `size_descriptor`, must not be `None`") # noqa: E501
self._size_descriptor = size_descriptor
@property
def size_all_descriptor(self):
"""Gets the size_all_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The size_all_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._size_all_descriptor
@size_all_descriptor.setter
def size_all_descriptor(self, size_all_descriptor):
"""Sets the size_all_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param size_all_descriptor: The size_all_descriptor of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if size_all_descriptor is None:
raise ValueError("Invalid value for `size_all_descriptor`, must not be `None`") # noqa: E501
self._size_all_descriptor = size_all_descriptor
@property
def url_key(self):
"""Gets the url_key of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The url_key of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._url_key
@url_key.setter
def url_key(self, url_key):
"""Sets the url_key of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param url_key: The url_key of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if url_key is None:
raise ValueError("Invalid value for `url_key`, must not be `None`") # noqa: E501
self._url_key = url_key
@property
def year(self):
"""Gets the year of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The year of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._year
@year.setter
def year(self, year):
"""Sets the year of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param year: The year of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if year is None:
raise ValueError("Invalid value for `year`, must not be `None`") # noqa: E501
self._year = year
@property
def shipping_group(self):
"""Gets the shipping_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The shipping_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._shipping_group
@shipping_group.setter
def shipping_group(self, shipping_group):
"""Sets the shipping_group of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param shipping_group: The shipping_group of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if shipping_group is None:
raise ValueError("Invalid value for `shipping_group`, must not be `None`") # noqa: E501
self._shipping_group = shipping_group
@property
def a_lim(self):
"""Gets the a_lim of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The a_lim of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: int
"""
return self._a_lim
@a_lim.setter
def a_lim(self, a_lim):
"""Sets the a_lim of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param a_lim: The a_lim of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: int
"""
if a_lim is None:
raise ValueError("Invalid value for `a_lim`, must not be `None`") # noqa: E501
self._a_lim = a_lim
@property
def meta(self):
"""Gets the meta of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The meta of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: PortfolioIdDelResponsePortfolioItemProductMeta
"""
return self._meta
@meta.setter
def meta(self, meta):
"""Sets the meta of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param meta: The meta of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: PortfolioIdDelResponsePortfolioItemProductMeta
"""
if meta is None:
raise ValueError("Invalid value for `meta`, must not be `None`") # noqa: E501
self._meta = meta
@property
def shipping(self):
"""Gets the shipping of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The shipping of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: PortfolioIdDelResponsePortfolioItemProductShipping
"""
return self._shipping
@shipping.setter
def shipping(self, shipping):
"""Sets the shipping of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param shipping: The shipping of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: PortfolioIdDelResponsePortfolioItemProductShipping
"""
if shipping is None:
raise ValueError("Invalid value for `shipping`, must not be `None`") # noqa: E501
self._shipping = shipping
@property
def children(self):
"""Gets the children of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The children of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: object
"""
return self._children
@children.setter
def children(self, children):
"""Sets the children of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param children: The children of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: object
"""
if children is None:
raise ValueError("Invalid value for `children`, must not be `None`") # noqa: E501
self._children = children
@property
def parent_id(self):
"""Gets the parent_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The parent_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._parent_id
@parent_id.setter
def parent_id(self, parent_id):
"""Sets the parent_id of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param parent_id: The parent_id of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if parent_id is None:
raise ValueError("Invalid value for `parent_id`, must not be `None`") # noqa: E501
self._parent_id = parent_id
@property
def parent_uuid(self):
"""Gets the parent_uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The parent_uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._parent_uuid
@parent_uuid.setter
def parent_uuid(self, parent_uuid):
"""Sets the parent_uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param parent_uuid: The parent_uuid of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if parent_uuid is None:
raise ValueError("Invalid value for `parent_uuid`, must not be `None`") # noqa: E501
self._parent_uuid = parent_uuid
@property
def size_sort_order(self):
"""Gets the size_sort_order of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The size_sort_order of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: int
"""
return self._size_sort_order
@size_sort_order.setter
def size_sort_order(self, size_sort_order):
"""Sets the size_sort_order of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param size_sort_order: The size_sort_order of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: int
"""
if size_sort_order is None:
raise ValueError("Invalid value for `size_sort_order`, must not be `None`") # noqa: E501
self._size_sort_order = size_sort_order
@property
def shoe_size(self):
"""Gets the shoe_size of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The shoe_size of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._shoe_size
@shoe_size.setter
def shoe_size(self, shoe_size):
"""Sets the shoe_size of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param shoe_size: The shoe_size of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if shoe_size is None:
raise ValueError("Invalid value for `shoe_size`, must not be `None`") # noqa: E501
self._shoe_size = shoe_size
@property
def market(self):
"""Gets the market of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The market of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: PortfolioitemsIdGetResponsePortfolioItemProductMarket
"""
return self._market
@market.setter
def market(self, market):
"""Sets the market of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param market: The market of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: PortfolioitemsIdGetResponsePortfolioItemProductMarket
"""
if market is None:
raise ValueError("Invalid value for `market`, must not be `None`") # noqa: E501
self._market = market
@property
def upc(self):
"""Gets the upc of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:return: The upc of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:rtype: str
"""
return self._upc
@upc.setter
def upc(self, upc):
"""Sets the upc of this PortfolioitemsIdGetResponsePortfolioItemProduct.
:param upc: The upc of this PortfolioitemsIdGetResponsePortfolioItemProduct. # noqa: E501
:type: str
"""
if upc is None:
raise ValueError("Invalid value for `upc`, must not be `None`") # noqa: E501
self._upc = upc
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PortfolioitemsIdGetResponsePortfolioItemProduct):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 1,198
| 33.464943
| 719
|
/sdk/python/lib/build/lib/io_stockx/models/portfolioitems_id_get_response_portfolio_item_product.py
| 0.647218
| 0.634261
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from io_stockx.models.billing_object import BillingObject # noqa: F401,E501
from io_stockx.models.customer_object_merchant import CustomerObjectMerchant # noqa: F401,E501
from io_stockx.models.customer_object_security import CustomerObjectSecurity # noqa: F401,E501
from io_stockx.models.customer_object_shipping import CustomerObjectShipping # noqa: F401,E501
class CustomerObject(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'str',
'uuid': 'str',
'first_name': 'str',
'last_name': 'str',
'full_name': 'str',
'email': 'str',
'username': 'str',
'email_verified': 'bool',
'default_size': 'str',
'categories': 'list[str]',
'default_category': 'str',
'vacation_date': 'str',
'is_active': 'bool',
'flagged': 'bool',
'hide_portfolio_banner': 'bool',
'refer_url': 'str',
'created_at': 'str',
'created_at_time': 'float',
'is_trader': 'bool',
'ship_by_date': 'bool',
'is_buying': 'bool',
'is_selling': 'bool',
'billing': 'BillingObject',
'shipping': 'CustomerObjectShipping',
'cc_only': 'BillingObject',
'merchant': 'CustomerObjectMerchant',
'promotion_code': 'str',
'paypal_emails': 'str',
'authorization_method': 'str',
'security_override': 'bool',
'team_member': 'bool',
'password_locked': 'bool',
'address_normalize_override': 'bool',
'early_payout_enabled': 'bool',
'early_payout_eligible': 'bool',
'security': 'CustomerObjectSecurity'
}
attribute_map = {
'id': 'id',
'uuid': 'uuid',
'first_name': 'firstName',
'last_name': 'lastName',
'full_name': 'fullName',
'email': 'email',
'username': 'username',
'email_verified': 'emailVerified',
'default_size': 'defaultSize',
'categories': 'categories',
'default_category': 'defaultCategory',
'vacation_date': 'vacationDate',
'is_active': 'isActive',
'flagged': 'flagged',
'hide_portfolio_banner': 'hidePortfolioBanner',
'refer_url': 'referUrl',
'created_at': 'createdAt',
'created_at_time': 'createdAtTime',
'is_trader': 'isTrader',
'ship_by_date': 'shipByDate',
'is_buying': 'isBuying',
'is_selling': 'isSelling',
'billing': 'Billing',
'shipping': 'Shipping',
'cc_only': 'CCOnly',
'merchant': 'Merchant',
'promotion_code': 'promotionCode',
'paypal_emails': 'paypalEmails',
'authorization_method': 'authorizationMethod',
'security_override': 'securityOverride',
'team_member': 'teamMember',
'password_locked': 'passwordLocked',
'address_normalize_override': 'addressNormalizeOverride',
'early_payout_enabled': 'earlyPayoutEnabled',
'early_payout_eligible': 'earlyPayoutEligible',
'security': 'security'
}
def __init__(self, id=None, uuid=None, first_name=None, last_name=None, full_name=None, email=None, username=None, email_verified=None, default_size=None, categories=None, default_category=None, vacation_date=None, is_active=None, flagged=None, hide_portfolio_banner=None, refer_url=None, created_at=None, created_at_time=None, is_trader=None, ship_by_date=None, is_buying=None, is_selling=None, billing=None, shipping=None, cc_only=None, merchant=None, promotion_code=None, paypal_emails=None, authorization_method=None, security_override=None, team_member=None, password_locked=None, address_normalize_override=None, early_payout_enabled=None, early_payout_eligible=None, security=None): # noqa: E501
"""CustomerObject - a model defined in Swagger""" # noqa: E501
self._id = None
self._uuid = None
self._first_name = None
self._last_name = None
self._full_name = None
self._email = None
self._username = None
self._email_verified = None
self._default_size = None
self._categories = None
self._default_category = None
self._vacation_date = None
self._is_active = None
self._flagged = None
self._hide_portfolio_banner = None
self._refer_url = None
self._created_at = None
self._created_at_time = None
self._is_trader = None
self._ship_by_date = None
self._is_buying = None
self._is_selling = None
self._billing = None
self._shipping = None
self._cc_only = None
self._merchant = None
self._promotion_code = None
self._paypal_emails = None
self._authorization_method = None
self._security_override = None
self._team_member = None
self._password_locked = None
self._address_normalize_override = None
self._early_payout_enabled = None
self._early_payout_eligible = None
self._security = None
self.discriminator = None
if id is not None:
self.id = id
if uuid is not None:
self.uuid = uuid
if first_name is not None:
self.first_name = first_name
if last_name is not None:
self.last_name = last_name
if full_name is not None:
self.full_name = full_name
if email is not None:
self.email = email
if username is not None:
self.username = username
if email_verified is not None:
self.email_verified = email_verified
if default_size is not None:
self.default_size = default_size
if categories is not None:
self.categories = categories
if default_category is not None:
self.default_category = default_category
if vacation_date is not None:
self.vacation_date = vacation_date
if is_active is not None:
self.is_active = is_active
if flagged is not None:
self.flagged = flagged
if hide_portfolio_banner is not None:
self.hide_portfolio_banner = hide_portfolio_banner
if refer_url is not None:
self.refer_url = refer_url
if created_at is not None:
self.created_at = created_at
if created_at_time is not None:
self.created_at_time = created_at_time
if is_trader is not None:
self.is_trader = is_trader
if ship_by_date is not None:
self.ship_by_date = ship_by_date
if is_buying is not None:
self.is_buying = is_buying
if is_selling is not None:
self.is_selling = is_selling
if billing is not None:
self.billing = billing
if shipping is not None:
self.shipping = shipping
if cc_only is not None:
self.cc_only = cc_only
if merchant is not None:
self.merchant = merchant
if promotion_code is not None:
self.promotion_code = promotion_code
if paypal_emails is not None:
self.paypal_emails = paypal_emails
if authorization_method is not None:
self.authorization_method = authorization_method
if security_override is not None:
self.security_override = security_override
if team_member is not None:
self.team_member = team_member
if password_locked is not None:
self.password_locked = password_locked
if address_normalize_override is not None:
self.address_normalize_override = address_normalize_override
if early_payout_enabled is not None:
self.early_payout_enabled = early_payout_enabled
if early_payout_eligible is not None:
self.early_payout_eligible = early_payout_eligible
if security is not None:
self.security = security
@property
def id(self):
"""Gets the id of this CustomerObject. # noqa: E501
:return: The id of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this CustomerObject.
:param id: The id of this CustomerObject. # noqa: E501
:type: str
"""
self._id = id
@property
def uuid(self):
"""Gets the uuid of this CustomerObject. # noqa: E501
:return: The uuid of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._uuid
@uuid.setter
def uuid(self, uuid):
"""Sets the uuid of this CustomerObject.
:param uuid: The uuid of this CustomerObject. # noqa: E501
:type: str
"""
self._uuid = uuid
@property
def first_name(self):
"""Gets the first_name of this CustomerObject. # noqa: E501
:return: The first_name of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._first_name
@first_name.setter
def first_name(self, first_name):
"""Sets the first_name of this CustomerObject.
:param first_name: The first_name of this CustomerObject. # noqa: E501
:type: str
"""
self._first_name = first_name
@property
def last_name(self):
"""Gets the last_name of this CustomerObject. # noqa: E501
:return: The last_name of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._last_name
@last_name.setter
def last_name(self, last_name):
"""Sets the last_name of this CustomerObject.
:param last_name: The last_name of this CustomerObject. # noqa: E501
:type: str
"""
self._last_name = last_name
@property
def full_name(self):
"""Gets the full_name of this CustomerObject. # noqa: E501
:return: The full_name of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._full_name
@full_name.setter
def full_name(self, full_name):
"""Sets the full_name of this CustomerObject.
:param full_name: The full_name of this CustomerObject. # noqa: E501
:type: str
"""
self._full_name = full_name
@property
def email(self):
"""Gets the email of this CustomerObject. # noqa: E501
:return: The email of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._email
@email.setter
def email(self, email):
"""Sets the email of this CustomerObject.
:param email: The email of this CustomerObject. # noqa: E501
:type: str
"""
self._email = email
@property
def username(self):
"""Gets the username of this CustomerObject. # noqa: E501
:return: The username of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._username
@username.setter
def username(self, username):
"""Sets the username of this CustomerObject.
:param username: The username of this CustomerObject. # noqa: E501
:type: str
"""
self._username = username
@property
def email_verified(self):
"""Gets the email_verified of this CustomerObject. # noqa: E501
:return: The email_verified of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._email_verified
@email_verified.setter
def email_verified(self, email_verified):
"""Sets the email_verified of this CustomerObject.
:param email_verified: The email_verified of this CustomerObject. # noqa: E501
:type: bool
"""
self._email_verified = email_verified
@property
def default_size(self):
"""Gets the default_size of this CustomerObject. # noqa: E501
:return: The default_size of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._default_size
@default_size.setter
def default_size(self, default_size):
"""Sets the default_size of this CustomerObject.
:param default_size: The default_size of this CustomerObject. # noqa: E501
:type: str
"""
self._default_size = default_size
@property
def categories(self):
"""Gets the categories of this CustomerObject. # noqa: E501
:return: The categories of this CustomerObject. # noqa: E501
:rtype: list[str]
"""
return self._categories
@categories.setter
def categories(self, categories):
"""Sets the categories of this CustomerObject.
:param categories: The categories of this CustomerObject. # noqa: E501
:type: list[str]
"""
self._categories = categories
@property
def default_category(self):
"""Gets the default_category of this CustomerObject. # noqa: E501
:return: The default_category of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._default_category
@default_category.setter
def default_category(self, default_category):
"""Sets the default_category of this CustomerObject.
:param default_category: The default_category of this CustomerObject. # noqa: E501
:type: str
"""
self._default_category = default_category
@property
def vacation_date(self):
"""Gets the vacation_date of this CustomerObject. # noqa: E501
:return: The vacation_date of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._vacation_date
@vacation_date.setter
def vacation_date(self, vacation_date):
"""Sets the vacation_date of this CustomerObject.
:param vacation_date: The vacation_date of this CustomerObject. # noqa: E501
:type: str
"""
self._vacation_date = vacation_date
@property
def is_active(self):
"""Gets the is_active of this CustomerObject. # noqa: E501
:return: The is_active of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._is_active
@is_active.setter
def is_active(self, is_active):
"""Sets the is_active of this CustomerObject.
:param is_active: The is_active of this CustomerObject. # noqa: E501
:type: bool
"""
self._is_active = is_active
@property
def flagged(self):
"""Gets the flagged of this CustomerObject. # noqa: E501
:return: The flagged of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._flagged
@flagged.setter
def flagged(self, flagged):
"""Sets the flagged of this CustomerObject.
:param flagged: The flagged of this CustomerObject. # noqa: E501
:type: bool
"""
self._flagged = flagged
@property
def hide_portfolio_banner(self):
"""Gets the hide_portfolio_banner of this CustomerObject. # noqa: E501
:return: The hide_portfolio_banner of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._hide_portfolio_banner
@hide_portfolio_banner.setter
def hide_portfolio_banner(self, hide_portfolio_banner):
"""Sets the hide_portfolio_banner of this CustomerObject.
:param hide_portfolio_banner: The hide_portfolio_banner of this CustomerObject. # noqa: E501
:type: bool
"""
self._hide_portfolio_banner = hide_portfolio_banner
@property
def refer_url(self):
"""Gets the refer_url of this CustomerObject. # noqa: E501
:return: The refer_url of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._refer_url
@refer_url.setter
def refer_url(self, refer_url):
"""Sets the refer_url of this CustomerObject.
:param refer_url: The refer_url of this CustomerObject. # noqa: E501
:type: str
"""
self._refer_url = refer_url
@property
def created_at(self):
"""Gets the created_at of this CustomerObject. # noqa: E501
:return: The created_at of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
"""Sets the created_at of this CustomerObject.
:param created_at: The created_at of this CustomerObject. # noqa: E501
:type: str
"""
self._created_at = created_at
@property
def created_at_time(self):
"""Gets the created_at_time of this CustomerObject. # noqa: E501
:return: The created_at_time of this CustomerObject. # noqa: E501
:rtype: float
"""
return self._created_at_time
@created_at_time.setter
def created_at_time(self, created_at_time):
"""Sets the created_at_time of this CustomerObject.
:param created_at_time: The created_at_time of this CustomerObject. # noqa: E501
:type: float
"""
self._created_at_time = created_at_time
@property
def is_trader(self):
"""Gets the is_trader of this CustomerObject. # noqa: E501
:return: The is_trader of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._is_trader
@is_trader.setter
def is_trader(self, is_trader):
"""Sets the is_trader of this CustomerObject.
:param is_trader: The is_trader of this CustomerObject. # noqa: E501
:type: bool
"""
self._is_trader = is_trader
@property
def ship_by_date(self):
"""Gets the ship_by_date of this CustomerObject. # noqa: E501
:return: The ship_by_date of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._ship_by_date
@ship_by_date.setter
def ship_by_date(self, ship_by_date):
"""Sets the ship_by_date of this CustomerObject.
:param ship_by_date: The ship_by_date of this CustomerObject. # noqa: E501
:type: bool
"""
self._ship_by_date = ship_by_date
@property
def is_buying(self):
"""Gets the is_buying of this CustomerObject. # noqa: E501
:return: The is_buying of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._is_buying
@is_buying.setter
def is_buying(self, is_buying):
"""Sets the is_buying of this CustomerObject.
:param is_buying: The is_buying of this CustomerObject. # noqa: E501
:type: bool
"""
self._is_buying = is_buying
@property
def is_selling(self):
"""Gets the is_selling of this CustomerObject. # noqa: E501
:return: The is_selling of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._is_selling
@is_selling.setter
def is_selling(self, is_selling):
"""Sets the is_selling of this CustomerObject.
:param is_selling: The is_selling of this CustomerObject. # noqa: E501
:type: bool
"""
self._is_selling = is_selling
@property
def billing(self):
"""Gets the billing of this CustomerObject. # noqa: E501
:return: The billing of this CustomerObject. # noqa: E501
:rtype: BillingObject
"""
return self._billing
@billing.setter
def billing(self, billing):
"""Sets the billing of this CustomerObject.
:param billing: The billing of this CustomerObject. # noqa: E501
:type: BillingObject
"""
self._billing = billing
@property
def shipping(self):
"""Gets the shipping of this CustomerObject. # noqa: E501
:return: The shipping of this CustomerObject. # noqa: E501
:rtype: CustomerObjectShipping
"""
return self._shipping
@shipping.setter
def shipping(self, shipping):
"""Sets the shipping of this CustomerObject.
:param shipping: The shipping of this CustomerObject. # noqa: E501
:type: CustomerObjectShipping
"""
self._shipping = shipping
@property
def cc_only(self):
"""Gets the cc_only of this CustomerObject. # noqa: E501
:return: The cc_only of this CustomerObject. # noqa: E501
:rtype: BillingObject
"""
return self._cc_only
@cc_only.setter
def cc_only(self, cc_only):
"""Sets the cc_only of this CustomerObject.
:param cc_only: The cc_only of this CustomerObject. # noqa: E501
:type: BillingObject
"""
self._cc_only = cc_only
@property
def merchant(self):
"""Gets the merchant of this CustomerObject. # noqa: E501
:return: The merchant of this CustomerObject. # noqa: E501
:rtype: CustomerObjectMerchant
"""
return self._merchant
@merchant.setter
def merchant(self, merchant):
"""Sets the merchant of this CustomerObject.
:param merchant: The merchant of this CustomerObject. # noqa: E501
:type: CustomerObjectMerchant
"""
self._merchant = merchant
@property
def promotion_code(self):
"""Gets the promotion_code of this CustomerObject. # noqa: E501
:return: The promotion_code of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._promotion_code
@promotion_code.setter
def promotion_code(self, promotion_code):
"""Sets the promotion_code of this CustomerObject.
:param promotion_code: The promotion_code of this CustomerObject. # noqa: E501
:type: str
"""
self._promotion_code = promotion_code
@property
def paypal_emails(self):
"""Gets the paypal_emails of this CustomerObject. # noqa: E501
:return: The paypal_emails of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._paypal_emails
@paypal_emails.setter
def paypal_emails(self, paypal_emails):
"""Sets the paypal_emails of this CustomerObject.
:param paypal_emails: The paypal_emails of this CustomerObject. # noqa: E501
:type: str
"""
self._paypal_emails = paypal_emails
@property
def authorization_method(self):
"""Gets the authorization_method of this CustomerObject. # noqa: E501
:return: The authorization_method of this CustomerObject. # noqa: E501
:rtype: str
"""
return self._authorization_method
@authorization_method.setter
def authorization_method(self, authorization_method):
"""Sets the authorization_method of this CustomerObject.
:param authorization_method: The authorization_method of this CustomerObject. # noqa: E501
:type: str
"""
self._authorization_method = authorization_method
@property
def security_override(self):
"""Gets the security_override of this CustomerObject. # noqa: E501
:return: The security_override of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._security_override
@security_override.setter
def security_override(self, security_override):
"""Sets the security_override of this CustomerObject.
:param security_override: The security_override of this CustomerObject. # noqa: E501
:type: bool
"""
self._security_override = security_override
@property
def team_member(self):
"""Gets the team_member of this CustomerObject. # noqa: E501
:return: The team_member of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._team_member
@team_member.setter
def team_member(self, team_member):
"""Sets the team_member of this CustomerObject.
:param team_member: The team_member of this CustomerObject. # noqa: E501
:type: bool
"""
self._team_member = team_member
@property
def password_locked(self):
"""Gets the password_locked of this CustomerObject. # noqa: E501
:return: The password_locked of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._password_locked
@password_locked.setter
def password_locked(self, password_locked):
"""Sets the password_locked of this CustomerObject.
:param password_locked: The password_locked of this CustomerObject. # noqa: E501
:type: bool
"""
self._password_locked = password_locked
@property
def address_normalize_override(self):
"""Gets the address_normalize_override of this CustomerObject. # noqa: E501
:return: The address_normalize_override of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._address_normalize_override
@address_normalize_override.setter
def address_normalize_override(self, address_normalize_override):
"""Sets the address_normalize_override of this CustomerObject.
:param address_normalize_override: The address_normalize_override of this CustomerObject. # noqa: E501
:type: bool
"""
self._address_normalize_override = address_normalize_override
@property
def early_payout_enabled(self):
"""Gets the early_payout_enabled of this CustomerObject. # noqa: E501
:return: The early_payout_enabled of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._early_payout_enabled
@early_payout_enabled.setter
def early_payout_enabled(self, early_payout_enabled):
"""Sets the early_payout_enabled of this CustomerObject.
:param early_payout_enabled: The early_payout_enabled of this CustomerObject. # noqa: E501
:type: bool
"""
self._early_payout_enabled = early_payout_enabled
@property
def early_payout_eligible(self):
"""Gets the early_payout_eligible of this CustomerObject. # noqa: E501
:return: The early_payout_eligible of this CustomerObject. # noqa: E501
:rtype: bool
"""
return self._early_payout_eligible
@early_payout_eligible.setter
def early_payout_eligible(self, early_payout_eligible):
"""Sets the early_payout_eligible of this CustomerObject.
:param early_payout_eligible: The early_payout_eligible of this CustomerObject. # noqa: E501
:type: bool
"""
self._early_payout_eligible = early_payout_eligible
@property
def security(self):
"""Gets the security of this CustomerObject. # noqa: E501
:return: The security of this CustomerObject. # noqa: E501
:rtype: CustomerObjectSecurity
"""
return self._security
@security.setter
def security(self, security):
"""Sets the security of this CustomerObject.
:param security: The security of this CustomerObject. # noqa: E501
:type: CustomerObjectSecurity
"""
self._security = security
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CustomerObject):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 1,027
| 27.773125
| 707
|
/sdk/python/lib/io_stockx/models/customer_object.py
| 0.595431
| 0.583012
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
# flake8: noqa
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import models into model package
from io_stockx.models.address_object import AddressObject
from io_stockx.models.billing_object import BillingObject
from io_stockx.models.customer_object import CustomerObject
from io_stockx.models.customer_object_merchant import CustomerObjectMerchant
from io_stockx.models.customer_object_security import CustomerObjectSecurity
from io_stockx.models.customer_object_shipping import CustomerObjectShipping
from io_stockx.models.customers_id_selling_current import CustomersIdSellingCurrent
from io_stockx.models.customers_id_selling_current_pagination import CustomersIdSellingCurrentPagination
from io_stockx.models.customers_id_selling_current_paging import CustomersIdSellingCurrentPaging
from io_stockx.models.login_request import LoginRequest
from io_stockx.models.login_response import LoginResponse
from io_stockx.models.market_data import MarketData
from io_stockx.models.market_data_market import MarketDataMarket
from io_stockx.models.portfolio_id_del_request import PortfolioIdDelRequest
from io_stockx.models.portfolio_id_del_response import PortfolioIdDelResponse
from io_stockx.models.portfolio_id_del_response_portfolio_item import PortfolioIdDelResponsePortfolioItem
from io_stockx.models.portfolio_id_del_response_portfolio_item_merchant import PortfolioIdDelResponsePortfolioItemMerchant
from io_stockx.models.portfolio_id_del_response_portfolio_item_product import PortfolioIdDelResponsePortfolioItemProduct
from io_stockx.models.portfolio_id_del_response_portfolio_item_product_market import PortfolioIdDelResponsePortfolioItemProductMarket
from io_stockx.models.portfolio_id_del_response_portfolio_item_product_media import PortfolioIdDelResponsePortfolioItemProductMedia
from io_stockx.models.portfolio_id_del_response_portfolio_item_product_meta import PortfolioIdDelResponsePortfolioItemProductMeta
from io_stockx.models.portfolio_id_del_response_portfolio_item_product_shipping import PortfolioIdDelResponsePortfolioItemProductShipping
from io_stockx.models.portfolio_id_del_response_portfolio_item_tracking import PortfolioIdDelResponsePortfolioItemTracking
from io_stockx.models.portfolio_request import PortfolioRequest
from io_stockx.models.portfolio_request_portfolio_item import PortfolioRequestPortfolioItem
from io_stockx.models.portfolio_response import PortfolioResponse
from io_stockx.models.portfolio_response_portfolio_item import PortfolioResponsePortfolioItem
from io_stockx.models.portfolio_response_portfolio_item_product import PortfolioResponsePortfolioItemProduct
from io_stockx.models.portfolio_response_portfolio_item_product_market import PortfolioResponsePortfolioItemProductMarket
from io_stockx.models.portfolio_response_portfolio_item_product_media import PortfolioResponsePortfolioItemProductMedia
from io_stockx.models.portfolio_response_portfolio_item_tracking import PortfolioResponsePortfolioItemTracking
from io_stockx.models.portfolioitems_id_get_response import PortfolioitemsIdGetResponse
from io_stockx.models.portfolioitems_id_get_response_portfolio_item import PortfolioitemsIdGetResponsePortfolioItem
from io_stockx.models.portfolioitems_id_get_response_portfolio_item_product import PortfolioitemsIdGetResponsePortfolioItemProduct
from io_stockx.models.portfolioitems_id_get_response_portfolio_item_product_market import PortfolioitemsIdGetResponsePortfolioItemProductMarket
from io_stockx.models.product_info import ProductInfo
from io_stockx.models.product_info_attributes import ProductInfoAttributes
from io_stockx.models.product_info_attributes_traits import ProductInfoAttributesTraits
from io_stockx.models.product_info_data import ProductInfoData
from io_stockx.models.product_info_meta import ProductInfoMeta
from io_stockx.models.product_info_product import ProductInfoProduct
from io_stockx.models.product_info_product_attributes import ProductInfoProductAttributes
from io_stockx.models.product_lookup_response import ProductLookupResponse
from io_stockx.models.product_response import ProductResponse
from io_stockx.models.product_response_product import ProductResponseProduct
from io_stockx.models.product_response_product_children import ProductResponseProductChildren
from io_stockx.models.product_response_product_children_productid import ProductResponseProductChildrenPRODUCTID
from io_stockx.models.product_response_product_children_productid_market import ProductResponseProductChildrenPRODUCTIDMarket
from io_stockx.models.product_response_product_media import ProductResponseProductMedia
from io_stockx.models.product_response_product_meta import ProductResponseProductMeta
from io_stockx.models.search_hit import SearchHit
from io_stockx.models.search_hit_media import SearchHitMedia
from io_stockx.models.search_hit_searchable_traits import SearchHitSearchableTraits
from io_stockx.models.search_results import SearchResults
from io_stockx.models.subscriptions_response import SubscriptionsResponse
from io_stockx.models.webhooks_get_response import WebhooksGetResponse
from io_stockx.models.webhooks_id_get_response import WebhooksIdGetResponse
from io_stockx.models.webhooks_post_request import WebhooksPostRequest
from io_stockx.models.webhooks_post_response import WebhooksPostResponse
|
Python
| 76
| 72.684212
| 176
|
/sdk/python/lib/build/lib/io_stockx/models/__init__.py
| 0.872143
| 0.870714
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import io_stockx
from io_stockx.models.portfolio_id_del_response_portfolio_item_product_media import PortfolioIdDelResponsePortfolioItemProductMedia # noqa: E501
from io_stockx.rest import ApiException
class TestPortfolioIdDelResponsePortfolioItemProductMedia(unittest.TestCase):
"""PortfolioIdDelResponsePortfolioItemProductMedia unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testPortfolioIdDelResponsePortfolioItemProductMedia(self):
"""Test PortfolioIdDelResponsePortfolioItemProductMedia"""
# FIXME: construct object with mandatory attributes with example values
# model = io_stockx.models.portfolio_id_del_response_portfolio_item_product_media.PortfolioIdDelResponsePortfolioItemProductMedia() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
Python
| 40
| 30.125
| 176
|
/sdk/python/lib/build/lib/test/test_portfolio_id_del_response_portfolio_item_product_media.py
| 0.747791
| 0.737349
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from io_stockx.models.portfolio_id_del_response_portfolio_item_merchant import PortfolioIdDelResponsePortfolioItemMerchant # noqa: F401,E501
from io_stockx.models.portfolio_id_del_response_portfolio_item_product import PortfolioIdDelResponsePortfolioItemProduct # noqa: F401,E501
from io_stockx.models.portfolio_id_del_response_portfolio_item_tracking import PortfolioIdDelResponsePortfolioItemTracking # noqa: F401,E501
class PortfolioIdDelResponsePortfolioItem(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'chain_id': 'str',
'customer_id': 'int',
'inventory_id': 'str',
'product_id': 'str',
'sku_uuid': 'str',
'merchant_id': 'int',
'condition': 'int',
'action': 'int',
'action_by': 'int',
'amount': 'int',
'expires_at': 'str',
'expires_at_time': 'int',
'gain_loss_dollars': 'int',
'gain_loss_percentage': 'int',
'market_value': 'str',
'matched_state': 'int',
'purchase_date': 'str',
'purchase_date_time': 'int',
'state': 'int',
'text': 'str',
'notes': 'str',
'created_at_time': 'int',
'can_edit': 'bool',
'can_delete': 'bool',
'tracking': 'PortfolioIdDelResponsePortfolioItemTracking',
'meta': 'object',
'product': 'PortfolioIdDelResponsePortfolioItemProduct',
'merchant': 'PortfolioIdDelResponsePortfolioItemMerchant'
}
attribute_map = {
'chain_id': 'chainId',
'customer_id': 'customerId',
'inventory_id': 'inventoryId',
'product_id': 'productId',
'sku_uuid': 'skuUuid',
'merchant_id': 'merchantId',
'condition': 'condition',
'action': 'action',
'action_by': 'actionBy',
'amount': 'amount',
'expires_at': 'expiresAt',
'expires_at_time': 'expiresAtTime',
'gain_loss_dollars': 'gainLossDollars',
'gain_loss_percentage': 'gainLossPercentage',
'market_value': 'marketValue',
'matched_state': 'matchedState',
'purchase_date': 'purchaseDate',
'purchase_date_time': 'purchaseDateTime',
'state': 'state',
'text': 'text',
'notes': 'notes',
'created_at_time': 'createdAtTime',
'can_edit': 'canEdit',
'can_delete': 'canDelete',
'tracking': 'Tracking',
'meta': 'meta',
'product': 'product',
'merchant': 'Merchant'
}
def __init__(self, chain_id=None, customer_id=None, inventory_id=None, product_id=None, sku_uuid=None, merchant_id=None, condition=None, action=None, action_by=None, amount=None, expires_at=None, expires_at_time=None, gain_loss_dollars=None, gain_loss_percentage=None, market_value=None, matched_state=None, purchase_date=None, purchase_date_time=None, state=None, text=None, notes=None, created_at_time=None, can_edit=None, can_delete=None, tracking=None, meta=None, product=None, merchant=None): # noqa: E501
"""PortfolioIdDelResponsePortfolioItem - a model defined in Swagger""" # noqa: E501
self._chain_id = None
self._customer_id = None
self._inventory_id = None
self._product_id = None
self._sku_uuid = None
self._merchant_id = None
self._condition = None
self._action = None
self._action_by = None
self._amount = None
self._expires_at = None
self._expires_at_time = None
self._gain_loss_dollars = None
self._gain_loss_percentage = None
self._market_value = None
self._matched_state = None
self._purchase_date = None
self._purchase_date_time = None
self._state = None
self._text = None
self._notes = None
self._created_at_time = None
self._can_edit = None
self._can_delete = None
self._tracking = None
self._meta = None
self._product = None
self._merchant = None
self.discriminator = None
self.chain_id = chain_id
self.customer_id = customer_id
self.inventory_id = inventory_id
self.product_id = product_id
self.sku_uuid = sku_uuid
self.merchant_id = merchant_id
self.condition = condition
self.action = action
self.action_by = action_by
self.amount = amount
self.expires_at = expires_at
self.expires_at_time = expires_at_time
self.gain_loss_dollars = gain_loss_dollars
self.gain_loss_percentage = gain_loss_percentage
self.market_value = market_value
self.matched_state = matched_state
self.purchase_date = purchase_date
self.purchase_date_time = purchase_date_time
self.state = state
self.text = text
self.notes = notes
self.created_at_time = created_at_time
self.can_edit = can_edit
self.can_delete = can_delete
self.tracking = tracking
self.meta = meta
self.product = product
self.merchant = merchant
@property
def chain_id(self):
"""Gets the chain_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The chain_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._chain_id
@chain_id.setter
def chain_id(self, chain_id):
"""Sets the chain_id of this PortfolioIdDelResponsePortfolioItem.
:param chain_id: The chain_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if chain_id is None:
raise ValueError("Invalid value for `chain_id`, must not be `None`") # noqa: E501
self._chain_id = chain_id
@property
def customer_id(self):
"""Gets the customer_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The customer_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._customer_id
@customer_id.setter
def customer_id(self, customer_id):
"""Sets the customer_id of this PortfolioIdDelResponsePortfolioItem.
:param customer_id: The customer_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if customer_id is None:
raise ValueError("Invalid value for `customer_id`, must not be `None`") # noqa: E501
self._customer_id = customer_id
@property
def inventory_id(self):
"""Gets the inventory_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The inventory_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._inventory_id
@inventory_id.setter
def inventory_id(self, inventory_id):
"""Sets the inventory_id of this PortfolioIdDelResponsePortfolioItem.
:param inventory_id: The inventory_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if inventory_id is None:
raise ValueError("Invalid value for `inventory_id`, must not be `None`") # noqa: E501
self._inventory_id = inventory_id
@property
def product_id(self):
"""Gets the product_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The product_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._product_id
@product_id.setter
def product_id(self, product_id):
"""Sets the product_id of this PortfolioIdDelResponsePortfolioItem.
:param product_id: The product_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if product_id is None:
raise ValueError("Invalid value for `product_id`, must not be `None`") # noqa: E501
self._product_id = product_id
@property
def sku_uuid(self):
"""Gets the sku_uuid of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The sku_uuid of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._sku_uuid
@sku_uuid.setter
def sku_uuid(self, sku_uuid):
"""Sets the sku_uuid of this PortfolioIdDelResponsePortfolioItem.
:param sku_uuid: The sku_uuid of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if sku_uuid is None:
raise ValueError("Invalid value for `sku_uuid`, must not be `None`") # noqa: E501
self._sku_uuid = sku_uuid
@property
def merchant_id(self):
"""Gets the merchant_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The merchant_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._merchant_id
@merchant_id.setter
def merchant_id(self, merchant_id):
"""Sets the merchant_id of this PortfolioIdDelResponsePortfolioItem.
:param merchant_id: The merchant_id of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if merchant_id is None:
raise ValueError("Invalid value for `merchant_id`, must not be `None`") # noqa: E501
self._merchant_id = merchant_id
@property
def condition(self):
"""Gets the condition of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The condition of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._condition
@condition.setter
def condition(self, condition):
"""Sets the condition of this PortfolioIdDelResponsePortfolioItem.
:param condition: The condition of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if condition is None:
raise ValueError("Invalid value for `condition`, must not be `None`") # noqa: E501
self._condition = condition
@property
def action(self):
"""Gets the action of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The action of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._action
@action.setter
def action(self, action):
"""Sets the action of this PortfolioIdDelResponsePortfolioItem.
:param action: The action of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if action is None:
raise ValueError("Invalid value for `action`, must not be `None`") # noqa: E501
self._action = action
@property
def action_by(self):
"""Gets the action_by of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The action_by of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._action_by
@action_by.setter
def action_by(self, action_by):
"""Sets the action_by of this PortfolioIdDelResponsePortfolioItem.
:param action_by: The action_by of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if action_by is None:
raise ValueError("Invalid value for `action_by`, must not be `None`") # noqa: E501
self._action_by = action_by
@property
def amount(self):
"""Gets the amount of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The amount of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._amount
@amount.setter
def amount(self, amount):
"""Sets the amount of this PortfolioIdDelResponsePortfolioItem.
:param amount: The amount of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if amount is None:
raise ValueError("Invalid value for `amount`, must not be `None`") # noqa: E501
self._amount = amount
@property
def expires_at(self):
"""Gets the expires_at of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The expires_at of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._expires_at
@expires_at.setter
def expires_at(self, expires_at):
"""Sets the expires_at of this PortfolioIdDelResponsePortfolioItem.
:param expires_at: The expires_at of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if expires_at is None:
raise ValueError("Invalid value for `expires_at`, must not be `None`") # noqa: E501
self._expires_at = expires_at
@property
def expires_at_time(self):
"""Gets the expires_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The expires_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._expires_at_time
@expires_at_time.setter
def expires_at_time(self, expires_at_time):
"""Sets the expires_at_time of this PortfolioIdDelResponsePortfolioItem.
:param expires_at_time: The expires_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if expires_at_time is None:
raise ValueError("Invalid value for `expires_at_time`, must not be `None`") # noqa: E501
self._expires_at_time = expires_at_time
@property
def gain_loss_dollars(self):
"""Gets the gain_loss_dollars of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The gain_loss_dollars of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._gain_loss_dollars
@gain_loss_dollars.setter
def gain_loss_dollars(self, gain_loss_dollars):
"""Sets the gain_loss_dollars of this PortfolioIdDelResponsePortfolioItem.
:param gain_loss_dollars: The gain_loss_dollars of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if gain_loss_dollars is None:
raise ValueError("Invalid value for `gain_loss_dollars`, must not be `None`") # noqa: E501
self._gain_loss_dollars = gain_loss_dollars
@property
def gain_loss_percentage(self):
"""Gets the gain_loss_percentage of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The gain_loss_percentage of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._gain_loss_percentage
@gain_loss_percentage.setter
def gain_loss_percentage(self, gain_loss_percentage):
"""Sets the gain_loss_percentage of this PortfolioIdDelResponsePortfolioItem.
:param gain_loss_percentage: The gain_loss_percentage of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if gain_loss_percentage is None:
raise ValueError("Invalid value for `gain_loss_percentage`, must not be `None`") # noqa: E501
self._gain_loss_percentage = gain_loss_percentage
@property
def market_value(self):
"""Gets the market_value of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The market_value of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._market_value
@market_value.setter
def market_value(self, market_value):
"""Sets the market_value of this PortfolioIdDelResponsePortfolioItem.
:param market_value: The market_value of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if market_value is None:
raise ValueError("Invalid value for `market_value`, must not be `None`") # noqa: E501
self._market_value = market_value
@property
def matched_state(self):
"""Gets the matched_state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The matched_state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._matched_state
@matched_state.setter
def matched_state(self, matched_state):
"""Sets the matched_state of this PortfolioIdDelResponsePortfolioItem.
:param matched_state: The matched_state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if matched_state is None:
raise ValueError("Invalid value for `matched_state`, must not be `None`") # noqa: E501
self._matched_state = matched_state
@property
def purchase_date(self):
"""Gets the purchase_date of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The purchase_date of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._purchase_date
@purchase_date.setter
def purchase_date(self, purchase_date):
"""Sets the purchase_date of this PortfolioIdDelResponsePortfolioItem.
:param purchase_date: The purchase_date of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if purchase_date is None:
raise ValueError("Invalid value for `purchase_date`, must not be `None`") # noqa: E501
self._purchase_date = purchase_date
@property
def purchase_date_time(self):
"""Gets the purchase_date_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The purchase_date_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._purchase_date_time
@purchase_date_time.setter
def purchase_date_time(self, purchase_date_time):
"""Sets the purchase_date_time of this PortfolioIdDelResponsePortfolioItem.
:param purchase_date_time: The purchase_date_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if purchase_date_time is None:
raise ValueError("Invalid value for `purchase_date_time`, must not be `None`") # noqa: E501
self._purchase_date_time = purchase_date_time
@property
def state(self):
"""Gets the state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._state
@state.setter
def state(self, state):
"""Sets the state of this PortfolioIdDelResponsePortfolioItem.
:param state: The state of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if state is None:
raise ValueError("Invalid value for `state`, must not be `None`") # noqa: E501
self._state = state
@property
def text(self):
"""Gets the text of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The text of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._text
@text.setter
def text(self, text):
"""Sets the text of this PortfolioIdDelResponsePortfolioItem.
:param text: The text of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if text is None:
raise ValueError("Invalid value for `text`, must not be `None`") # noqa: E501
self._text = text
@property
def notes(self):
"""Gets the notes of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The notes of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: str
"""
return self._notes
@notes.setter
def notes(self, notes):
"""Sets the notes of this PortfolioIdDelResponsePortfolioItem.
:param notes: The notes of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: str
"""
if notes is None:
raise ValueError("Invalid value for `notes`, must not be `None`") # noqa: E501
self._notes = notes
@property
def created_at_time(self):
"""Gets the created_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The created_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: int
"""
return self._created_at_time
@created_at_time.setter
def created_at_time(self, created_at_time):
"""Sets the created_at_time of this PortfolioIdDelResponsePortfolioItem.
:param created_at_time: The created_at_time of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: int
"""
if created_at_time is None:
raise ValueError("Invalid value for `created_at_time`, must not be `None`") # noqa: E501
self._created_at_time = created_at_time
@property
def can_edit(self):
"""Gets the can_edit of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The can_edit of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: bool
"""
return self._can_edit
@can_edit.setter
def can_edit(self, can_edit):
"""Sets the can_edit of this PortfolioIdDelResponsePortfolioItem.
:param can_edit: The can_edit of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: bool
"""
if can_edit is None:
raise ValueError("Invalid value for `can_edit`, must not be `None`") # noqa: E501
self._can_edit = can_edit
@property
def can_delete(self):
"""Gets the can_delete of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The can_delete of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: bool
"""
return self._can_delete
@can_delete.setter
def can_delete(self, can_delete):
"""Sets the can_delete of this PortfolioIdDelResponsePortfolioItem.
:param can_delete: The can_delete of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: bool
"""
if can_delete is None:
raise ValueError("Invalid value for `can_delete`, must not be `None`") # noqa: E501
self._can_delete = can_delete
@property
def tracking(self):
"""Gets the tracking of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The tracking of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: PortfolioIdDelResponsePortfolioItemTracking
"""
return self._tracking
@tracking.setter
def tracking(self, tracking):
"""Sets the tracking of this PortfolioIdDelResponsePortfolioItem.
:param tracking: The tracking of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: PortfolioIdDelResponsePortfolioItemTracking
"""
if tracking is None:
raise ValueError("Invalid value for `tracking`, must not be `None`") # noqa: E501
self._tracking = tracking
@property
def meta(self):
"""Gets the meta of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The meta of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: object
"""
return self._meta
@meta.setter
def meta(self, meta):
"""Sets the meta of this PortfolioIdDelResponsePortfolioItem.
:param meta: The meta of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: object
"""
if meta is None:
raise ValueError("Invalid value for `meta`, must not be `None`") # noqa: E501
self._meta = meta
@property
def product(self):
"""Gets the product of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The product of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: PortfolioIdDelResponsePortfolioItemProduct
"""
return self._product
@product.setter
def product(self, product):
"""Sets the product of this PortfolioIdDelResponsePortfolioItem.
:param product: The product of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: PortfolioIdDelResponsePortfolioItemProduct
"""
if product is None:
raise ValueError("Invalid value for `product`, must not be `None`") # noqa: E501
self._product = product
@property
def merchant(self):
"""Gets the merchant of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:return: The merchant of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:rtype: PortfolioIdDelResponsePortfolioItemMerchant
"""
return self._merchant
@merchant.setter
def merchant(self, merchant):
"""Sets the merchant of this PortfolioIdDelResponsePortfolioItem.
:param merchant: The merchant of this PortfolioIdDelResponsePortfolioItem. # noqa: E501
:type: PortfolioIdDelResponsePortfolioItemMerchant
"""
if merchant is None:
raise ValueError("Invalid value for `merchant`, must not be `None`") # noqa: E501
self._merchant = merchant
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PortfolioIdDelResponsePortfolioItem):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 846
| 31.914894
| 515
|
/sdk/python/lib/build/lib/io_stockx/models/portfolio_id_del_response_portfolio_item.py
| 0.626517
| 0.613122
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class ProductInfoProductAttributes(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'product_category': 'str',
'url_key': 'str',
'slug': 'str',
'brand': 'str',
'ticker': 'str',
'style_id': 'str',
'model': 'str',
'name': 'str',
'title': 'str',
'size_locale': 'str',
'size_title': 'str',
'size_descriptor': 'str',
'size_all_descriptor': 'str',
'gender': 'str',
'condition': 'str',
'minimum_bid': 'int',
'uniq_bids': 'bool',
'primary_category': 'str',
'secondary_category': 'str'
}
attribute_map = {
'product_category': 'product_category',
'url_key': 'url_key',
'slug': 'slug',
'brand': 'brand',
'ticker': 'ticker',
'style_id': 'style_id',
'model': 'model',
'name': 'name',
'title': 'title',
'size_locale': 'size_locale',
'size_title': 'size_title',
'size_descriptor': 'size_descriptor',
'size_all_descriptor': 'size_all_descriptor',
'gender': 'gender',
'condition': 'condition',
'minimum_bid': 'minimum_bid',
'uniq_bids': 'uniq_bids',
'primary_category': 'primary_category',
'secondary_category': 'secondary_category'
}
def __init__(self, product_category=None, url_key=None, slug=None, brand=None, ticker=None, style_id=None, model=None, name=None, title=None, size_locale=None, size_title=None, size_descriptor=None, size_all_descriptor=None, gender=None, condition=None, minimum_bid=None, uniq_bids=None, primary_category=None, secondary_category=None): # noqa: E501
"""ProductInfoProductAttributes - a model defined in Swagger""" # noqa: E501
self._product_category = None
self._url_key = None
self._slug = None
self._brand = None
self._ticker = None
self._style_id = None
self._model = None
self._name = None
self._title = None
self._size_locale = None
self._size_title = None
self._size_descriptor = None
self._size_all_descriptor = None
self._gender = None
self._condition = None
self._minimum_bid = None
self._uniq_bids = None
self._primary_category = None
self._secondary_category = None
self.discriminator = None
if product_category is not None:
self.product_category = product_category
if url_key is not None:
self.url_key = url_key
if slug is not None:
self.slug = slug
if brand is not None:
self.brand = brand
if ticker is not None:
self.ticker = ticker
if style_id is not None:
self.style_id = style_id
if model is not None:
self.model = model
if name is not None:
self.name = name
if title is not None:
self.title = title
if size_locale is not None:
self.size_locale = size_locale
if size_title is not None:
self.size_title = size_title
if size_descriptor is not None:
self.size_descriptor = size_descriptor
if size_all_descriptor is not None:
self.size_all_descriptor = size_all_descriptor
if gender is not None:
self.gender = gender
if condition is not None:
self.condition = condition
if minimum_bid is not None:
self.minimum_bid = minimum_bid
if uniq_bids is not None:
self.uniq_bids = uniq_bids
if primary_category is not None:
self.primary_category = primary_category
if secondary_category is not None:
self.secondary_category = secondary_category
@property
def product_category(self):
"""Gets the product_category of this ProductInfoProductAttributes. # noqa: E501
:return: The product_category of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._product_category
@product_category.setter
def product_category(self, product_category):
"""Sets the product_category of this ProductInfoProductAttributes.
:param product_category: The product_category of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._product_category = product_category
@property
def url_key(self):
"""Gets the url_key of this ProductInfoProductAttributes. # noqa: E501
:return: The url_key of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._url_key
@url_key.setter
def url_key(self, url_key):
"""Sets the url_key of this ProductInfoProductAttributes.
:param url_key: The url_key of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._url_key = url_key
@property
def slug(self):
"""Gets the slug of this ProductInfoProductAttributes. # noqa: E501
:return: The slug of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._slug
@slug.setter
def slug(self, slug):
"""Sets the slug of this ProductInfoProductAttributes.
:param slug: The slug of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._slug = slug
@property
def brand(self):
"""Gets the brand of this ProductInfoProductAttributes. # noqa: E501
:return: The brand of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._brand
@brand.setter
def brand(self, brand):
"""Sets the brand of this ProductInfoProductAttributes.
:param brand: The brand of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._brand = brand
@property
def ticker(self):
"""Gets the ticker of this ProductInfoProductAttributes. # noqa: E501
:return: The ticker of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._ticker
@ticker.setter
def ticker(self, ticker):
"""Sets the ticker of this ProductInfoProductAttributes.
:param ticker: The ticker of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._ticker = ticker
@property
def style_id(self):
"""Gets the style_id of this ProductInfoProductAttributes. # noqa: E501
:return: The style_id of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._style_id
@style_id.setter
def style_id(self, style_id):
"""Sets the style_id of this ProductInfoProductAttributes.
:param style_id: The style_id of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._style_id = style_id
@property
def model(self):
"""Gets the model of this ProductInfoProductAttributes. # noqa: E501
:return: The model of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._model
@model.setter
def model(self, model):
"""Sets the model of this ProductInfoProductAttributes.
:param model: The model of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._model = model
@property
def name(self):
"""Gets the name of this ProductInfoProductAttributes. # noqa: E501
:return: The name of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this ProductInfoProductAttributes.
:param name: The name of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._name = name
@property
def title(self):
"""Gets the title of this ProductInfoProductAttributes. # noqa: E501
:return: The title of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._title
@title.setter
def title(self, title):
"""Sets the title of this ProductInfoProductAttributes.
:param title: The title of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._title = title
@property
def size_locale(self):
"""Gets the size_locale of this ProductInfoProductAttributes. # noqa: E501
:return: The size_locale of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._size_locale
@size_locale.setter
def size_locale(self, size_locale):
"""Sets the size_locale of this ProductInfoProductAttributes.
:param size_locale: The size_locale of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._size_locale = size_locale
@property
def size_title(self):
"""Gets the size_title of this ProductInfoProductAttributes. # noqa: E501
:return: The size_title of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._size_title
@size_title.setter
def size_title(self, size_title):
"""Sets the size_title of this ProductInfoProductAttributes.
:param size_title: The size_title of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._size_title = size_title
@property
def size_descriptor(self):
"""Gets the size_descriptor of this ProductInfoProductAttributes. # noqa: E501
:return: The size_descriptor of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._size_descriptor
@size_descriptor.setter
def size_descriptor(self, size_descriptor):
"""Sets the size_descriptor of this ProductInfoProductAttributes.
:param size_descriptor: The size_descriptor of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._size_descriptor = size_descriptor
@property
def size_all_descriptor(self):
"""Gets the size_all_descriptor of this ProductInfoProductAttributes. # noqa: E501
:return: The size_all_descriptor of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._size_all_descriptor
@size_all_descriptor.setter
def size_all_descriptor(self, size_all_descriptor):
"""Sets the size_all_descriptor of this ProductInfoProductAttributes.
:param size_all_descriptor: The size_all_descriptor of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._size_all_descriptor = size_all_descriptor
@property
def gender(self):
"""Gets the gender of this ProductInfoProductAttributes. # noqa: E501
:return: The gender of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._gender
@gender.setter
def gender(self, gender):
"""Sets the gender of this ProductInfoProductAttributes.
:param gender: The gender of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._gender = gender
@property
def condition(self):
"""Gets the condition of this ProductInfoProductAttributes. # noqa: E501
:return: The condition of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._condition
@condition.setter
def condition(self, condition):
"""Sets the condition of this ProductInfoProductAttributes.
:param condition: The condition of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._condition = condition
@property
def minimum_bid(self):
"""Gets the minimum_bid of this ProductInfoProductAttributes. # noqa: E501
:return: The minimum_bid of this ProductInfoProductAttributes. # noqa: E501
:rtype: int
"""
return self._minimum_bid
@minimum_bid.setter
def minimum_bid(self, minimum_bid):
"""Sets the minimum_bid of this ProductInfoProductAttributes.
:param minimum_bid: The minimum_bid of this ProductInfoProductAttributes. # noqa: E501
:type: int
"""
self._minimum_bid = minimum_bid
@property
def uniq_bids(self):
"""Gets the uniq_bids of this ProductInfoProductAttributes. # noqa: E501
:return: The uniq_bids of this ProductInfoProductAttributes. # noqa: E501
:rtype: bool
"""
return self._uniq_bids
@uniq_bids.setter
def uniq_bids(self, uniq_bids):
"""Sets the uniq_bids of this ProductInfoProductAttributes.
:param uniq_bids: The uniq_bids of this ProductInfoProductAttributes. # noqa: E501
:type: bool
"""
self._uniq_bids = uniq_bids
@property
def primary_category(self):
"""Gets the primary_category of this ProductInfoProductAttributes. # noqa: E501
:return: The primary_category of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._primary_category
@primary_category.setter
def primary_category(self, primary_category):
"""Sets the primary_category of this ProductInfoProductAttributes.
:param primary_category: The primary_category of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._primary_category = primary_category
@property
def secondary_category(self):
"""Gets the secondary_category of this ProductInfoProductAttributes. # noqa: E501
:return: The secondary_category of this ProductInfoProductAttributes. # noqa: E501
:rtype: str
"""
return self._secondary_category
@secondary_category.setter
def secondary_category(self, secondary_category):
"""Sets the secondary_category of this ProductInfoProductAttributes.
:param secondary_category: The secondary_category of this ProductInfoProductAttributes. # noqa: E501
:type: str
"""
self._secondary_category = secondary_category
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ProductInfoProductAttributes):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 580
| 27.908621
| 354
|
/sdk/python/lib/io_stockx/models/product_info_product_attributes.py
| 0.600167
| 0.588835
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
from __future__ import print_function
import time
import io_stockx
from example_constants import ExampleConstants
from io_stockx.rest import ApiException
from pprint import pprint
# Configure API key authorization: api_key
configuration = io_stockx.Configuration()
configuration.host = "https://gateway.stockx.com/stage"
configuration.api_key['x-api-key'] = ExampleConstants.AWS_API_KEY
# create an instance of the API class
stockx = io_stockx.StockXApi(io_stockx.ApiClient(configuration))
login = io_stockx.LoginRequest(email=ExampleConstants.STOCKX_USERNAME, password=ExampleConstants.STOCKX_PASSWORD)
try:
# Attempts to log the user in with a username and password.
api_response = stockx.login_with_http_info(login)
# Get the customer object after login
customer = api_response[0]
# Get the login's assigned jwt token
jwt_token = api_response[2]['Jwt-Authorization']
# Use the jwt token to authenticate future requests
stockx.api_client.set_default_header('jwt-authorization', jwt_token)
# Search for a type of product
search_result = stockx.search('Jordan Retro Black Cat')
first_hit = search_result.hits[0]
style_id = first_hit.style_id
# Lookup the first product returned from the search
product = stockx.lookup_product(identifier=style_id, size='11')
# Get the current market data for the product (highest bid info, etc.)
attributes = product.data[0].attributes
id = product.data[0].id
uuid = attributes.product_uuid
# Get the product market data
market_data = stockx.get_product_market_data(id, sku=uuid)
# Get the lowest ask for the product and decrement it
lowest_ask = market_data.market.lowest_ask
lowest_ask += 1
# Create a portfolio item request with a higher bid
item = io_stockx.PortfolioRequestPortfolioItem()
item.amount = lowest_ask
item.sku_uuid = "bae25b67-a721-4f57-ad5a-79973c7d0a5c"
item.matched_with_date = "2018-12-12T05:00:00+0000"
item.expires_at = "2018-12-12T12:39:07+00:00"
request = io_stockx.PortfolioRequest()
request.portfolio_item = item
request.customer = customer
request.timezone = "America/Detroit"
# Submit the ask
ask_resp = stockx.new_portfolio_ask(request)
pprint(ask_resp)
except ApiException as e:
print("Exception when calling StockXApi->new_portfolio_ask: %s\n" % e)
|
Python
| 71
| 32.549297
| 113
|
/sdk/python/src/place_new_lowest_ask_example.py
| 0.72628
| 0.699832
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
from __future__ import print_function
import time
import io_stockx
from example_constants import ExampleConstants
from io_stockx.rest import ApiException
from pprint import pprint
# Configure API key authorization: api_key
configuration = io_stockx.Configuration()
configuration.host = "https://gateway.stockx.com/stage"
configuration.api_key['x-api-key'] = ExampleConstants.AWS_API_KEY
# create an instance of the API class
stockx = io_stockx.StockXApi(io_stockx.ApiClient(configuration))
login = io_stockx.LoginRequest(email=ExampleConstants.STOCKX_USERNAME, password=ExampleConstants.STOCKX_PASSWORD)
try:
# Attempts to log the user in with a username and password.
api_response = stockx.login(login)
pprint(api_response)
except ApiException as e:
print("Exception when calling StockXApi->login: %s\n" % e)
|
Python
| 23
| 35.086956
| 113
|
/sdk/python/src/login.py
| 0.781928
| 0.781928
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from io_stockx.models.search_hit_media import SearchHitMedia # noqa: F401,E501
from io_stockx.models.search_hit_searchable_traits import SearchHitSearchableTraits # noqa: F401,E501
class SearchHit(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'str',
'brand': 'str',
'thumbnail_url': 'str',
'media': 'SearchHitMedia',
'url': 'str',
'release_date': 'str',
'categories': 'list[str]',
'product_category': 'str',
'ticker_symbol': 'str',
'style_id': 'str',
'make': 'str',
'model': 'str',
'short_description': 'str',
'gender': 'str',
'colorway': 'str',
'price': 'int',
'description': 'str',
'highest_bid': 'str',
'total_dollars': 'str',
'lowest_ask': 'str',
'last_sale': 'str',
'sales_last_72': 'int',
'deadstock_sold': 'int',
'quality_bid': 'int',
'active': 'int',
'new_release': 'str',
'searchable_traits': 'SearchHitSearchableTraits',
'object_id': 'str',
'annual_high': 'str',
'annual_low': 'str',
'deadstock_range_low': 'str',
'deadstock_range_high': 'str',
'average_deadstock_price': 'str',
'change_value': 'str'
}
attribute_map = {
'name': 'name',
'brand': 'brand',
'thumbnail_url': 'thumbnail_url',
'media': 'media',
'url': 'url',
'release_date': 'release_date',
'categories': 'categories',
'product_category': 'product_category',
'ticker_symbol': 'ticker_symbol',
'style_id': 'style_id',
'make': 'make',
'model': 'model',
'short_description': 'short_description',
'gender': 'gender',
'colorway': 'colorway',
'price': 'price',
'description': 'description',
'highest_bid': 'highest_bid',
'total_dollars': 'total_dollars',
'lowest_ask': 'lowest_ask',
'last_sale': 'last_sale',
'sales_last_72': 'sales_last_72',
'deadstock_sold': 'deadstock_sold',
'quality_bid': 'quality_bid',
'active': 'active',
'new_release': 'new_release',
'searchable_traits': 'searchable_traits',
'object_id': 'objectID',
'annual_high': 'annual_high',
'annual_low': 'annual_low',
'deadstock_range_low': 'deadstock_range_low',
'deadstock_range_high': 'deadstock_range_high',
'average_deadstock_price': 'average_deadstock_price',
'change_value': 'change_value'
}
def __init__(self, name=None, brand=None, thumbnail_url=None, media=None, url=None, release_date=None, categories=None, product_category=None, ticker_symbol=None, style_id=None, make=None, model=None, short_description=None, gender=None, colorway=None, price=None, description=None, highest_bid=None, total_dollars=None, lowest_ask=None, last_sale=None, sales_last_72=None, deadstock_sold=None, quality_bid=None, active=None, new_release=None, searchable_traits=None, object_id=None, annual_high=None, annual_low=None, deadstock_range_low=None, deadstock_range_high=None, average_deadstock_price=None, change_value=None): # noqa: E501
"""SearchHit - a model defined in Swagger""" # noqa: E501
self._name = None
self._brand = None
self._thumbnail_url = None
self._media = None
self._url = None
self._release_date = None
self._categories = None
self._product_category = None
self._ticker_symbol = None
self._style_id = None
self._make = None
self._model = None
self._short_description = None
self._gender = None
self._colorway = None
self._price = None
self._description = None
self._highest_bid = None
self._total_dollars = None
self._lowest_ask = None
self._last_sale = None
self._sales_last_72 = None
self._deadstock_sold = None
self._quality_bid = None
self._active = None
self._new_release = None
self._searchable_traits = None
self._object_id = None
self._annual_high = None
self._annual_low = None
self._deadstock_range_low = None
self._deadstock_range_high = None
self._average_deadstock_price = None
self._change_value = None
self.discriminator = None
if name is not None:
self.name = name
if brand is not None:
self.brand = brand
if thumbnail_url is not None:
self.thumbnail_url = thumbnail_url
if media is not None:
self.media = media
if url is not None:
self.url = url
if release_date is not None:
self.release_date = release_date
if categories is not None:
self.categories = categories
if product_category is not None:
self.product_category = product_category
if ticker_symbol is not None:
self.ticker_symbol = ticker_symbol
if style_id is not None:
self.style_id = style_id
if make is not None:
self.make = make
if model is not None:
self.model = model
if short_description is not None:
self.short_description = short_description
if gender is not None:
self.gender = gender
if colorway is not None:
self.colorway = colorway
if price is not None:
self.price = price
if description is not None:
self.description = description
if highest_bid is not None:
self.highest_bid = highest_bid
if total_dollars is not None:
self.total_dollars = total_dollars
if lowest_ask is not None:
self.lowest_ask = lowest_ask
if last_sale is not None:
self.last_sale = last_sale
if sales_last_72 is not None:
self.sales_last_72 = sales_last_72
if deadstock_sold is not None:
self.deadstock_sold = deadstock_sold
if quality_bid is not None:
self.quality_bid = quality_bid
if active is not None:
self.active = active
if new_release is not None:
self.new_release = new_release
if searchable_traits is not None:
self.searchable_traits = searchable_traits
if object_id is not None:
self.object_id = object_id
if annual_high is not None:
self.annual_high = annual_high
if annual_low is not None:
self.annual_low = annual_low
if deadstock_range_low is not None:
self.deadstock_range_low = deadstock_range_low
if deadstock_range_high is not None:
self.deadstock_range_high = deadstock_range_high
if average_deadstock_price is not None:
self.average_deadstock_price = average_deadstock_price
if change_value is not None:
self.change_value = change_value
@property
def name(self):
"""Gets the name of this SearchHit. # noqa: E501
:return: The name of this SearchHit. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this SearchHit.
:param name: The name of this SearchHit. # noqa: E501
:type: str
"""
self._name = name
@property
def brand(self):
"""Gets the brand of this SearchHit. # noqa: E501
:return: The brand of this SearchHit. # noqa: E501
:rtype: str
"""
return self._brand
@brand.setter
def brand(self, brand):
"""Sets the brand of this SearchHit.
:param brand: The brand of this SearchHit. # noqa: E501
:type: str
"""
self._brand = brand
@property
def thumbnail_url(self):
"""Gets the thumbnail_url of this SearchHit. # noqa: E501
:return: The thumbnail_url of this SearchHit. # noqa: E501
:rtype: str
"""
return self._thumbnail_url
@thumbnail_url.setter
def thumbnail_url(self, thumbnail_url):
"""Sets the thumbnail_url of this SearchHit.
:param thumbnail_url: The thumbnail_url of this SearchHit. # noqa: E501
:type: str
"""
self._thumbnail_url = thumbnail_url
@property
def media(self):
"""Gets the media of this SearchHit. # noqa: E501
:return: The media of this SearchHit. # noqa: E501
:rtype: SearchHitMedia
"""
return self._media
@media.setter
def media(self, media):
"""Sets the media of this SearchHit.
:param media: The media of this SearchHit. # noqa: E501
:type: SearchHitMedia
"""
self._media = media
@property
def url(self):
"""Gets the url of this SearchHit. # noqa: E501
:return: The url of this SearchHit. # noqa: E501
:rtype: str
"""
return self._url
@url.setter
def url(self, url):
"""Sets the url of this SearchHit.
:param url: The url of this SearchHit. # noqa: E501
:type: str
"""
self._url = url
@property
def release_date(self):
"""Gets the release_date of this SearchHit. # noqa: E501
:return: The release_date of this SearchHit. # noqa: E501
:rtype: str
"""
return self._release_date
@release_date.setter
def release_date(self, release_date):
"""Sets the release_date of this SearchHit.
:param release_date: The release_date of this SearchHit. # noqa: E501
:type: str
"""
self._release_date = release_date
@property
def categories(self):
"""Gets the categories of this SearchHit. # noqa: E501
:return: The categories of this SearchHit. # noqa: E501
:rtype: list[str]
"""
return self._categories
@categories.setter
def categories(self, categories):
"""Sets the categories of this SearchHit.
:param categories: The categories of this SearchHit. # noqa: E501
:type: list[str]
"""
self._categories = categories
@property
def product_category(self):
"""Gets the product_category of this SearchHit. # noqa: E501
:return: The product_category of this SearchHit. # noqa: E501
:rtype: str
"""
return self._product_category
@product_category.setter
def product_category(self, product_category):
"""Sets the product_category of this SearchHit.
:param product_category: The product_category of this SearchHit. # noqa: E501
:type: str
"""
self._product_category = product_category
@property
def ticker_symbol(self):
"""Gets the ticker_symbol of this SearchHit. # noqa: E501
:return: The ticker_symbol of this SearchHit. # noqa: E501
:rtype: str
"""
return self._ticker_symbol
@ticker_symbol.setter
def ticker_symbol(self, ticker_symbol):
"""Sets the ticker_symbol of this SearchHit.
:param ticker_symbol: The ticker_symbol of this SearchHit. # noqa: E501
:type: str
"""
self._ticker_symbol = ticker_symbol
@property
def style_id(self):
"""Gets the style_id of this SearchHit. # noqa: E501
:return: The style_id of this SearchHit. # noqa: E501
:rtype: str
"""
return self._style_id
@style_id.setter
def style_id(self, style_id):
"""Sets the style_id of this SearchHit.
:param style_id: The style_id of this SearchHit. # noqa: E501
:type: str
"""
self._style_id = style_id
@property
def make(self):
"""Gets the make of this SearchHit. # noqa: E501
:return: The make of this SearchHit. # noqa: E501
:rtype: str
"""
return self._make
@make.setter
def make(self, make):
"""Sets the make of this SearchHit.
:param make: The make of this SearchHit. # noqa: E501
:type: str
"""
self._make = make
@property
def model(self):
"""Gets the model of this SearchHit. # noqa: E501
:return: The model of this SearchHit. # noqa: E501
:rtype: str
"""
return self._model
@model.setter
def model(self, model):
"""Sets the model of this SearchHit.
:param model: The model of this SearchHit. # noqa: E501
:type: str
"""
self._model = model
@property
def short_description(self):
"""Gets the short_description of this SearchHit. # noqa: E501
:return: The short_description of this SearchHit. # noqa: E501
:rtype: str
"""
return self._short_description
@short_description.setter
def short_description(self, short_description):
"""Sets the short_description of this SearchHit.
:param short_description: The short_description of this SearchHit. # noqa: E501
:type: str
"""
self._short_description = short_description
@property
def gender(self):
"""Gets the gender of this SearchHit. # noqa: E501
:return: The gender of this SearchHit. # noqa: E501
:rtype: str
"""
return self._gender
@gender.setter
def gender(self, gender):
"""Sets the gender of this SearchHit.
:param gender: The gender of this SearchHit. # noqa: E501
:type: str
"""
self._gender = gender
@property
def colorway(self):
"""Gets the colorway of this SearchHit. # noqa: E501
:return: The colorway of this SearchHit. # noqa: E501
:rtype: str
"""
return self._colorway
@colorway.setter
def colorway(self, colorway):
"""Sets the colorway of this SearchHit.
:param colorway: The colorway of this SearchHit. # noqa: E501
:type: str
"""
self._colorway = colorway
@property
def price(self):
"""Gets the price of this SearchHit. # noqa: E501
:return: The price of this SearchHit. # noqa: E501
:rtype: int
"""
return self._price
@price.setter
def price(self, price):
"""Sets the price of this SearchHit.
:param price: The price of this SearchHit. # noqa: E501
:type: int
"""
self._price = price
@property
def description(self):
"""Gets the description of this SearchHit. # noqa: E501
:return: The description of this SearchHit. # noqa: E501
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this SearchHit.
:param description: The description of this SearchHit. # noqa: E501
:type: str
"""
self._description = description
@property
def highest_bid(self):
"""Gets the highest_bid of this SearchHit. # noqa: E501
:return: The highest_bid of this SearchHit. # noqa: E501
:rtype: str
"""
return self._highest_bid
@highest_bid.setter
def highest_bid(self, highest_bid):
"""Sets the highest_bid of this SearchHit.
:param highest_bid: The highest_bid of this SearchHit. # noqa: E501
:type: str
"""
self._highest_bid = highest_bid
@property
def total_dollars(self):
"""Gets the total_dollars of this SearchHit. # noqa: E501
:return: The total_dollars of this SearchHit. # noqa: E501
:rtype: str
"""
return self._total_dollars
@total_dollars.setter
def total_dollars(self, total_dollars):
"""Sets the total_dollars of this SearchHit.
:param total_dollars: The total_dollars of this SearchHit. # noqa: E501
:type: str
"""
self._total_dollars = total_dollars
@property
def lowest_ask(self):
"""Gets the lowest_ask of this SearchHit. # noqa: E501
:return: The lowest_ask of this SearchHit. # noqa: E501
:rtype: str
"""
return self._lowest_ask
@lowest_ask.setter
def lowest_ask(self, lowest_ask):
"""Sets the lowest_ask of this SearchHit.
:param lowest_ask: The lowest_ask of this SearchHit. # noqa: E501
:type: str
"""
self._lowest_ask = lowest_ask
@property
def last_sale(self):
"""Gets the last_sale of this SearchHit. # noqa: E501
:return: The last_sale of this SearchHit. # noqa: E501
:rtype: str
"""
return self._last_sale
@last_sale.setter
def last_sale(self, last_sale):
"""Sets the last_sale of this SearchHit.
:param last_sale: The last_sale of this SearchHit. # noqa: E501
:type: str
"""
self._last_sale = last_sale
@property
def sales_last_72(self):
"""Gets the sales_last_72 of this SearchHit. # noqa: E501
:return: The sales_last_72 of this SearchHit. # noqa: E501
:rtype: int
"""
return self._sales_last_72
@sales_last_72.setter
def sales_last_72(self, sales_last_72):
"""Sets the sales_last_72 of this SearchHit.
:param sales_last_72: The sales_last_72 of this SearchHit. # noqa: E501
:type: int
"""
self._sales_last_72 = sales_last_72
@property
def deadstock_sold(self):
"""Gets the deadstock_sold of this SearchHit. # noqa: E501
:return: The deadstock_sold of this SearchHit. # noqa: E501
:rtype: int
"""
return self._deadstock_sold
@deadstock_sold.setter
def deadstock_sold(self, deadstock_sold):
"""Sets the deadstock_sold of this SearchHit.
:param deadstock_sold: The deadstock_sold of this SearchHit. # noqa: E501
:type: int
"""
self._deadstock_sold = deadstock_sold
@property
def quality_bid(self):
"""Gets the quality_bid of this SearchHit. # noqa: E501
:return: The quality_bid of this SearchHit. # noqa: E501
:rtype: int
"""
return self._quality_bid
@quality_bid.setter
def quality_bid(self, quality_bid):
"""Sets the quality_bid of this SearchHit.
:param quality_bid: The quality_bid of this SearchHit. # noqa: E501
:type: int
"""
self._quality_bid = quality_bid
@property
def active(self):
"""Gets the active of this SearchHit. # noqa: E501
:return: The active of this SearchHit. # noqa: E501
:rtype: int
"""
return self._active
@active.setter
def active(self, active):
"""Sets the active of this SearchHit.
:param active: The active of this SearchHit. # noqa: E501
:type: int
"""
self._active = active
@property
def new_release(self):
"""Gets the new_release of this SearchHit. # noqa: E501
:return: The new_release of this SearchHit. # noqa: E501
:rtype: str
"""
return self._new_release
@new_release.setter
def new_release(self, new_release):
"""Sets the new_release of this SearchHit.
:param new_release: The new_release of this SearchHit. # noqa: E501
:type: str
"""
self._new_release = new_release
@property
def searchable_traits(self):
"""Gets the searchable_traits of this SearchHit. # noqa: E501
:return: The searchable_traits of this SearchHit. # noqa: E501
:rtype: SearchHitSearchableTraits
"""
return self._searchable_traits
@searchable_traits.setter
def searchable_traits(self, searchable_traits):
"""Sets the searchable_traits of this SearchHit.
:param searchable_traits: The searchable_traits of this SearchHit. # noqa: E501
:type: SearchHitSearchableTraits
"""
self._searchable_traits = searchable_traits
@property
def object_id(self):
"""Gets the object_id of this SearchHit. # noqa: E501
:return: The object_id of this SearchHit. # noqa: E501
:rtype: str
"""
return self._object_id
@object_id.setter
def object_id(self, object_id):
"""Sets the object_id of this SearchHit.
:param object_id: The object_id of this SearchHit. # noqa: E501
:type: str
"""
self._object_id = object_id
@property
def annual_high(self):
"""Gets the annual_high of this SearchHit. # noqa: E501
:return: The annual_high of this SearchHit. # noqa: E501
:rtype: str
"""
return self._annual_high
@annual_high.setter
def annual_high(self, annual_high):
"""Sets the annual_high of this SearchHit.
:param annual_high: The annual_high of this SearchHit. # noqa: E501
:type: str
"""
self._annual_high = annual_high
@property
def annual_low(self):
"""Gets the annual_low of this SearchHit. # noqa: E501
:return: The annual_low of this SearchHit. # noqa: E501
:rtype: str
"""
return self._annual_low
@annual_low.setter
def annual_low(self, annual_low):
"""Sets the annual_low of this SearchHit.
:param annual_low: The annual_low of this SearchHit. # noqa: E501
:type: str
"""
self._annual_low = annual_low
@property
def deadstock_range_low(self):
"""Gets the deadstock_range_low of this SearchHit. # noqa: E501
:return: The deadstock_range_low of this SearchHit. # noqa: E501
:rtype: str
"""
return self._deadstock_range_low
@deadstock_range_low.setter
def deadstock_range_low(self, deadstock_range_low):
"""Sets the deadstock_range_low of this SearchHit.
:param deadstock_range_low: The deadstock_range_low of this SearchHit. # noqa: E501
:type: str
"""
self._deadstock_range_low = deadstock_range_low
@property
def deadstock_range_high(self):
"""Gets the deadstock_range_high of this SearchHit. # noqa: E501
:return: The deadstock_range_high of this SearchHit. # noqa: E501
:rtype: str
"""
return self._deadstock_range_high
@deadstock_range_high.setter
def deadstock_range_high(self, deadstock_range_high):
"""Sets the deadstock_range_high of this SearchHit.
:param deadstock_range_high: The deadstock_range_high of this SearchHit. # noqa: E501
:type: str
"""
self._deadstock_range_high = deadstock_range_high
@property
def average_deadstock_price(self):
"""Gets the average_deadstock_price of this SearchHit. # noqa: E501
:return: The average_deadstock_price of this SearchHit. # noqa: E501
:rtype: str
"""
return self._average_deadstock_price
@average_deadstock_price.setter
def average_deadstock_price(self, average_deadstock_price):
"""Sets the average_deadstock_price of this SearchHit.
:param average_deadstock_price: The average_deadstock_price of this SearchHit. # noqa: E501
:type: str
"""
self._average_deadstock_price = average_deadstock_price
@property
def change_value(self):
"""Gets the change_value of this SearchHit. # noqa: E501
:return: The change_value of this SearchHit. # noqa: E501
:rtype: str
"""
return self._change_value
@change_value.setter
def change_value(self, change_value):
"""Sets the change_value of this SearchHit.
:param change_value: The change_value of this SearchHit. # noqa: E501
:type: str
"""
self._change_value = change_value
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, SearchHit):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 973
| 26.171635
| 639
|
/sdk/python/lib/io_stockx/models/search_hit.py
| 0.573795
| 0.559536
|
stvncrn/stockx_api_ref
|
refs/heads/master
|
# coding: utf-8
"""
StockX API
PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from io_stockx.models.search_hit import SearchHit # noqa: F401,E501
class SearchResults(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'hits': 'list[SearchHit]',
'nb_hits': 'int'
}
attribute_map = {
'hits': 'hits',
'nb_hits': 'nbHits'
}
def __init__(self, hits=None, nb_hits=None): # noqa: E501
"""SearchResults - a model defined in Swagger""" # noqa: E501
self._hits = None
self._nb_hits = None
self.discriminator = None
if hits is not None:
self.hits = hits
if nb_hits is not None:
self.nb_hits = nb_hits
@property
def hits(self):
"""Gets the hits of this SearchResults. # noqa: E501
:return: The hits of this SearchResults. # noqa: E501
:rtype: list[SearchHit]
"""
return self._hits
@hits.setter
def hits(self, hits):
"""Sets the hits of this SearchResults.
:param hits: The hits of this SearchResults. # noqa: E501
:type: list[SearchHit]
"""
self._hits = hits
@property
def nb_hits(self):
"""Gets the nb_hits of this SearchResults. # noqa: E501
:return: The nb_hits of this SearchResults. # noqa: E501
:rtype: int
"""
return self._nb_hits
@nb_hits.setter
def nb_hits(self, nb_hits):
"""Sets the nb_hits of this SearchResults.
:param nb_hits: The nb_hits of this SearchResults. # noqa: E501
:type: int
"""
self._nb_hits = nb_hits
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, SearchResults):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
Python
| 140
| 25.478571
| 176
|
/sdk/python/lib/build/lib/io_stockx/models/search_results.py
| 0.543027
| 0.531427
|
joshling1919/django_polls
|
refs/heads/master
|
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import Answer, Question
def index(request):
latest_question_list = Question.objects.order_by('id')[:20]
context = {'latest_question_list': latest_question_list}
return render(request, 'survey/index.html', context)
def process(request):
print('Made it!')
return "Hi!"
|
Python
| 18
| 27
| 63
|
/mysite/survey/views.py
| 0.75
| 0.740079
|
jlamonade/splitteroni
|
refs/heads/master
|
from django.test import TestCase
from django.urls import reverse, resolve
from django.contrib.auth import get_user_model
from .views import HomePageView
# Create your tests here.
class HomepageTests(TestCase):
def setUp(self):
url = reverse('home')
self.response = self.client.get(url)
self.user = get_user_model().objects.create_user(
username='testuser',
email='testuser@email.com',
password='testpass',
)
def test_homepage_status_code(self):
self.assertEqual(self.response.status_code, 200)
def test_homepage_template(self):
self.assertTemplateUsed(self.response, 'home.html')
def test_homepage_contains_correct_html_while_logged_out(self):
self.assertContains(self.response, 'Create a new split. Log in or sign up to save your splits.')
self.assertContains(self.response, 'Sign up')
def test_homepage_contains_correct_html_while_logged_in(self):
self.client.login(email='testuser@email.com', password='testpass')
self.assertContains(self.response, 'Create a new split.')
def test_homepage_does_not_contain_incorrect_html(self):
self.assertNotContains(self.response, 'Should not contain this')
def test_homepage_url_resolves_homepageview(self):
view = resolve('/')
self.assertEqual(
view.func.__name__, HomePageView.as_view().__name__
)
|
Python
| 40
| 34.474998
| 104
|
/pages/tests.py
| 0.664321
| 0.66221
|
jlamonade/splitteroni
|
refs/heads/master
|
from django.test import TestCase, RequestFactory
from django.urls import reverse
from django.contrib.auth import get_user_model
from decimal import Decimal
from .models import Bill, Person, Item
# Create your tests here.
class SplitterTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
username='testuser',
email='testuser@email.com',
password='testpass',
)
self.bill = Bill.objects.create(
title='testbill',
tip=12.00,
tax=13.00,
owner=self.user,
)
self.person = Person.objects.create(
name='testperson',
bill=self.bill
)
self.item = Item.objects.create(
title='testitem',
price=14.00,
person=self.person,
bill=self.bill,
)
self.shared_item = Item.objects.create(
title='testshareditem',
price=15.00,
bill=self.bill,
shared=True,
)
# Testing tax percent/amount
self.bill_two = Bill.objects.create(
title='testbill2',
tip_percent=15,
tax_percent=8.875,
owner=self.user,
)
self.item_two = Item.objects.create(
title='testitem2',
price=14.00,
bill=self.bill_two,
shared=True,
)
self.bill_total = self.item.price + self.shared_item.price + self.bill.tax + self.bill.tip
self.shared_item_total = self.bill.tip + self.bill.tax + self.shared_item.price
self.bill_detail_response = self.client.get(self.bill.get_absolute_url())
self.bill_two_response = self.client.get(self.bill_two.get_absolute_url())
def test_bill_object(self):
self.assertEqual(self.bill.title, 'testbill')
self.assertEqual(self.bill.tip, 12.00)
self.assertEqual(self.bill.tax, 13.00)
self.assertEqual(self.bill.owner, self.user)
def test_bill_list_view_for_logged_in_user(self):
self.client.login(email='testuser@email.com', password='testpass')
response = self.client.get(reverse('bill-list'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'testbill'.title())
self.assertTemplateUsed(response, 'splitter/bill_list.html')
def test_bill_list_view_for_logged_out_users(self):
response = self.client.get(reverse('bill-list'))
self.assertEqual(response.status_code, 200)
def test_bill_detail_view(self):
no_response = self.client.get('/bill/12345/')
self.assertEqual(self.bill_detail_response.status_code, 200)
self.assertEqual(no_response.status_code, 404)
self.assertContains(self.bill_detail_response, 'testbill'.title())
self.assertContains(self.bill_detail_response, '12.00')
self.assertContains(self.bill_detail_response, '13.00')
self.assertContains(self.bill_detail_response, self.item.price)
self.assertContains(self.bill_detail_response, self.shared_item.price)
self.assertContains(self.bill_detail_response, self.bill_total)
self.assertTemplateUsed(self.bill_detail_response, 'splitter/bill_detail.html')
def test_person_object(self):
self.assertEqual(self.person.name, 'testperson')
self.assertEqual(self.person.bill, self.bill)
def test_person_object_in_bill_detail_view(self):
self.assertContains(self.bill_detail_response, 'testperson'.title())
def test_item_object(self):
self.assertEqual(self.item.title, 'testitem')
self.assertEqual(self.item.price, 14.00)
self.assertEqual(self.item.bill, self.bill)
self.assertEqual(self.item.person, self.person)
def test_item_object_in_bill_detail_view(self):
self.assertContains(self.bill_detail_response, 'testitem')
self.assertContains(self.bill_detail_response, 14.00)
def test_shared_item_object(self):
self.assertEqual(self.shared_item.title, 'testshareditem')
self.assertEqual(self.shared_item.price, 15.00)
self.assertEqual(self.shared_item.bill, self.bill)
def test_shared_item_object_in_bill_detail_view(self):
self.assertContains(self.bill_detail_response, 'testshareditem')
self.assertContains(self.bill_detail_response, 15.00)
def test_bill_model_methods(self):
"""Tests for Bill model methods."""
# Bill.get_order_total()
self.assertEqual(self.bill.get_order_grand_total(), self.bill_total)
# Bill.get_shared_items_total()
self.assertEqual(self.bill.get_shared_items_total(), self.shared_item.price)
def test_person_model_methods(self):
"""Tests for Person model methods."""
# Person.get_shared_items_split()
self.assertEqual(self.person.get_shared_items_split(), self.shared_item_total)
# Person.get_person_total()
self.assertEqual(self.person.get_person_total(), self.bill.get_order_grand_total())
def test_bill_calculate_tax(self):
self.assertContains(self.bill_two_response, Decimal(self.bill_two.get_tax_amount()))
self.assertContains(self.bill_two_response, self.bill_two.tax_percent)
self.bill_two.tax = 12.00
self.assertContains(self.bill_two_response, Decimal(self.bill_two.tax))
def test_bill_calculate_tip(self):
self.assertContains(self.bill_two_response, Decimal(self.bill_two.get_tip_amount()))
self.assertContains(self.bill_two_response, self.bill_two.tip_percent)
self.bill_two.tip = 12.00
self.assertContains(self.bill_two_response, Decimal(self.bill_two.tip))
def test_bill_saves_session(self):
self.client.session.create()
self.bill_three = Bill.objects.create(
title='testbill3',
session=self.client.session.session_key,
)
self.assertEqual(self.bill_three.session, self.client.session.session_key)
|
Python
| 149
| 39.328857
| 98
|
/splitter/tests.py
| 0.645306
| 0.630992
|
jlamonade/splitteroni
|
refs/heads/master
|
from django.urls import path
from .views import (
BillCreateView,
BillDetailView,
PersonCreateView,
PersonDeleteView,
BillListView,
ItemCreateView,
ItemDeleteView,
SharedItemCreateView,
BillUpdateView,
BillUpdateTaxPercentView,
BillUpdateTaxAmountView,
BillUpdateTipAmountView,
BillUpdateTipPercentView,
BillDeleteView,
)
urlpatterns = [
# Bill links
path('new/', BillCreateView.as_view(), name='bill-create'),
path('<uuid:pk>/', BillDetailView.as_view(), name='bill-detail'),
path('archive/', BillListView.as_view(), name='bill-list'),
path('<uuid:pk>/update/', BillUpdateView.as_view(), name='bill-update'),
path('<uuid:pk>/update-tax-percent/',
BillUpdateTaxPercentView.as_view(),
name='bill-update-tax-percent'),
path('<uuid:pk>/update-tax-amount/',
BillUpdateTaxAmountView.as_view(),
name='bill-update-tax-amount'),
path('<uuid:pk>/update-tip-amount/', BillUpdateTipAmountView.as_view(), name='bill-update-tip'),
path('<uuid:pk>/update-tip-percent/',
BillUpdateTipPercentView.as_view(),
name='bill-update-tip-percent'),
path('<uuid:pk>/delete/', BillDeleteView.as_view(), name='bill-delete'),
# Person links
path('<uuid:pk>/add-person/', PersonCreateView.as_view(), name='person-create'),
path('person/<uuid:pk>/delete/', PersonDeleteView.as_view(), name='person-delete'),
# Item links
path('<uuid:bill_id>/<uuid:person_id>/add-item/',
ItemCreateView.as_view(),
name='item-create'
),
path('<uuid:bill_id>/add-shared-item/',
SharedItemCreateView.as_view(),
name='shared-item-create'
),
path('item/<uuid:pk>/item-delete/', ItemDeleteView.as_view(), name='item-delete'),
]
|
Python
| 53
| 33.188679
| 100
|
/splitter/urls.py
| 0.646052
| 0.646052
|
jlamonade/splitteroni
|
refs/heads/master
|
from django.forms import forms, ModelForm
from django.utils.translation import gettext_lazy as _
from .models import Bill
class BillCreateForm(ModelForm):
class Meta:
model = Bill
fields = ('title', 'tax_percent', 'tip_percent',)
labels = {
'title': _('Name'),
}
help_texts = {
'title': _('The current date and time will be used if name field is empty.'),
'tax_percent': _('Please enter a percentage value. You can leave this blank and change it later.'),
'tip_percent': _('Please enter a percentage value. You can leave this blank and change it later.'),
}
error_messages = {
'title': {
'max_length': _("Name is too long."),
},
'tax_percent': {
'max_digits': _("Too many digits.")
},
'tip_percent': {
'max_digits': _("Too many digits.")
}
}
class BillUpdateForm(ModelForm):
class Meta:
model = Bill
fields = ('title',)
labels = {
'title': _('Name'),
}
class BillUpdateTaxPercentForm(ModelForm):
# def __init__(self, *args, **kwargs):
# initial = kwargs.get('initial', {})
# initial['tax'] = 0
# kwargs['initial'] = initial
# super(BillUpdateTaxPercentForm, self).__init__(*args, **kwargs)
class Meta:
model = Bill
fields = ('tax_percent',)
help_texts = {
'tax_percent': _('Please enter a percent(%) amount.')
}
class BillUpdateTaxAmountForm(ModelForm):
class Meta:
model = Bill
fields = ('tax',)
help_texts = {
'tax': _('Please enter a currency amount.')
}
class BillUpdateTipForm(ModelForm):
class Meta:
model = Bill
fields = ('tip',)
labels = {
'tip': _('Tip/Service Charge'),
}
help_texts = {
'tip': _('Please enter currency amount.')
}
class BillUpdateTipPercentForm(ModelForm):
class Meta:
model = Bill
fields = ('tip_percent',)
labels = {
'tip_percent': _('Tip/Service Charge Percent'),
}
help_texts = {
'tip': _('Please enter a percent(%) amount.')
}
|
Python
| 88
| 25.625
| 111
|
/splitter/forms.py
| 0.505978
| 0.505551
|
jlamonade/splitteroni
|
refs/heads/master
|
import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
from decimal import Decimal
from .utils import _check_tip_tax_then_add
# Create your models here.
class Bill(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
title = models.CharField(max_length=50, blank=True, null=True)
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True)
session = models.CharField(max_length=40, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
tip = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
tip_percent = models.DecimalField(max_digits=10, decimal_places=3, blank=True, null=True)
tax = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
tax_percent = models.DecimalField(max_digits=10, decimal_places=5, blank=True, null=True)
class Meta:
indexes = [
models.Index(fields=['id'], name='id_index'),
]
def __str__(self):
if not self.title:
return self.date_created.strftime("%m/%d/%y %I:%M%p")
else:
return self.title.title()
def get_tax_amount(self):
subtotal = self.get_order_subtotal()
if self.tax_percent:
tax_amount = (subtotal * (Decimal(self.tax_percent / 100)))
bill = Bill.objects.get(id=self.id)
bill.tax = tax_amount
bill.save()
return Decimal(tax_amount).quantize(Decimal('.01'))
elif self.tax:
return Decimal(self.tax).quantize(Decimal('.01'))
else:
return 0
def get_tip_amount(self):
subtotal = self.get_order_subtotal() + self.get_tax_amount()
if self.tip_percent:
tip_amount = (subtotal * (Decimal(self.tip_percent / 100)))
bill = Bill.objects.get(id=self.id)
bill.tip = tip_amount
bill.save()
return Decimal(tip_amount).quantize(Decimal('.01'))
elif self.tip:
return Decimal(self.tip).quantize(Decimal('.01'))
else:
return 0
def get_order_grand_total(self):
# Returns the sum of all items including tax and tip
total = _check_tip_tax_then_add(self) + self.get_order_subtotal()
return Decimal(total)
def get_order_subtotal(self):
total = 0
items = Item.objects.filter(bill=self)
for item in items:
total += Decimal(item.price)
return Decimal(total)
def get_shared_items_total(self):
# Returns sum of shared items only
total = 0
items = Item.objects.filter(shared=True, bill=self)
for item in items:
total += Decimal(item.price)
return Decimal(total)
def get_absolute_url(self):
return reverse('bill-detail', args=[self.id])
class Person(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
name = models.CharField(max_length=30)
bill = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='people')
class Meta:
verbose_name_plural = 'people'
indexes = [
models.Index(fields=['id'], name='person_id_index'),
]
def __str__(self):
return self.name.title()
def get_shared_items_split(self):
# Returns the amount every person owes inside the shared items including tax and tip
total = _check_tip_tax_then_add(self.bill)
person_count = self.bill.people.all().count()
items = self.bill.items.filter(shared=True)
for item in items:
total += Decimal(item.price)
split_amount = Decimal(total / person_count)
return Decimal(split_amount)
def get_person_total(self):
# Returns the sum of the person's items and their share of the shared items total
total = 0
items = Item.objects.filter(person=self)
for item in items:
total += Decimal(item.price)
return Decimal(total + self.get_shared_items_split()).quantize(Decimal('.01'))
def get_absolute_url(self):
return reverse('bill-detail', args=[self.bill.id])
class Item(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
title = models.CharField(max_length=50, blank=True, null=True)
price = models.DecimalField(max_digits=15, decimal_places=2)
person = models.ForeignKey(
Person,
on_delete=models.CASCADE,
related_name='items',
blank=True,
null=True
)
bill = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='items')
shared = models.BooleanField(default=False)
class Meta:
indexes = [
models.Index(fields=['id'], name='item_id_index'),
]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('bill-detail', args=[self.bill.id])
|
Python
| 154
| 32.474026
| 96
|
/splitter/models.py
| 0.612997
| 0.60388
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-09 14:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('splitter', '0004_auto_20201008_2206'),
('splitter', '0004_auto_20201009_1430'),
]
operations = [
]
|
Python
| 14
| 18.642857
| 48
|
/splitter/migrations/0005_merge_20201009_1438.py
| 0.629091
| 0.458182
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-09 16:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0006_auto_20201009_1603'),
]
operations = [
migrations.AddIndex(
model_name='item',
index=models.Index(fields=['id'], name='item_id_index'),
),
migrations.AddIndex(
model_name='person',
index=models.Index(fields=['id'], name='person_id_index'),
),
]
|
Python
| 21
| 23.666666
| 70
|
/splitter/migrations/0007_auto_20201009_1606.py
| 0.569498
| 0.509652
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-12 20:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('splitter', '0008_auto_20201011_1907'),
('splitter', '0008_auto_20201011_0301'),
]
operations = [
]
|
Python
| 14
| 18.642857
| 48
|
/splitter/migrations/0009_merge_20201012_2025.py
| 0.629091
| 0.458182
|
jlamonade/splitteroni
|
refs/heads/master
|
from django.contrib import admin
from .models import Bill, Person, Item
# Register your models here.
admin.site.register(Bill)
admin.site.register(Person)
admin.site.register(Item)
|
Python
| 7
| 25
| 38
|
/splitter/admin.py
| 0.796703
| 0.796703
|
jlamonade/splitteroni
|
refs/heads/master
|
"""
Django settings for config project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
from environs import Env
env = Env()
env.read_env()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env("DJANGO_SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DJANGO_DEBUG", default=False)
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=[])
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'django.contrib.sites',
# Third party apps
'crispy_forms',
'allauth',
'allauth.account',
'debug_toolbar',
# My apps
'users',
'pages',
'splitter',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
# # Cache settings
# CACHE_MIDDLEWARE_ALIAS = 'default'
# CACHE_MIDDLEWARE_SECONDS = 604800
# CACHE_MIDDLEWARE_KEY_PREFIX = ''
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [str(BASE_DIR.joinpath('templates'))],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': env.dj_db_url(
"DATABASE_URL", default="postgres://postgres@db/postgres")
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
# Static file settings
STATIC_URL = '/static/'
STATICFILES_DIRS = (str(BASE_DIR.joinpath('static')),)
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
AUTH_USER_MODEL = 'users.CustomUser'
# Crispy settings
CRISPY_TEMPLATE_PACK = 'bootstrap4'
# django-allauth config
LOGIN_REDIRECT_URL = 'home'
ACCOUNT_LOGOUT_REDIRECT_URL = 'home'
SITE_ID = 1
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND',
default='django.core.mail.backends.console.EmailBackend')
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False
# Email settings
DEFAULT_FROM_EMAIL = 'lamgoesbam@gmail.com'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = env("DJANGO_EMAIL_HOST_PASSWORD", default='')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# django-debug-toolbar
import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS = [ip[:-1] + "1" for ip in ips]
# Security settings
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
SECURE_HSTS_SECONDS = env.int("DJANGO_SECURE_HSTS_SECONDS", default=2592000)
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True)
SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True)
SESSION_COOKIE_SECURE = env.bool("DJANGO_SESSION_COOKIE_SECURE", default=True)
CSRF_COOKIE_SECURE = env.bool("DJANGO_CSRF_COOKIE_SECURE", default=True)
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
|
Python
| 191
| 28.020943
| 96
|
/config/settings.py
| 0.712739
| 0.70498
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-08 03:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='item',
name='title',
field=models.CharField(blank=True, max_length=50, null=True),
),
migrations.AlterField(
model_name='person',
name='name',
field=models.CharField(max_length=30),
),
]
|
Python
| 23
| 22.782608
| 73
|
/splitter/migrations/0002_auto_20201007_2310.py
| 0.559415
| 0.517367
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-16 21:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0011_bill_tip_percent'),
]
operations = [
migrations.AddField(
model_name='bill',
name='session',
field=models.CharField(blank=True, max_length=40, null=True),
),
]
|
Python
| 18
| 21.5
| 73
|
/splitter/migrations/0012_bill_session.py
| 0.590123
| 0.538272
|
jlamonade/splitteroni
|
refs/heads/master
|
from decimal import Decimal
def _check_tip_tax_then_add(self):
# Checks to see if tip or tax is null before adding them to total else it returns 0
total = 0
tip = self.get_tip_amount()
tax = self.get_tax_amount()
if tip:
total += tip
if tax:
total += tax
return Decimal(total)
|
Python
| 13
| 23.846153
| 87
|
/splitter/utils.py
| 0.622291
| 0.616099
|
jlamonade/splitteroni
|
refs/heads/master
|
from django.apps import AppConfig
class SplitterConfig(AppConfig):
name = 'splitter'
|
Python
| 5
| 17.200001
| 33
|
/splitter/apps.py
| 0.758242
| 0.758242
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-12 14:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0009_merge_20201012_2025'),
]
operations = [
migrations.AddField(
model_name='bill',
name='tax_percent',
field=models.DecimalField(blank=True, decimal_places=5, max_digits=10, null=True),
),
]
|
Python
| 18
| 23.055555
| 94
|
/splitter/migrations/0010_bill_tax_percent.py
| 0.605081
| 0.526559
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-08 02:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Bill',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('title', models.CharField(blank=True, max_length=50, null=True)),
('date_created', models.DateTimeField(auto_now_add=True)),
('tip', models.DecimalField(blank=True, decimal_places=2, max_digits=15)),
('tax', models.DecimalField(blank=True, decimal_places=2, max_digits=15)),
('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Person',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=20)),
('bill', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='people', to='splitter.bill')),
],
options={
'verbose_name_plural': 'people',
},
),
migrations.CreateModel(
name='Item',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('title', models.CharField(max_length=50)),
('price', models.DecimalField(decimal_places=2, max_digits=15)),
('shared', models.BooleanField(default=False)),
('bill', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='splitter.bill')),
('person', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='splitter.person')),
],
),
]
|
Python
| 51
| 43.313725
| 158
|
/splitter/migrations/0001_initial.py
| 0.591593
| 0.576991
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-09 16:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0005_merge_20201009_1438'),
]
operations = [
migrations.AddIndex(
model_name='bill',
index=models.Index(fields=['id'], name='id_index'),
),
]
|
Python
| 17
| 20.764706
| 63
|
/splitter/migrations/0006_auto_20201009_1603.py
| 0.589189
| 0.505405
|
jlamonade/splitteroni
|
refs/heads/master
|
from django.views.generic import CreateView, DetailView, DeleteView, ListView, UpdateView
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.http import Http404
from decimal import Decimal
from .models import Bill, Person, Item
from .forms import (BillCreateForm,
BillUpdateForm,
BillUpdateTaxPercentForm,
BillUpdateTaxAmountForm,
BillUpdateTipForm,
BillUpdateTipPercentForm)
# from .mixins import BillUpdateViewMixin
# Create your views here.
class BillCreateView(CreateView):
template_name = 'splitter/bill_create.html'
form_class = BillCreateForm
def form_valid(self, form):
if self.request.user.is_authenticated:
form.instance.owner = self.request.user
return super().form_valid(form)
else:
self.request.session.create()
form.instance.session = self.request.session.session_key
return super().form_valid(form)
class BillDetailView(DetailView):
model = Bill
template_name = 'splitter/bill_detail.html'
context_object_name = 'bill'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['people'] = Person.objects.filter(
bill=self.object.id)
context['shared_items'] = Item.objects.filter(bill=self.object.id, shared=True)
if self.object.tax_percent:
context['tax_percentage'] = Decimal(self.object.tax_percent).quantize(Decimal('0.001'))
if self.object.tip_percent:
context['tip_percentage'] = Decimal(self.object.tip_percent.quantize(Decimal('0')))
return context
def get_object(self, queryset=None):
pk = self.kwargs.get('pk')
obj = get_object_or_404(Bill, id=pk)
if self.request.user.is_authenticated and self.request.user == obj.owner:
return obj
elif self.request.session.session_key == obj.session:
return obj
else:
raise Http404
class PersonCreateView(CreateView):
model = Person
template_name = 'splitter/person_create.html'
fields = ('name',)
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['pk'])
form.instance.bill = bill
return super().form_valid(form)
class BillDeleteView(DeleteView):
model = Bill
template_name = 'splitter/bill_delete.html'
def get_success_url(self):
return reverse_lazy('bill-list')
class BillListView(ListView):
template_name = 'splitter/bill_list.html'
context_object_name = 'bills'
def get_queryset(self):
if self.request.user.is_authenticated:
qs = Bill.objects.filter(owner=self.request.user).order_by('-date_created')
elif self.request.session.session_key:
qs = Bill.objects.filter(session=self.request.session.session_key).order_by('-date_created')
else:
qs = None
return qs
class PersonDeleteView(DeleteView):
model = Person
template_name = 'splitter/person_delete.html'
def get_success_url(self):
return reverse_lazy('bill-detail', args=[self.object.bill.id])
class ItemCreateView(CreateView):
model = Item
template_name = 'splitter/item_create.html'
fields = ('title', 'price',)
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['bill_id'])
person = get_object_or_404(Person, id=self.kwargs['person_id'])
form.instance.bill = bill
form.instance.person = person
return super().form_valid(form)
class SharedItemCreateView(CreateView):
model = Item
template_name = "splitter/item_create.html"
fields = ('title', 'price',)
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['bill_id'])
form.instance.bill = bill
form.instance.shared = True
return super().form_valid(form)
class ItemDeleteView(DeleteView):
model = Item
template_name = 'splitter/item_delete.html'
def get_success_url(self):
return reverse_lazy('bill-detail', args=[self.object.bill.id])
class BillUpdateView(UpdateView):
model = Bill
template_name = 'splitter/bill_update.html'
form_class = BillUpdateForm
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['pk'])
form.instance.bill = bill
return super().form_valid(form)
class BillUpdateTaxPercentView(UpdateView):
model = Bill
form_class = BillUpdateTaxPercentForm
template_name = 'splitter/bill_update_tax_percent.html'
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['pk'])
form.instance.bill = bill
form.instance.tax = None
return super().form_valid(form)
class BillUpdateTaxAmountView(UpdateView):
model = Bill
form_class = BillUpdateTaxAmountForm
template_name = 'splitter/bill_update_tax_amount.html'
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['pk'])
form.instance.bill = bill
form.instance.tax_percent = None
return super().form_valid(form)
class BillUpdateTipAmountView(UpdateView):
model = Bill
form_class = BillUpdateTipForm
template_name = 'splitter/bill_update_tip.html'
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['pk'])
form.instance.bill = bill
form.instance.tip_percent = None
return super().form_valid(form)
class BillUpdateTipPercentView(UpdateView):
model = Bill
form_class = BillUpdateTipPercentForm
template_name = 'splitter/bill_update_tip_percent.html'
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['pk'])
form.instance.bill = bill
form.instance.tip = None
return super().form_valid(form)
|
Python
| 189
| 30.703703
| 104
|
/splitter/views.py
| 0.651202
| 0.643858
|
jlamonade/splitteroni
|
refs/heads/master
|
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse, resolve
from .forms import CustomUserCreationForm, CustomUserChangeForm
# Create your tests here.
class CustomUserTests(TestCase):
def test_create_user(self):
User = get_user_model()
user = User.objects.create(
username='test',
email='test@email.com',
password='test123',
)
self.assertEqual(user.username, 'test')
self.assertEqual(user.email, 'test@email.com')
self.assertTrue(user.is_active)
self.assertFalse(user.is_staff)
self.assertFalse(user.is_superuser)
def test_create_superuser(self):
User = get_user_model()
super_user = User.objects.create_superuser(
username='superuser',
email='superuser@email.com',
password='super123',
)
self.assertEqual(super_user.username, 'superuser')
self.assertEqual(super_user.email, 'superuser@email.com')
self.assertTrue(super_user.is_active)
self.assertTrue(super_user.is_staff)
self.assertTrue(super_user.is_superuser)
class SignupPageTests(TestCase):
username = 'testuser'
email = 'testuser@email.com'
def setUp(self):
url = reverse('account_signup')
self.response = self.client.get(url)
def test_signup_template(self):
self.assertEqual(self.response.status_code, 200)
self.assertTemplateUsed(self.response, 'account/signup.html')
self.assertContains(self.response, 'Sign up')
self.assertNotContains(self.response, 'Should not contain this')
def test_signup_form(self):
new_user = get_user_model().objects.create_user(
self.username, self.email
)
self.assertEqual(get_user_model().objects.all().count(), 1)
self.assertEqual(
get_user_model().objects.all()[0].username, 'testuser'
)
self.assertEqual(
get_user_model().objects.all()[0].email, 'testuser@email.com'
)
|
Python
| 62
| 31.951612
| 72
|
/users/tests.py
| 0.625857
| 0.622919
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-09 02:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0003_auto_20201007_2339'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='tax',
field=models.DecimalField(blank=True, decimal_places=2, default=0, max_digits=15, null=True),
),
migrations.AlterField(
model_name='bill',
name='tip',
field=models.DecimalField(blank=True, decimal_places=2, default=0, max_digits=15, null=True),
),
]
|
Python
| 23
| 26.826086
| 105
|
/splitter/migrations/0004_auto_20201008_2206.py
| 0.589063
| 0.528125
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-15 04:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0010_bill_tax_percent'),
]
operations = [
migrations.AddField(
model_name='bill',
name='tip_percent',
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True),
),
]
|
Python
| 18
| 22.888889
| 94
|
/splitter/migrations/0011_bill_tip_percent.py
| 0.602326
| 0.551163
|
jlamonade/splitteroni
|
refs/heads/master
|
# Generated by Django 3.1.2 on 2020-10-08 03:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('splitter', '0002_auto_20201007_2310'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='tax',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True),
),
migrations.AlterField(
model_name='bill',
name='tip',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True),
),
]
|
Python
| 23
| 25.869566
| 94
|
/splitter/migrations/0003_auto_20201007_2339.py
| 0.584142
| 0.524272
|
jlamonade/splitteroni
|
refs/heads/master
|
class BillUpdateViewMixin(object):
def form_valid(self, form):
bill = get_object_or_404(Bill, id=self.kwargs['pk'])
form.instance.bill = bill
return super().form_valid(form)
|
Python
| 6
| 32.833332
| 60
|
/splitter/mixins.py
| 0.643564
| 0.628713
|
sergiypotapov/Selenium2
|
refs/heads/master
|
__author__ = 'spotapov'
import unittest
import string
import random
from selenium import webdriver
class HomePageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# create a FF window
cls.driver = webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
#go to app HomePage
cls.driver.get("http://enterprise-demo.user.magentotrial.com//")
def test_full_cart(self):
# insert some goods to the cart
self.driver.get("http://enterprise-demo.user.magentotrial.com/bowery-chino-pants-545.html")
color = self.driver.find_element_by_xpath("//img[@alt='Charcoal']")
color.click()
size = self.driver.find_element_by_xpath("//*[@title='32']")
size.click()
add_to_cart = self.driver.find_element_by_class_name("add-to-cart-buttons")
add_to_cart.click()
cart = self.driver.find_element_by_css_selector("#header > div > div.skip-links > div > div > a > span.icon")
# click on cart
cart.click()
self.assertTrue("Bowery Chino Pants", self.driver.find_element_by_xpath("//*[@id='cart-sidebar']/li/div/p/a").text)
self.assertTrue("$140.00", self.driver.find_element_by_class_name("price").text)
|
Python
| 32
| 38.90625
| 123
|
/separate_tests.py
| 0.641347
| 0.63195
|
sergiypotapov/Selenium2
|
refs/heads/master
|
__author__ = 'spotapov'
import string
import random
#makes random string of 129 characters
def big_text():
text = ''
l = 0
for i in range(0,129):
text += random.choice(string.ascii_letters)
print(text)
for k in text:
l = l + 1
print(l)
big_text()
|
Python
| 18
| 15.166667
| 51
|
/text.py
| 0.582192
| 0.55137
|
sergiypotapov/Selenium2
|
refs/heads/master
|
__author__ = 'spotapov'
import unittest
import string
import random
from selenium import webdriver
class HomePageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# create a FF window
cls.driver = webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
#go to app HomePage
cls.driver.get("http://enterprise-demo.user.magentotrial.com//")
def test_search_text_field_max(self):
self.driver.get("http://enterprise-demo.user.magentotrial.com//")
# get search text box
search_field = self.driver.find_element_by_id("search")
# check that max attribute is 128
self.assertEqual("128", search_field.get_attribute("maxlength"))
def test_search_text_really_128_max(self):
self.driver.get("http://enterprise-demo.user.magentotrial.com//")
# get search text box
search_field = self.driver.find_element_by_id("search")
text = ''
for i in range(0,129):
text +=random.choice(string.ascii_letters)
search_field.send_keys(text)
entered_text = search_field.get_attribute("value")
self.assertNotEqual(text,entered_text)
def test_search_button_enabled(self):
self.driver.get("http://enterprise-demo.user.magentotrial.com//")
# get search button
search_button = self.driver.find_element_by_class_name("button")
self.assertTrue(search_button.is_enabled())
def test_account_link_is_visible(self):
self.driver.get("http://enterprise-demo.user.magentotrial.com//")
# get link ACCOUNT
account_link = self.driver.find_element_by_link_text("ACCOUNT")
self.assertTrue(account_link.is_displayed())
def test_number_of_links_with_account(self):
self.driver.get("http://enterprise-demo.user.magentotrial.com//")
# get all links which have Account text
account_links = self.driver.find_elements_by_partial_link_text("ACCO")
print(account_links)
self.assertEqual(2, len(account_links))
for i in account_links:
self.assertTrue(i.is_displayed())
def test_if_there_are_3_banners(self):
self.driver.get("http://enterprise-demo.user.magentotrial.com//")
# get promo banners
banner_list = self.driver.find_element_by_class_name("promos")
print(banner_list)
banners = banner_list.find_elements_by_tag_name("img")
self.assertEqual(3, len(banners))
def test_gift_promo(self):
self.driver.get("http://enterprise-demo.user.magentotrial.com//")
gift_promo = self.driver.find_element_by_xpath("//img[@alt='Physical & Virtual Gift Cards']")
self.assertTrue(gift_promo.is_displayed())
gift_promo.click()
# check vip promo is displayed
self.assertEqual("Gift Card", self.driver.title)
def test_shopping_cart_status(self):
self.driver.get("http://enterprise-demo.user.magentotrial.com//")
# get shopping cart
cart = self.driver.find_element_by_css_selector("div.header-minicart span.icon")
cart.click()
# get message
message = self.driver.find_element_by_css_selector("p.empty").text
self.assertEqual(message, "You have no items in your shopping cart.")
close = self.driver.find_element_by_css_selector("div.minicart-wrapper a.close.skip-link-close")
close.click()
def test_full_cart(self):
# insert some goods to the cart
self.driver.get("http://enterprise-demo.user.magentotrial.com/bowery-chino-pants-545.html")
color = self.driver.find_element_by_xpath("//img[@alt='Charcoal']")
color.click()
size = self.driver.find_element_by_xpath("//*[@title='32']")
size.click()
add_to_cart = self.driver.find_element_by_class_name("add-to-cart-buttons")
add_to_cart.click()
cart = self.driver.find_element_by_css_selector("#header > div > div.skip-links > div > div > a > span.icon")
# click on cart
cart.click()
self.assertTrue("Bowery Chino Pants", self.driver.find_element_by_xpath("//*[@id='cart-sidebar']/li/div/p/a").text)
self.assertTrue("$140.00", self.driver.find_element_by_class_name("price").text)
@classmethod
def tearDownClass(cls):
#close bro
cls.driver.quit()
if __name__ == '__main__':
unittest.main(verbosity=2)
|
Python
| 108
| 40.222221
| 123
|
/magento.py
| 0.643098
| 0.636588
|
kumarkapil/MyVision
|
refs/heads/master
|
from tqdm import tqdm
import torch
import numpy as np
from tabulate import tabulate
from ..utils import Meters
from MyVision import metrics
import os
import time
from itertools import chain
import abc
class Trainer:
def __init__(
self,
train_loader,
val_loader,
test_loader,
device,
loss,
optimizer,
model,
lr_scheduler,
accumulation_steps=1,
):
self.train_loader = train_loader
self.val_loader = val_loader
self.test_loader = test_loader
self.device = device
self.criterion = loss
self.optimizer = optimizer
self.model = model
self.lr_scheduler = lr_scheduler
self.accumulation_steps = accumulation_steps
def train(self):
losses = Meters.AverageMeter("Loss", ":.4e")
self.model.train()
tl = tqdm(self.train_loader)
for batch_idx, (images, targets) in enumerate(tl, 1):
self.optimizer.zero_grad()
images = images.to(self.device)
targets = targets.to(self.device)
outputs = self.model(images)
loss = self.criterion(outputs, targets)
loss.backward()
if batch_idx % self.accumulation_steps == 0:
self.optimizer.step()
losses.update(val=loss.item(), n=images.size(0))
return losses.avg
def validate(self):
losses = Meters.AverageMeter("Loss", ":.4e")
self.model.eval()
predictions = []
gts = []
vl = tqdm(self.val_loader)
for batch_idx, (images, targets) in enumerate(vl, 1):
images = images.to(self.device)
targets = targets.to(self.device)
outputs = self.model(images)
loss = self.criterion(outputs, targets)
predictions = chain(predictions, outputs.detach().cpu().numpy())
gts = chain(gts, targets.detach().cpu().numpy())
losses.update(val=loss.item(), n=images.size(0))
return np.array(list(predictions)), np.array(list(gts)), losses.avg
def fit(self, epochs, metric):
best_loss = 1
table_list = []
for epoch in range(epochs):
train_loss = self.train()
preds, gts, valid_loss = self.validate()
if valid_loss < best_loss:
if not os.path.exists("models"):
os.mkdir("models")
print("[SAVING].....")
torch.save(
self.model.state_dict(), f"models\\best_model-({epoch}).pth.tar"
)
if len(np.unique(preds)) > 2:
multiclass_metrics = ["accuracy"]
preds = [np.argmax(p) for p in preds]
score = metrics.ClassificationMetrics()(
metric, y_true=gts, y_pred=preds, y_proba=None
)
else:
binary_metrics = ["auc", "f1", "recall", "precision"]
preds = [1 if p >= 0.5 else 0 for p in preds]
score = metrics.ClassificationMetrics()(
metric, y_true=gts, y_pred=preds, y_proba=None
)
table_list.append((epoch, train_loss, valid_loss, score))
print(
tabulate(
table_list,
headers=("Epoch", "Train loss", "Validation loss", metric),
)
)
if self.lr_scheduler:
self.lr_scheduler.step(score)
|
Python
| 137
| 25.007299
| 84
|
/MyVision/engine/Engine.py
| 0.524277
| 0.520067
|
kumarkapil/MyVision
|
refs/heads/master
|
import torch
from torch.utils.data import Dataset
from PIL import Image, ImageFile
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import albumentations as A
import torchvision.transforms as transforms
import operator
ImageFile.LOAD_TRUNCATED_IMAGES = True
class DatasetUtils:
"""
This class contains utilities for making a Pytorch Dataset.
"""
def __init__(
self, train_df, image_path_column, target_column, train_tfms, valid_tfms
):
self.train_df = train_df
self.image_path_column = image_path_column
self.target_column = target_column
self.train_tfms = train_tfms
self.valid_tfms = valid_tfms
def splitter(self, valid_size=0.25):
train_images, valid_images, train_labels, valid_labels = train_test_split(
self.train_df[self.image_path_column],
self.train_df[self.target_column],
test_size=valid_size,
random_state=42,
)
return (
train_images.values,
train_labels.values,
valid_images.values,
valid_labels.values,
)
def make_dataset(
self, resize, train_idx=None, val_idx=None, valid_size=0.25, is_CV=None
):
if is_CV:
train_dataset = CVDataset(
train_df,
train_idx,
self.image_path_column,
self.target_column,
transform=self.train_tfms,
resize=resize,
)
valid_dataset = CVDataset(
train_df,
val_idx,
self.image_path_column,
self.target_column,
transform=self.valid_tfms,
resize=resize,
)
else:
(
train_image_paths,
train_labels,
valid_image_paths,
valid_labels,
) = self.splitter(valid_size=valid_size)
train_dataset = SimpleDataset(
train_image_paths, train_labels, transform=self.train_tfms
)
valid_dataset = SimpleDataset(
valid_image_paths, valid_labels, transform=self.valid_tfms
)
return train_dataset, valid_dataset
class SimpleDataset(Dataset):
def __init__(self, image_paths, targets, transform=None, resize=224):
self.image_paths = image_paths
self.targets = targets
self.default_tfms = transforms.Compose(
[
transforms.Resize((resize, resize)),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
),
]
)
self.transform = transform
def __getitem__(self, index: int):
image = Image.open(self.image_paths[index])
target = self.targets[index]
if self.transform:
image = self.transform(image)
image = self.default_tfms(image)
target = torch.tensor(target)
return image, target
def __len__(self):
return len(self.image_paths)
class CVDataset(Dataset):
def __init__(
self,
df: pd.DataFrame,
indices: np.ndarray,
image_paths,
target_cols,
transform=None,
resize=224,
):
self.df = df
self.indices = indices
self.transform = transform
self.default_tfms = transforms.Compose(
[
transforms.Resize((resize, resize)),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
),
]
)
self.image_paths = image_paths
self.target_cols = target_cols
def __getitem__(self, idx: int):
image_ids = operator.itemgetter(*self.indices)(self.df[[self.image_paths]])
labels = operator.itemgetter(*self.indices)(self.df[[self.target_cols]])
image = Image.open(image_ids[idx])
label = torch.tensor(labels[idx])
if self.transform:
image = self.transform(image)
image = self.default_tfms(image)
return image, label
def __len__(self):
return len(self.indices)
|
Python
| 158
| 26.810127
| 83
|
/MyVision/dataset/Dataset.py
| 0.544606
| 0.530496
|
kumarkapil/MyVision
|
refs/heads/master
|
import pandas as pd
def make_multiclass_labels(df, label_column, start_from):
"""
Takes in a pandas dataframe, the label column & a start index.
makes the categorical labels into integers
You can specify which index to start labelling from 0 or 1.
returns a dictionary mapping the label to it's integer value.
:param df: pd.Dataframe
:param label_column: str
:param start_from: int(0 or 1)
:return: Dict
"""
label_dict = {}
for k, v in enumerate(df[label_column].unique(), start=start_from):
label_dict[v] = k
return label_dict
|
Python
| 21
| 27.238094
| 71
|
/MyVision/utils/LabelUtils.py
| 0.666105
| 0.659359
|
kamalbec2005/PyVocabi
|
refs/heads/master
|
'''
Project: To build vocabulary.
'''
|
Python
| 3
| 11.666667
| 29
|
/main.py
| 0.631579
| 0.631579
|
tia-cima/reverse_shell_it
|
refs/heads/main
|
import socket, sys, time
def comandi(s):
while(True):
try:
print('''
Digita un qualsiasi comando.
Per uscire dal server e dal progrmma premi "ctrl + c"
''')
com = input("\n--> ")
s.send(com.encode())
dati = s.recv(1048000)
print(str(dati, "utf-8"))
continue
except KeyboardInterrupt:
print("uscita dal server in corso...")
s.close()
time.sleep(4)
sys.exit(0)
except UnicodeDecodeError:
print("ATTENZIONE\nil comando inserito non supporta la codifica utf-8, di conseguenza verrà ritornata la sua versione originale.")
print(dati)
def conne_server(indirizzo):
try:
s = socket.socket()
s.connect(indirizzo)
print(f"conne stabilita con il server all'indirizzo: {indirizzo}")
except socket.error as errore:
print(f"qualcosa è andato storto durnte la connesione\n{errore}")
retry = input("riprovare? Y/N: ")
if retry == "Y" or retry == "y":
conne_server(indirizzo)
else:
print("nessuna connessione stabilita. uscita..")
sys.exit(0)
comandi(s)
if __name__ == "__main__":
print("Attesa di una connessione al server...")
conne_server(("192.168.1.1", 15000)) # devi cambiare l'indirizzo ip se è differente
|
Python
| 47
| 30.042553
| 142
|
/client.py
| 0.527224
| 0.510624
|
tia-cima/reverse_shell_it
|
refs/heads/main
|
import sys, socket, subprocess, time, os
def ricevi(conn):
while(True):
richiesta = conn.recv(1048000)
cmd = richiesta.decode()
if cmd.startswith("cd "):
os.chdir(cmd)
s.send(b"$ ")
continue
risposta = subprocess.run(cmd, shell = True, capture_output = True)
data = risposta.stdout + risposta.stderr
conn.send(data)
def conne_client(indirizzo, backlog = 1):
try:
s = socket.socket()
s.bind(indirizzo)
s.listen(backlog)
print("server in ascolto")
except socket.error as errore:
print(f"frate qualcosa non va.\nforse c'è un altro server aperto \ncodice erorre: {errore}")
time.sleep(15)
sys.exit(0)
conn, indirizzo_client = s.accept()
print(f"conne stabilita con il client: {indirizzo_client}")
ricevi(conn)
conne_client(("192.168.1.1", 15000)) # devi cambiare l'indirizzo ip se è differente
|
Python
| 31
| 30.419355
| 100
|
/server.py
| 0.577954
| 0.554121
|
jasondentler/zeus-sensors
|
refs/heads/master
|
import os
import time
import math
import pygame, sys
from pygame.locals import *
import RPi.GPIO as GPIO
boardRevision = GPIO.RPI_REVISION
GPIO.setmode(GPIO.BCM) # use real GPIO numbering
GPIO.setup(17,GPIO.IN, pull_up_down=GPIO.PUD_UP)
pygame.init()
VIEW_WIDTH = 0
VIEW_HEIGHT = 0
pygame.display.set_caption('Flow')
pouring = False
lastPinState = False
pinState = 0
lastPinChange = int(time.time() * 1000)
pourStart = 0
pinChange = lastPinChange
pinDelta = 0
hertz = 0
flow = 0
litersPoured = 0
pintsPoured = 0
tweet = ''
BLACK = (0,0,0)
WHITE = (255, 255, 255)
windowSurface = pygame.display.set_mode((VIEW_WIDTH,VIEW_HEIGHT), FULLSCREEN, 32)
FONTSIZE = 48
LINEHEIGHT = 52
basicFont = pygame.font.SysFont(None, FONTSIZE)
def renderThings(lastPinChange, pinChange, pinDelta, hertz, flow, pintsPoured, pouring, pourStart, tweet, windowSurface, basicFont):
# Clear the screen
windowSurface.fill(BLACK)
# Draw LastPinChange
text = basicFont.render('Last Pin Change: '+time.strftime('%H:%M:%S', time.localtime(lastPinChange/1000)), True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,1*LINEHEIGHT))
# Draw PinChange
text = basicFont.render('Pin Change: '+time.strftime('%H:%M:%S', time.localtime(pinChange/1000)), True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,2*LINEHEIGHT))
# Draw PinDelta
text = basicFont.render('Pin Delta: '+str(pinDelta) + ' ms', True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,3*LINEHEIGHT))
# Draw hertz
text = basicFont.render('Hertz: '+str(hertz) + 'Hz', True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,4*LINEHEIGHT))
# Draw instantaneous speed
text = basicFont.render('Flow: '+str(flow) + ' L/sec', True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,5*LINEHEIGHT))
# Draw Liters Poured
text = basicFont.render('Pints Poured: '+str(pintsPoured) + ' pints', True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,6*LINEHEIGHT))
# Draw Pouring
text = basicFont.render('Pouring: '+str(pouring), True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,7*LINEHEIGHT))
# Draw Pour Start
text = basicFont.render('Last Pour Started At: '+time.strftime('%H:%M:%S', time.localtime(pourStart/1000)), True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,8*LINEHEIGHT))
# Draw Tweet
text = basicFont.render('Tweet: '+str(tweet), True, WHITE, BLACK)
textRect = text.get_rect()
windowSurface.blit(text, (40,9*LINEHEIGHT))
# Display everything
pygame.display.flip()
while True:
currentTime = int(time.time() * 1000)
if GPIO.input(17):
pinState = True
else:
pinState = False
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# If we have changed pin states low to high...
if(pinState != lastPinState and pinState == True):
if(pouring == False):
pourStart = currentTime
pouring = True
# get the current time
pinChange = currentTime
pinDelta = pinChange - lastPinChange
if (pinDelta < 1000):
# calculate the instantaneous speed
hertz = 1000.0000 / pinDelta
flow = hertz / (60 * 7.5) # L/s
litersPoured += flow * (pinDelta / 1000.0000)
pintsPoured = litersPoured * 2.11338
renderThings(lastPinChange, pinChange, pinDelta, hertz, flow, pintsPoured, pouring, pourStart, tweet, windowSurface, basicFont)
lastPinChange = pinChange
lastPinState = pinState
|
Python
| 119
| 29.226891
| 132
|
/flow.py
| 0.701862
| 0.671853
|
jasondentler/zeus-sensors
|
refs/heads/master
|
import os
import glob
import time
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
def get_devices():
devices = glob.glob(base_dir + '28*')
for device in devices:
yield device + '/w1_slave'
def read_temp_raw():
devices = get_devices()
for device in devices:
f = open(device, 'r')
lines = f.readlines()
f.close()
yield device, lines
def read_temp():
data = read_temp_raw()
for item in data:
device, lines = item
if lines[0].strip()[-3:] != 'YES':
print('Device ' + device + ' not ready')
continue;
print('Read device ' + device)
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
yield device, temp_c, temp_f
while True:
data = read_temp()
for item in data:
print(item)
time.sleep(1)
|
Python
| 42
| 20.357143
| 43
|
/therm.py
| 0.629176
| 0.601336
|
SSRomanSS/flask_blog
|
refs/heads/master
|
from blog import app, db, manager
from blog.models import *
if __name__ == '__main__':
manager.run()
|
Python
| 5
| 20.200001
| 33
|
/manage.py
| 0.622642
| 0.622642
|
SSRomanSS/flask_blog
|
refs/heads/master
|
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_babel import Babel, lazy_gettext as _l
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
login = LoginManager(app)
login.login_view = 'login'
login.login_message = _l('Please log in to access this page')
login.login_message_category = 'info'
bootstrap = Bootstrap(app)
moment = Moment(app)
babel = Babel(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@babel.localeselector
def get_locale():
return request.accept_languages.best_match(app.config['LANGUAGES'])
# from blog import routes, models, errors
from blog.models import User, Post
# Admin Panel
admin = Admin(app)
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Post, db.session))
|
Python
| 42
| 25.690475
| 71
|
/blog/__init__.py
| 0.772848
| 0.772848
|
SSRomanSS/flask_blog
|
refs/heads/master
|
"""fix create followers relationship
Revision ID: 89b140c56c4d
Revises: 7d84ff36825f
Create Date: 2021-03-30 14:57:47.528704
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '89b140c56c4d'
down_revision = '7d84ff36825f'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('followed_followers',
sa.Column('followed_id', sa.Integer(), nullable=True),
sa.Column('follower_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['follower_id'], ['users.id'], )
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('followed_followers')
# ### end Alembic commands ###
|
Python
| 33
| 25.878788
| 65
|
/migrations/versions/89b140c56c4d_fix_create_followers_relationship.py
| 0.669673
| 0.647125
|
SSRomanSS/flask_blog
|
refs/heads/master
|
from blog import app, db
from blog import routes, models, errors, set_logger
@app.shell_context_processor
def make_shell_context():
return {
'db': db,
'User': models.User,
'Post': models.Post
}
if __name__ == '__main__':
app.run(debug=True)
|
Python
| 15
| 17.733334
| 51
|
/run.py
| 0.590747
| 0.590747
|
SSRomanSS/flask_blog
|
refs/heads/master
|
"""Add two new column to User
Revision ID: 5e12ea69ab10
Revises: a89dbfef15cc
Create Date: 2021-03-29 20:46:23.445651
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5e12ea69ab10'
down_revision = 'a89dbfef15cc'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('about_me', sa.String(length=160), nullable=True))
op.add_column('users', sa.Column('last_seen', sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'last_seen')
op.drop_column('users', 'about_me')
# ### end Alembic commands ###
|
Python
| 30
| 25.366667
| 87
|
/migrations/versions/5e12ea69ab10_add_two_new_column_to_user.py
| 0.672566
| 0.620733
|
SSRomanSS/flask_blog
|
refs/heads/master
|
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request
from flask_login import current_user, login_user, logout_user, login_required
from flask_babel import _
from werkzeug.urls import url_parse
from blog import app, db
from blog.forms import LoginForm, RegisterForm, EditProfileForm, PostForm, EmptyForm
from blog.models import User, Post
@app.before_request
def before_request():
if current_user.is_authenticated:
current_user.last_seen = datetime.utcnow()
db.session.commit()
@app.route('/', methods=['GET', 'POST'])
@login_required
def index():
form = PostForm()
if form.validate_on_submit():
post = Post(body=form.post.data, author=current_user)
db.session.add(post)
db.session.commit()
flash(_('Your post is live now!'), 'info')
return redirect(url_for('index'))
page = request.args.get('page', 1, type=int)
posts = current_user.get_followed_posts().paginate(page, app.config['POST_PER_PAGE'], False)
next_url = url_for('index', page=posts.next_num) if posts.has_next else None
prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None
app.logger.info('message')
return render_template('index.html', posts=posts.items, form=form, next_url=next_url, prev_url=prev_url)
@app.route('/explore')
@login_required
def explore():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.timestamp.desc()).paginate(page, app.config['POST_PER_PAGE'], False)
next_url = url_for('index', page=posts.next_num) if posts.has_next else None
prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None
return render_template('index.html', posts=posts.items, next_url=next_url, prev_url=prev_url)
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first_or_404()
if not user or not user.check_password(form.password.data):
flash('Invalid username or password', 'error')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
flash(f'Login successful for {user.username} ({user.email})', 'success')
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('index')
return redirect(next_page)
return render_template('login.html', title='Sign In', form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
redirect(url_for('index'))
form = RegisterForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you successfully registered!', 'success')
return redirect(url_for('index'))
form = RegisterForm()
return render_template('register.html', title='Registration', form=form)
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/user/<username>')
@login_required
def user(username):
user = User.query.filter_by(username=username).first_or_404()
page = request.args.get('page', 1, type=int)
if user == current_user:
posts = user.get_followed_posts().paginate(page, app.config['POST_PER_PAGE'], False)
else:
posts = user.posts.order_by(Post.timestamp.desc()).paginate(page, app.config['POST_PER_PAGE'], False)
next_url = url_for('user', username=user.username, page=posts.next_num) if posts.has_next else None
prev_url = url_for('user', username=user.username, page=posts.prev_num) if posts.has_prev else None
form = EmptyForm()
return render_template('user.html', user=user, form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(formdata=request.form, obj=current_user)
if form.validate_on_submit():
form.populate_obj(current_user)
db.session.commit()
flash('Profile successfully updated', 'success')
return redirect(url_for('user', username=current_user.username))
return render_template('edit_profile.html', title='Edit Profile', form=form)
@app.route('/follow/<username>', methods=['POST'])
@login_required
def follow(username):
form = EmptyForm()
if form.validate_on_submit():
user = User.query.filter_by(username=username).first_or_404()
if not user:
flash(f'User {username} is not found', 'info')
return redirect(url_for('index'))
elif user == current_user:
flash('You cannot follow yourself', 'info')
return redirect(url_for('user', username=username))
else:
current_user.follow(user)
db.session.commit()
flash(f'You are following {username}!', 'success')
return redirect(url_for('user', username=username))
else:
return redirect(url_for('index'))
@app.route('/unfollow/<username>', methods=['POST'])
@login_required
def unfollow(username):
form = EmptyForm()
if form.validate_on_submit():
user = User.query.filter_by(username=username).first_or_404()
if not user:
flash(f'User {username} is not found', 'info')
return redirect(url_for('index'))
elif user == current_user:
flash('You cannot unfollow yourself', 'info')
return redirect(url_for('user', username=username))
else:
current_user.unfollow(user)
db.session.commit()
flash(f'You are unfollowing {username}!', 'info')
return redirect(url_for('user', username=username))
else:
return redirect(url_for('index'))
|
Python
| 155
| 38.451614
| 118
|
/blog/routes.py
| 0.652494
| 0.650041
|
Ren-Roros-Digital/django-admin-export-xlsx
|
refs/heads/main
|
from openpyxl import Workbook
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from datetime import datetime, date
from openpyxl.styles import Font
from unidecode import unidecode
class ExportExcelAction:
@classmethod
def generate_header(cls, admin, model, list_display):
def default_format(value):
return value.replace('_', ' ').upper()
header = []
for field_display in list_display:
is_model_field = field_display in [f.name for f in model._meta.fields]
is_admin_field = hasattr(admin, field_display)
if is_model_field:
field = model._meta.get_field(field_display)
field_name = getattr(field, 'verbose_name', field_display)
header.append(default_format(field_name))
elif is_admin_field:
field = getattr(admin, field_display)
field_name = getattr(field, 'short_description', default_format(field_display))
header.append(default_format(field_name))
else:
header.append(default_format(field_display))
return header
def style_output_file(file):
black_font = Font(color='000000', bold=True)
for cell in file["1:1"]:
cell.font = black_font
for column_cells in file.columns:
length = max(len((cell.value)) for cell in column_cells)
length += 10
file.column_dimensions[column_cells[0].column_letter].width = length
return file
def convert_data_date(value):
return value.strftime('%d.%m.%Y')
def convert_boolean_field(value):
if value:
return 'Yes'
return 'No'
def export_as_xls(self, request, queryset):
if not request.user.is_staff:
raise PermissionDenied
opts = self.model._meta
field_names = self.list_display
file_name = unidecode(opts.verbose_name)
wb = Workbook()
ws = wb.active
ws.append(ExportExcelAction.generate_header(self, self.model, field_names))
for obj in queryset:
row = []
for field in field_names:
is_admin_field = hasattr(self, field)
if is_admin_field:
value = getattr(self, field)(obj)
else:
value = getattr(obj, field)
if isinstance(value, datetime) or isinstance(value, date):
value = convert_data_date(value)
elif isinstance(value, bool):
value = convert_boolean_field(value)
row.append(str(value))
ws.append(row)
ws = style_output_file(ws)
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = f'attachment; filename={file_name}.xlsx'
wb.save(response)
return response
export_as_xls.short_description = "Export as excel"
|
Python
| 81
| 34.876545
| 109
|
/export_xlsx/actions.py
| 0.626635
| 0.622849
|
Ren-Roros-Digital/django-admin-export-xlsx
|
refs/heads/main
|
from setuptools import setup
setup(
name='django-admin-export-xlsx',
version='1.0.0',
author='Rune Hansén Steinnes',
author_email='rune.steinnes@renroros.no',
packages=['export_xlsx'],
url='http://github.com/Ren-Roros-Digital/django-admin-export-xlsx',
license='LICENSE.txt',
description='Admin action to export xlsx from list_display',
long_description=open('README.rst').read(),
install_requires=[
"Django >= 3",
"unidecode >=1.2",
"openpyxl >= 3",
],
)
|
Python
| 18
| 26.388889
| 71
|
/setup.py
| 0.610548
| 0.596349
|
furotsu/turret_game
|
refs/heads/master
|
import pygame
import sys
import math
from random import randint, choice
from constants import *
class Player(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y, screen):
super(Player, self).__init__()
self.screen = screen
self.original_image = pygame.image.load(player_img).convert_alpha() # we should rotate original image instead
self.image = self.original_image # of current to keep it quality
self.rect = self.image.get_rect().move((pos_x, pos_y))
self.charger = pygame.Surface((0, CHARGER_HEIGHT))
self.charger.fill(pygame.Color('sienna2'))
self.shot_power = 0
self.cooldown = pygame.Surface((COOLDOWN_WIDTH, 0))
self.cooldown.fill(YELLOW)
self.shot_cooldown = 0
self.current_angle = START_CANNON_ANGLE
self.motion = STOP
self.missile = None
self.already_shoot = False
self.is_charging = False
self.increase_shot_power = True
def draw(self):
self.screen.blit(self.image, self.rect)
def shoot(self):
self.already_shoot = True
self.missile = Missile(self.current_angle + 15, MISSILE_POS_X, MISSILE_POS_Y, self.shot_power,
self.screen)
def get_missile_rect(self):
if self.already_shoot:
return self.missile.rect
else:
return None
def action(self, event):
"""processing pressed button """
if event.type == pygame.QUIT:
sys.exit()
else:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.motion = UP
elif event.key == pygame.K_DOWN:
self.motion = DOWN
elif event.key == pygame.K_SPACE and not self.shot_cooldown:
self.motion = STOP
self.is_charging = True
elif event.type == pygame.KEYUP:
if event.key in [pygame.K_UP, pygame.K_DOWN]:
self.motion = STOP
elif event.key == pygame.K_SPACE and not self.shot_cooldown:
self.is_charging = False
self.shoot()
self.shot_cooldown = COOLDOWN
self.shot_power = 0
def draw_game_elements(self):
self.screen.fill(WHITE)
self.draw()
if self.is_charging:
self.draw_charger()
self.draw_trajectory()
if self.shot_cooldown:
self.draw_cooldown()
if self.already_shoot:
self.missile.draw()
def update_game_elements(self):
self.update_player(self.motion)
if self.is_charging:
self.update_charger()
elif self.already_shoot:
self.update_missile()
def update_missile(self):
self.missile.update_velocity()
self.missile.move()
def update_player(self, angle):
self.image = pygame.transform.rotate(self.original_image, self.current_angle + angle)
x, y, = self.rect.center
self.current_angle += angle
self.rect = self.image.get_rect() # make image rotate around its center
self.rect.center = (x, y) # and preventing it from moving around screen
self.update_cooldown()
def update_charger(self):
self.check_power_limits()
if self.increase_shot_power:
self.shot_power += POWER_CHARGE
else:
self.shot_power -= POWER_CHARGE
self.charger = pygame.transform.scale(self.charger, (self.shot_power, CHARGER_HEIGHT))
def update_cooldown(self):
if self.shot_cooldown != 0:
self.shot_cooldown -= 1
self.cooldown = pygame.transform.scale(self.cooldown, (COOLDOWN_WIDTH, self.shot_cooldown))
def check_power_limits(self):
if self.shot_power >= MAX_SHOT_POWER:
self.increase_shot_power = False
elif self.shot_power <= 0:
self.increase_shot_power = True
def draw_charger(self):
self.screen.blit(self.charger, (PLAYER_POS_X, PLAYER_POS_Y - 80))
def draw_cooldown(self):
self.screen.blit(self.cooldown, (PLAYER_POS_X + 80, PLAYER_POS_Y - 100))
def draw_trajectory(self):
time = 2
if self.shot_power != 0:
velocity_x = self.shot_power * math.cos((self.current_angle + 15) * math.pi / 180)
velocity_y = -self.shot_power * math.sin((self.current_angle + 15) * math.pi / 180)
while time != 20:
pos_x = int(MISSILE_POS_X + velocity_x * time)
pos_y = int(MISSILE_POS_Y + velocity_y * time - (ACCELERATION * time ** 2) / 2)
pygame.draw.circle(self.screen, RED, (pos_x, pos_y), 10)
time += 1
class Missile(pygame.sprite.Sprite):
def __init__(self, angle, pos_x, pos_y, shot_power, screen):
super(Missile, self).__init__()
self.image = pygame.image.load(missile_img).convert_alpha()
self.screen = screen
self.velocity_x = shot_power * math.cos(angle * math.pi / 180)
self.velocity_y = -shot_power * math.sin(angle * math.pi / 180)
self.rect = self.image.get_rect().move((pos_x, pos_y))
def update_velocity(self):
self.velocity_y -= ACCELERATION
def move(self):
self.rect.x += self.velocity_x
self.rect.y += self.velocity_y
def draw(self):
self.screen.blit(self.image, self.rect)
class Enemies(pygame.sprite.Sprite):
def __init__(self, screen, *groups):
super(Enemies, self).__init__()
self.image = choice([enemy1_img, enemy2_img, enemy3_img])
self.image = pygame.image.load(self.image).convert_alpha()
self.rect = self.image.get_rect().move((randint(500, 700), -20))
self.screen = screen
self.velocity_x = ENEMY_VELOCITY_X
self.velocity_y = ENEMY_VELOCITY_Y
def move(self):
self.rect.x += self.velocity_x
self.rect.y += self.velocity_y
def draw(self):
self.screen.blit(self.image, self.rect)
def check_destiny(self):
if display_height + 100 >= self.rect.y >= display_height:
self.rect.y = display_height + 1000
return True
return False
class AlienArmy:
def __init__(self, player, screen):
self.enemies = []
self.screen = screen
self.time_before_new_enemy = 3
self.player = player
self.kill_count = 0
def update_enemies(self): # move enemies and check for collide with missile
self.check_army_integrity()
for enemy in self.enemies:
enemy.move()
enemy.draw()
self.enemy_hit(self.player.get_missile_rect()) # check if enemy hit by missile and kill it if positive
def defeat(self): # check if player lost of not
for enemy in self.enemies:
if enemy.check_destiny():
return True
return False
def enemy_hit(self, missile):
if missile is None:
return
counter = 0
for enemy in self.enemies:
if missile.colliderect(enemy):
self.kill_enemy(counter)
counter += 1
def add_enemy(self):
self.enemies.append(Enemies(self.screen))
def check_army_integrity(self):
if self.time_before_new_enemy == 0:
self.add_enemy()
self.time_before_new_enemy = TIME_BETWEEN_ENEMIES
self.time_before_new_enemy -= 1
def kill_enemy(self, pos):
self.enemies.pop(pos)
self.kill_count += 1
def renew_kill_count(self):
self.kill_count = 0
|
Python
| 221
| 33.710407
| 118
|
/player.py
| 0.5775
| 0.568505
|
furotsu/turret_game
|
refs/heads/master
|
import pygame
from constants import *
class MenuButton:
"""Create a button """
def __init__(self, pos_x, pos_y, image, button_type):
self.button_type = button_type
self.image = pygame.image.load(image).convert_alpha()
self.size = self.image.get_rect().size
self.rect_pos = self.image.get_rect().move((pos_x, pos_y))
def draw(self, screen):
screen.blit(self.image, self.rect_pos)
class MainMenu:
"""manage all of the buttons in menu """
def __init__(self, screen, *buttons):
self.buttons = buttons
self.screen = screen
def draw(self):
for button in self.buttons:
self.screen.blit(button.image, button.rect_pos)
|
Python
| 27
| 25.74074
| 66
|
/menu.py
| 0.610803
| 0.610803
|
furotsu/turret_game
|
refs/heads/master
|
import pygame
from constants import *
class Terrain:
def __init__(self):
pass
|
Python
| 6
| 14.166667
| 23
|
/terrain.py
| 0.644444
| 0.644444
|
furotsu/turret_game
|
refs/heads/master
|
import pygame
from controller import *
from menu import *
from constants import *
def main():
pygame.init()
screen = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Cannon defend v0.08")
clock = pygame.time.Clock()
controller = Controller(screen, pygame.time.Clock())
while True:
controller.set_menu()
while not controller.game_started: # main menu loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
return 0
else:
controller.menu_action(event)
controller.draw_new_screen()
pygame.display.flip()
clock.tick(FPS)
controller.start_game()
if __name__ == "__main__":
main()
|
Python
| 36
| 21.916666
| 69
|
/main.py
| 0.564848
| 0.56
|
furotsu/turret_game
|
refs/heads/master
|
import pygame
from constants import *
class Death_screen:
def __init__(self, screen, *buttons):
self.main_block = pygame.Surface((display_width - 200, display_height - 100))
self.main_block.fill(pygame.Color('sienna2'))
self.screen = screen
self.buttons = buttons
def draw(self, score):
font = pygame.font.Font('freesansbold.ttf', 16)
self.draw_main_block()
self.screen.blit(font.render("Your score is: {}".format(score), True, BLACK), (80, 70))
for button in self.buttons:
button.draw(self.screen)
def draw_main_block(self):
self.screen.blit(self.main_block, (100, 50))
|
Python
| 20
| 32.549999
| 95
|
/death_screen.py
| 0.622951
| 0.596125
|
furotsu/turret_game
|
refs/heads/master
|
import pygame
import sys
import menu
import player
import leaderboard
import death_screen
import terrain
from constants import *
class Controller:
"""
Class that control all game actions
"""
def __init__(self, screen, clock):
self.screen = screen
self.clock = clock
self.game_started = False
self.quit_button = menu.MenuButton(display_width / 2 - 150, display_height / 2, quit_button_img, "quit")
self.start_button = menu.MenuButton(display_width / 2 - 150, display_height / 4, start_button_img, "start")
self.leaderboard_button = menu.MenuButton(display_width / 2 - 450, display_height / 6, leaderboard_button_img,
"leaderboard")
self.back_button = menu.MenuButton(display_width / 4, display_height - 100, back_button_img, "back")
self.menu_table = menu.MainMenu(self.screen, self.quit_button, self.start_button, self.leaderboard_button)
self.leaderboard_table = leaderboard.Leaderboard(leaderboard_storage, screen)
self.create_start_leaderboard()
self.death_screen_table = death_screen.Death_screen(screen, self.back_button)
self.game_surface = terrain.Terrain()
self.player = player.Player(PLAYER_POS_X, PLAYER_POS_Y, self.screen)
self.army = player.AlienArmy(self.player, self.screen)
def menu_action(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
for button in self.menu_table.buttons:
if button.rect_pos.collidepoint(event.pos): # trigger pressed button
self.trigger(button)
else:
pass
def back_button_action(self, event):
if event.type == pygame.MOUSEBUTTONDOWN and self.back_button.rect_pos.collidepoint(event.pos):
self.back_pressed()
def trigger(self, button):
if button.button_type == "quit":
self.quit_pressed()
elif button.button_type == "start":
self.start_pressed()
elif button.button_type == "leaderboard":
self.leaderboard_pressed()
self.show_leaderboard()
def quit_pressed(self):
sys.exit()
def start_pressed(self):
self.game_started = True # make main game loop in main.py start
def leaderboard_pressed(self):
self.leaderboard_table.closed = False
def back_pressed(self):
if not self.leaderboard_table.closed:
self.leaderboard_table.closed = True
self.leaderboard_table.renew_board()
elif self.game_started:
self.game_started = False
def show_leaderboard(self):
self.leaderboard_table.generate_text()
self.leaderboard_table.render_text()
while not self.leaderboard_table.closed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
else:
self.back_button_action(event)
self.screen.fill(WHITE)
self.leaderboard_table.draw()
self.draw_back_button()
pygame.display.flip()
self.clock.tick(FPS)
def create_start_leaderboard(self):
for key, item in computer_scores.items():
self.leaderboard_table.add_score(key, item)
def draw_back_button(self):
self.back_button.draw(self.screen)
def draw_new_screen(self):
self.screen.fill(WHITE)
self.set_menu()
def set_menu(self):
self.menu_table.draw()
def start_game(self):
self.player_name = self.get_player_name()
self.screen.fill(WHITE)
self.game_loop()
def get_player_name(self):
player_name = ""
flag = True
while flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_0:
return player_name
elif event.key == pygame.K_BACKSPACE:
player_name = player_name[:-1] # delete last element of name if backspace pressed
elif 97 <= event.key <= 122:
player_name += chr(event.key)
else:
pass
self.display_player_name(player_name)
def display_player_name(self, player_name):
font = pygame.font.Font('freesansbold.ttf', 16)
left = (display_width / 2) - 250
top = (display_height / 2) - 100
self.screen.fill(WHITE)
pygame.draw.rect(self.screen, YELLOW, (left, top, 320, 150))
self.screen.blit(font.render(player_name, True, BLACK), (left + 80, top + 70))
pygame.display.flip()
def game_over(self):
self.leaderboard_table.add_score(self.player_name, self.army.kill_count)
self.death_screen_table.draw(self.army.kill_count)
self.army.renew_kill_count()
while self.game_started:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
else:
self.back_button_action(event)
pygame.display.flip()
def check_for_pause(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.pause_game()
def pause_game(self):
while True:
self.draw_back_button()
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return
def game_loop(self):
self.player.draw()
while self.game_started:
for event in pygame.event.get():
self.player.action(event)
self.check_for_pause(event)
self.player.update_game_elements()
self.player.draw_game_elements()
self.army.update_enemies()
if self.army.defeat():
self.game_over()
pygame.display.flip()
self.clock.tick(FPS)
|
Python
| 186
| 33.026882
| 118
|
/controller.py
| 0.565808
| 0.55854
|
furotsu/turret_game
|
refs/heads/master
|
import shelve
import pygame
from constants import *
class Leaderboard:
def __init__(self, filename, screen):
self.file = shelve.open(filename)
self.closed = True
self.screen = screen
self.sorted_leaderboard = []
self.text = []
self.rendered_text = []
self.sorted_leaderboard = []
def draw(self): # draw scores one by one
counter = 0
for score in self.rendered_text:
self.screen.blit(score, (display_width / 4, 20 + counter)) # make indent between scores
counter += 20
def generate_text(self): # get scores by one and add it to a str list
self.sort_leaderboard()
for i in range(len(self.sorted_leaderboard), 0, -1):
player_name = self.sorted_leaderboard[i - 1][0]
score = self.sorted_leaderboard[i - 1][1]
self.text.append("{} |==| {}".format(player_name, score))
def render_text(self):
font = pygame.font.Font('freesansbold.ttf', 16)
for score in self.text:
self.rendered_text.append(font.render(score, True, BLACK, WHITE))
def add_score(self, player_name, score):
if player_name in self.file.keys() and score > self.file[player_name]:
self.file[player_name] = score
elif player_name not in self.file.keys():
self.file[player_name] = score
def renew_board(self):
self.text = []
self.rendered_text = []
def sort_leaderboard(self):
self.sorted_leaderboard = [(k, v) for k, v in sorted(self.file.items(), key=lambda item: item[1])]
|
Python
| 45
| 34.777779
| 106
|
/leaderboard.py
| 0.594041
| 0.58473
|
furotsu/turret_game
|
refs/heads/master
|
import os.path
display_height = 600
display_width = 1000
CHARGER_HEIGHT = 60
COOLDOWN_WIDTH = 50
PLAYER_POS_X = 50
PLAYER_POS_Y = 430
START_CANNON_ANGLE = 25
MISSILE_POS_X = 70
MISSILE_POS_Y = 470
ACCELERATION = -2
MAX_SHOT_POWER = 50
POWER_CHARGE = 5
COOLDOWN = 40
ENEMY_VELOCITY_X = 0
ENEMY_VELOCITY_Y = 4
TIME_BETWEEN_ENEMIES = 100
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 51)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
STOP = 0
UP = 1
DOWN = -1
FPS = 30
# extracting images from their folders
start_button_img = os.path.join("data", "start_button.png")
quit_button_img = os.path.join("data", "quit_button.png")
leaderboard_button_img = os.path.join("data", "leaderboard_button.png")
back_button_img = os.path.join("data", "back_button.png")
player_img = os.path.join("data", "player_image.png")
missile_img = os.path.join("data", "missile_image.png")
enemy1_img = os.path.join("data", "enemy1.png")
enemy2_img = os.path.join("data", "enemy2.png")
enemy3_img = os.path.join("data", "enemy3.png")
leaderboard_storage = os.path.join("data", "leaderboard.db")
computer_scores = dict([
("Vlad", 100000),
("Misha", 5000),
("Arthur", 2500),
("Max", 2000),
("Kirrilishche", 10)
])
|
Python
| 55
| 21.581818
| 71
|
/constants.py
| 0.658085
| 0.577635
|
BlastTNG/flight
|
refs/heads/master
|
#!/usr/bin/env /usr/bin/python
#TODO: can keep UID fixed, but should update the time
#to get time: datetime.utcnow().replace(microsecond=0).isoformat(' ')
UID_UTIME = "1\t2008-08-08 08:08:08" #for spider "sbenton" has UID 1
#UID_UTIME = "23\t2008-08-08 08:08:08" #for BLASTpol "sbenton" has UID 23
class Failure(Exception):
"""exception to use for failures in parsing and matching"""
def __init__(self, msg, linenum=0):
self.errstr = msg
self.msg="Error: %s" % msg
if linenum > 0: self.msg += " (%d)"%linenum
def __str__(self):
return self.msg
class Connector:
"""contains information about objects in the connector and congender tables"""
#file objects to write output to
connout = open('out/connector', 'w')
gconnout = open('out/congender', 'w')
def __init__(self, type, matetype, count, desc, alpha, bcd, mMate, fMate):
#need to find reference to mate
self.type = type
self.matetype = matetype
self.desc = desc
self.count = int(count)
#alpha and bcd will wither be None or a non-empty string
self.flags = {'alpha': 'N', 'bcd': 'N'}
if (alpha): self.flags['alpha'] = 'Y';
if (bcd): self.flags['bcd'] = 'Y';
#gender contains 'M' or 'F' for mating pair, 'X' used to simplify comparison
self.genders = {'M': 'X', 'F': 'X', 'X':'u'}
if mMate: self.genders['M'] = mMate.upper()
if fMate: self.genders['F'] = fMate.upper()
self.mate = None #object reference #needed
def gendersMatch(self, other):
"""ensure genders are unused or properly matched between two connectors"""
return (other.genders[self.genders['M']] in 'uM' \
and other.genders[self.genders['F']] in 'uF' \
and self.genders[other.genders['M']] in 'uM' \
and self.genders[other.genders['F']] in 'uF')
def __str__(self):
"""return a string representing the connector"""
if self.flags['alpha'] == "Y": alpha = " alpha"
else: alpha = ""
if self.flags['bcd'] == "Y": bcd = " bcd"
else: bcd = ""
if self.genders['M'] == 'X': male = ""
else: male = " M-%s" % self.genders['M']
if self.genders['F'] == 'X': female = ""
else: female = " F-%s" % self.genders['F']
return '%s -> %s %d "%s"%s%s%s%s' % (self.type, self.matetype,
self.count, self.desc, alpha, bcd, male, female)
def __eq__(self, other):
"""equality comparison"""
if hasattr(other, 'type'): return self.type == other.type
else: return self.type == other
def toInfile(self):
self.__class__.connout.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\n'%(self.type, \
self.desc, self.count, self.flags['alpha'], self.flags['bcd'], \
self.mate.type, UID_UTIME))
if self.genders['M'] != 'X':
self.__class__.gconnout.write("%s\tM\t%s\t\\N\t\\N\t\\N\t\\N\t%s\n"%\
(self.type, self.genders['M'], UID_UTIME))
if self.genders['F'] != 'X':
self.__class__.gconnout.write("%s\tF\t%s\t\\N\t\\N\t\\N\t\\N\t%s\n"%\
(self.type, self.genders['F'], UID_UTIME))
class Component:
"""contains information about objects in the component table"""
compout = open('out/component', 'w')
def __init__(self, ref, name, partOf):
#need to populate jack and line lists
self.ref = ref
self.name = name
self.partOf = partOf
self.jacks = [] #needed
self.lines = [] #needed
def __str__(self):
if self.partOf: partof = " < %s" % self.partOf
else: partof = ""
return '%s "%s"%s' % (self.ref, self.name, partof)
def __eq__(self, other):
if hasattr(other, 'ref'): return self.ref == other.ref
else: return self.ref == other
def toInfile(self):
if self.partOf is None: partOf = "\N"
else: partOf = self.partOf
self.__class__.compout.write("%s\t%s\t%s\t%s\n" % (self.ref,\
self.name, partOf, UID_UTIME))
class Cable:
"""entries for the cable table. most are implicit p2p cables"""
cabout = open('out/cable', 'w')
def __init__(self, ref, label, length):
#need to change p2p for implicit cables, populate jacks and lines lists
self.number = 0 #needed
if ref and ref[0] == "&": #try to infer number from ref
if ref[1] == "C": number = int(ref[2:])
else: number = int(ref[1:])
if number > 0:
self.number = number
self.ref = ref #internal use only
self.label = label
self.length = length and int(length) #short circuit avoids casting None
self.p2p = 'N' #is this a sensible default? #needed
self.jacks = [] #needed
self.lines = [] #needed
def __str__(self):
if self.number > 0: ref = "&C%d" % self.number
else: ref = self.ref
if self.length > 0: length = " %d" % self.length
else: length = ""
return 'CABLE %s "%s"%s' % (ref, self.label, length)
def __eq__(self, other):
if hasattr(other, 'ref'): return self.ref == other.ref
else: return self.ref == other
def toInfile(self):
if self.length is None or self.length < 0: lenstr = "\\N"
else: lenstr = self.length.str()
self.__class__.cabout.write("%s\t%s\t%s\t%s\t%s\n" % (self.number,\
self.label, self.p2p, lenstr, UID_UTIME))
class Jack:
"""contains information for jack table"""
jackout = open('out/jack', 'w')
def __init__(self, internal, ref, label, conn_str, dest_part, \
dest_jack, c_num, c_desc, c_len):
#need to populate pins list, find references to location, destination, conn
#need to set placeholder and cablemaster where appropriate
self.number = 0 #needed
#try to infer number from ref
if ref and ref[0] == "&":
if ref[1] == "J": number = int(ref[2:])
else: number = int(ref[1:])
if number > 0:
self.number = number
self.internal = internal #either None or 'IN'
self.ref = ref #internal use only (matched in LINEs)
self.label = label
self.conn_str = conn_str #contains: "conn_type/gender"
self.gender = self.conn_str[-1].upper()
self.conn = None #object reference #needed
self.dest_str = dest_part
self.dest_jack = dest_jack #only needed for indistinguishable jacks
self.location = None #object reference #needed
self.dest = None #object reference #needed
if c_desc is not None: #allows ""
self.cable = Cable(c_num, c_desc, c_len)
self.cable.p2p = 'Y'
else: self.cable = None
self.pins = [] #needed
self.mate = None #object reference #needed
self.placeholder = False #in direct connection, one of pair is placeholder
self.cablemaster = False #in cable pair, cable shared but only 1 is master
def canMate(self, other):
#check cable use and length
if (self.cable is not None and other.cable is not None):
if (self.cable.length and other.cable.length and \
self.cable.length != other.cable.length): return False
elif self.cable is not None or other.cable is not None: return False
#check that connectors match properly
if self.cable is not None: #for cables, ends must be same type or mates
if (self.conn.mate == other.conn and other.conn.mate == self.conn) or \
self.conn == other.conn: return True
else: #no cable means must be mates, and must have genders match
if self.conn.mate == other.conn and other.conn.mate == self.conn and \
self.conn.genders[self.gender] == other.gender and \
other.conn.genders[other.gender] == self.gender: return True
return False
def __str__(self):
if self.internal: internal = " IN"
else: internal = ""
if self.number > 0: ref = "&J%d" % self.number
else: ref = self.ref
if self.conn: connector = "%s/%s" % (self.conn.type, self.gender)
else: connector = self.conn_str
if self.dest:
if hasattr(self.dest, 'number') and self.dest.number > 0:
dest = "&C%d" % self.dest.number
else: dest = self.dest.ref #component or unnumbered cable
else: dest = self.dest_str
if self.mate:
if self.mate.number > 0: destjack = "&J%d" % self.mate.number
else: destjack = self.mate.ref
elif self.dest_jack: destjack = self.dest_jack
else: destjack = ""
if destjack: destination = "%s/%s" % (dest, destjack)
else: destination = dest
if self.cable:
if self.cable.number > 0: cref = " &C%d" % self.cable.number
#elif self.cable.ref: cref = " %s" % self.cable.ref #shouldn't happen
else: cref = ""
if self.cable.length: length = " %d" % self.cable.length
else: length = ""
cable = ' CABLE%s "%s"%s' % (cref, self.cable.label, length)
else: cable = ""
return 'JACK%s %s "%s" %s -> %s%s' % (internal, ref, self.label,
connector, destination, cable)
def __eq__(self, other):
if hasattr(other, 'ref'): return self.ref == other.ref
else: return self.ref == other
def toInfile(self):
if self.placeholder: return #don't write placeholders
if self.cable is not None: dest = self.cable.number #implicit cable
elif hasattr(self.dest, 'p2p'): dest = self.dest.number #explicit cable
else: dest = self.dest.ref #mates directly to component
if hasattr(self.location, 'p2p'): location = self.location.number
else: location = self.location.ref
if self.internal: internal = 'Y'
else: internal = 'N'
self.__class__.jackout.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"%(\
self.number, self.gender, internal, location, self.conn.type, dest,\
self.label, UID_UTIME))
import re
class Line:
"""contains information on the line table"""
pinRE = re.compile(r'\(((?:&J?\d{1,5})|[a-z0-9]+)[;,]((?:\s*[A-Za-z0-9]{1,3},?)*)\)')
count = 1
lineout = open('out/line', 'w')
def __init__(self, desc, pin_str):
#pin_str takes further processing, need to fill in owner (comp or cable)
self.number = self.__class__.count
self.__class__.count += 1
self.desc = desc
self.pinnums = []; #internal reference
self.jacknums = []; #internal reference
for match in self.__class__.pinRE.finditer(pin_str):
for pin in match.group(2).replace(',',' ').split():
self.jacknums.append(match.group(1))
self.pinnums.append(pin)
self.owner = None #object reference #needed
self.autogen = False #set to true for automatically generated lines #needed
#autogen lines will only connect to a single pin
def __str__(self):
old_jacknum = self.jacknums[0]
pintok = ["(%s;"%old_jacknum]
for jacknum, pinnum in zip(self.jacknums, self.pinnums):
if jacknum != old_jacknum:
pintok.append("),(%s;" % jacknum)
old_jacknum = jacknum
if pintok[-1][-1] != ';': pintok.append(',')
pintok.append(pinnum)
pintok.append(")")
return 'LINE "%s" %s' % (self.desc, "".join(pintok))
#return str((self.number, self.desc, zip(self.jacknums, self.pinnums)))
def __eq__(self, other):
"""doesn't quite test equality in this case: more like overlap"""
if self.autogen or other.autogen: return False #autogens don't count
for jackpin in zip(self.jacknums, self.pinnums):
if jackpin in zip(other.jacknums, other.pinnums): return True
return False
def toInfile(self):
if hasattr(self.owner,'p2p'): #owner is a cable, so use its number
owner = self.owner.number
else: owner = self.owner.ref #it is a component
self.__class__.lineout.write("%s\t%s\t%s\t%s\n"%(self.number,\
self.desc, owner, UID_UTIME))
class Pin:
"""info for the pin table, is inferred from lines and jacks"""
pinout = open('out/pin', 'w')
def __init__(self, number, desc, jack, bline, cline):
self.number = number #not necessarily a number; 3-digit string
self.desc = desc
#jack and lines are all object references instead of numbers
self.jack = jack #object reference
self.lines = {'box': bline, 'cable': cline}
def __eq__(self, other):
#should only be used from within a given jack
if hasattr(other, 'number'): return self.number == other.number
else: return self.number == other
def toInfile(self):
self.__class__.pinout.write("%s\t%s\t%s\t%s\t%s\tN\tN\t%s\n"%(self.number,\
self.jack.number, self.desc, self.lines['box'].number,\
self.lines['cable'].number, UID_UTIME))
|
Python
| 304
| 40.355263
| 87
|
/sedpy/sedobjects.py
| 0.597519
| 0.590999
|
BlastTNG/flight
|
refs/heads/master
|
from pylab import pi
def from_hours(angle):
return angle*pi/12.
def to_hours(angle):
return angle*12./pi
def from_degrees(angle):
return angle*pi/180.
def to_degrees(angle):
return angle*180./pi
def to_arcmin(angle):
return angle*180./pi*60.
def from_arcmin(angle):
return angle/60.*pi/180.
def to_arcsec(angle):
return angle*180./pi*3600.
def from_arcsec(angle):
return angle/3600.*pi/180.
|
Python
| 25
| 16.24
| 30
|
/stars/utilities/imports/python/angles.py
| 0.673611
| 0.594907
|
BlastTNG/flight
|
refs/heads/master
|
#! /usr/bin/env python
import os
import pylab as pl
import stars_log_parser as parser
def plot_fluxes(solution):
print "plotting flux for", solution.filename
print "solution had fit %d blobs and ignored %d blobs" \
% (solution.fluxer.num_blobs_fit, solution.fluxer.num_blobs_ignored)
print "solution had best fit exposure", solution.fluxer.best_fit_exposure, "s"
star_fluxes = map(lambda match: match.star.flux, solution.matches)
blob_fluxes = map(lambda match: match.blob.flux, solution.matches)
pl.plot(star_fluxes, blob_fluxes, 'o')
xlim = list(pl.xlim())
xlim[0] = 0
max_x = max(star_fluxes) * 1.1
xlim[1] = max_x
ylim = list(pl.ylim())
ylim[0] = 0
pl.plot([0, max_x], [0, max_x*solution.fluxer.best_fit_line], '-')
pl.xlim((xlim))
pl.ylim((ylim))
pl.xlabel("star flux (electrons / m^s / s)")
pl.ylabel("blob flux (ADU)")
last_solving_logname = parser.get_last_logname("../../output_dir/logs", "solving")
print "using", last_solving_logname
print "using last solution"
solutions = parser.get_solutions(last_solving_logname)
plot_fluxes(solutions[-1])
pl.show()
|
Python
| 32
| 34.75
| 82
|
/stars/utilities/fluxer/plot_last_fit.py
| 0.668122
| 0.659389
|
BlastTNG/flight
|
refs/heads/master
|
import os
from angles import *
def get_last_logname(logs_dirname, logtype):
for date_dirname in reversed(sorted(os.listdir(logs_dirname))):
if os.path.isdir(os.path.join(logs_dirname, date_dirname)):
for filename in reversed(sorted(os.listdir(os.path.join(logs_dirname, date_dirname)))):
if filename.endswith(logtype+".log"):
return os.path.join(logs_dirname, date_dirname, filename)
return None
class Coordinates():
def __init__(self):
self.ra = None
self.dec = None
self.az = None
self.el = None
self.roll = None
self.filled = False
def set_equatorial(self, ra, dec, roll):
self.ra = ra
self.dec = dec
self.roll = roll
self.filled = True
def set_horizontal(self, az, el, roll):
self.az = az
self.el = el
self.roll = roll
self.filled = True
def __repr__(self):
if self.filled:
s = "Coordinates\n"
if self.ra:
s += " equatorial: %s" % str(map(to_degrees, [self.ra, self.dec, self.roll]))
if self.az:
s += " horizontal: %s" % str(map(to_degrees, [self.az, self.el, self.roll]))
return s
class Attitude():
def __init__(self):
self.equatorial = Coordinates()
self.equatorial_errors = Coordinates()
self.horizontal = Coordinates()
self.horizontal_errors = Coordinates()
class ImageStats():
pass
class HorizontalInfo():
pass
class Solution:
def __init__(self):
self.fluxer = Fluxer()
self.blobs = []
self.stars = []
self.matches = []
self.image_stats = ImageStats()
self.attitude = Attitude()
self.horizontal_info = HorizontalInfo()
def add_match(self, line):
blob_id = int(line.split()[7])
star_id = int(line.split()[12])
star_fitted_x = float(line.split()[16])
star_fitted_y = float(line.split()[17])
blob = None
for solution_blob in self.blobs:
if solution_blob.id == blob_id:
blob = solution_blob
star = None
for solution_star in self.stars:
if solution_star.id == star_id:
star = solution_star
star.fitted_x = star_fitted_x
star.fitted_y = star_fitted_y
self.matches.append(Match(blob, star))
def __str__(self):
s = "solution for image " + str(self.filename)
s += " matching " + str(len(self.matches))
return s
def __repr__(self):
return str(self)
class Match:
def __init__(self, blob, star):
self.blob = blob
self.star = star
class Fluxer:
def __init__(self):
self.best_fit_line = None
self.best_fit_exposure = None
self.num_blobs_fit = None
self.num_blobs_ignored = None
class Blob:
def __init__(self, from_line=None):
if from_line != None:
self.unload_line(from_line)
def unload_line(self, line):
self.id = int(line.split()[8])
self.x = float(line.split()[10])
self.y = float(line.split()[11])
self.flux = float(line.split()[13])
saturated = line.split()[15]
self.saturated = False
if saturated in ["1"]:
self.saturated = True
def __str__(self):
s = "blob with"
for attribute in ["id", "x", "y", "flux", "saturated"]:
s += " %s %d" % (attribute, getattr(self, attribute))
return s
class Star:
def __init__(self, from_line=None):
if from_line != None:
self.unload_line(from_line)
def unload_line(self, line):
self.id = int(line.split()[6])
self.ra = from_degrees(float(line.split()[9]))
self.dec = from_degrees(float(line.split()[12]))
self.flux = float(line.split()[14])
def __str__(self):
s = "star with"
for attribute in ["id", "ra", "dec", "flux"]:
s += " %s %d" % (attribute, getattr(self, attribute))
return s
def add_line_to_fluxer(fluxer, line):
if "fluxer: found best fit line" in line:
fluxer.best_fit_line = float(line.split()[8])
if "fluxer: found best fit exposure" in line:
fluxer.best_fit_exposure = float(line.split()[8])/1000.0
if "fluxer: ignoring" in line:
fluxer.num_blobs_ignored = int(line.split()[5])
if "fluxer: fitting" in line:
fluxer.num_blobs_fit = int(line.split()[5])
def add_line_to_solution(line, solution):
if "starting to solve image" in line:
solution.filename = line.split()[7]
if "fluxer:" in line:
add_line_to_fluxer(solution.fluxer, line)
if "finder: found blob with id" in line:
solution.blobs.append(Blob(from_line=line))
if "solution: star id" in line:
solution.stars.append(Star(from_line=line))
if "solution: blob with" in line and "matches star" in line:
solution.add_match(line)
if "solution: equatorial attitude (deg)" in line:
solution.attitude.equatorial.set_equatorial(\
*map(from_degrees, map(float, line.split()[7:10])))
if "solution: equatorial errors (arcsec)" in line:
solution.attitude.equatorial_errors.set_equatorial(\
*map(from_arcsec, map(float, line.split()[7:10])))
if "solution: equatorial pointing error (arcsec)" in line:
solution.attitude.equatorial_pointing_error = from_arcsec(float(line.split()[8]))
if "solution: horizontal attitude (deg)" in line:
solution.attitude.horizontal.set_horizontal(\
*map(from_degrees, map(float, line.split()[7:10])))
if "solution: horizontal errors (arcsec)" in line:
solution.attitude.horizontal_errors.set_horizontal(\
*map(from_arcsec, map(float, line.split()[7:10])))
if "solution: equatorial iplatescale (arcsec/px)" in line:
solution.iplatescale = from_arcsec(float(line.split()[7]))
if "stats: mean" in line:
solution.image_stats.mean = float(line.split()[5])
if "stats: noise" in line:
solution.image_stats.noise = float(line.split()[5])
if "solution fitter: final pass used lat" in line:
solution.horizontal_info.lat = from_degrees(float(line.split()[9]))
solution.horizontal_info.lst = from_hours(float(line.split()[12]))
def get_solutions_from_output(output):
solutions = []
in_solution = False
for line in output:
if "starting to solve image" in line:
solutions.append(Solution())
in_solution = True
if "finished solving image" in line:
in_solution = False
if in_solution:
add_line_to_solution(line, solutions[-1])
return solutions
def get_solutions(log):
if log.endswith(".log") and "STARS is running" not in log:
output = open(log).readlines()
else:
output = log.split("\n")
return get_solutions_from_output(output)
def get_last_solution(log, imagename=None):
solutions = get_solutions(log)
if len(solutions) > 0 and solutions[-1].attitude.equatorial.filled:
if imagename == None or solutions[-1].filename == imagename:
return solutions[-1]
return None
def get_solutions_with_matches_from_dir(dirname):
solutions = []
for filename in sorted(os.listdir(dirname)):
possible_solutions = get_solutions(os.path.join(dirname, filename))
for possible_solution in possible_solutions:
if len(possible_solution.matches) > 0:
solutions.append(possible_solution)
return solutions
|
Python
| 209
| 35.555023
| 99
|
/stars/utilities/imports/python/stars_log_parsing.py
| 0.590499
| 0.582908
|
BlastTNG/flight
|
refs/heads/master
|
#!/usr/bin/python
import time
import numpy as np
from datetime import datetime
import pygetdata as gd
import soco
DEVICE_ADDRESS = "192.168.0.140"
DATAFILE = "/data/etc/mole.lnk"
sonos = soco.SoCo(DEVICE_ADDRESS)
#sonos = soco.discovery.any_soco()
df = gd.dirfile(DATAFILE, gd.RDONLY)
# find the tracks
def get_current_track_title():
return sonos.get_current_track_info()['title']
class AutoSonos:
def __init__(self, trackname, fieldname, trueval=None):
self.trackname = trackname
self.fieldname = fieldname
self.trueval = trueval
self.timeout = 0
self.lastval = 0
self.framenum = 0
self.changed = False
self.timesteady = 0
self.update()
self.track = sonos.music_library.get_tracks(search_term=self.trackname)[0]
# Checks to see if there is new data in the dirfile
# Increments a timeout when there is no new data
def has_update(self):
num = df.eof(self.fieldname)
retval = False
if (num != self.framenum):
self.timeout = 0
retval = True
else:
self.timeout += 1
self.framenum = num
return retval
# General command to be called always in the loop
# Loads data from dirfile if necessary
def update(self):
if (self.has_update()):
val = df.getdata(self.fieldname,
first_frame=0,
first_sample=self.framenum-1,
num_frames=0,
num_samples=1)[0]
if (val != self.lastval):
self.changed = True
self.timesteady = 0
else:
self.changed = False
self.timesteady += 1
self.lastval = val
# Queues the assigned song
# If the song is already playing, doesn't try to play again
# If persist=True, will play even if queue is stopped
def trigger(self, persist=True, volume=None):
if (get_current_track_title() != self.track.title) or (persist and sonos.get_current_transport_info()['current_transport_state'] != 'PLAYING'):
if (sonos.get_current_transport_info()['current_transport_state'] == 'PLAYING'): sonos.pause()
sonos.add_to_queue(self.track, 1) # add to queue indexing by 1
sonos.play_from_queue(0, True) # play from queue indexing from 0
if volume is not None:
sonos.ramp_to_volume(volume)
print("Playing " + self.track.title)
return 1
return 0
# Checks if the value in the dirfile has reached the assigned value
def truestate(self):
return self.lastval == self.trueval
# Looks at field "STATE_POTVALVE" and .truestate() == True when STATE_POTVALVE == 1
# When the .trigger() function is called, will play the requested song on the SONOS
PotvalveOpen = AutoSonos("Flagpole Sitta", "STATE_POTVALVE", 1)
PotvalveOpen2 = AutoSonos("Ooh Pot Valve Open", "STATE_POTVALVE", 1)
PotvalveYell = True
PotvavleSong = False
HWPMove = AutoSonos("You Spin Me Round", "MOVE_STAT_HWPR", 1)
Lunch = AutoSonos("Sandstorm", "TIME")
Leave = AutoSonos("End of the World as", "TIME")
while True:
song_requested = False
# Potvalve open
# Logic is in the main loop
PotvalveOpen.update() # must always be called in the loop
# If the truestate is reached and has been true for 20 second, then trigger the song
if (PotvalveOpen2.truestate() and (PotvalveOpen.timesteady >= 20) and (PotvalveYell == True)):
print("Potvalve is OPEN!")
if not song_requested:
PotvalveOpen.trigger()
song_requested = True
PotvalveYell = False
PotvavleSong = True
# If the truestate is reached and has been true for 20 second, then trigger the song
if (PotvalveOpen.truestate() and (PotvalveOpen.timesteady >= 20) and (PotvalveSong == True)):
print("Potvalve is OPEN!")
if not song_requested:
PotvalveOpen.trigger()
song_requested = True
PotvalveYell = True
PotvavleSong = False
# If the HWP move state is 1 we are in state "ready" so we are sending a move command
if (HWPMove.truestate()):
print("Half-wave plate is moving!")
if not song_requested:
HWPMove.trigger()
song_requested = True
# time to leave
Leave.update()
date = datetime.utcfromtimestamp(Leave.lastval)
if ((date.hour+13)%24 == 17) and (15 <= date.minute <= 25):
print("Time to leave!")
if not song_requested:
Leave.trigger(volume=65)
song_requested = True
# lunch
Lunch.update()
date = datetime.utcfromtimestamp(Lunch.lastval)
if ((date.hour+13)%24 == 11) and (date.minute >= 56) and (date.second >= 17) and (datetime.today().isoweekday() != 7):
print("Lunchtime!")
if not song_requested:
Lunch.trigger(volume=50)
song_requested = True
# reload the datafile if necessary
if (Lunch.timeout > 5):
df.close()
df = gd.dirfile(DATAFILE, gd.RDONLY)
print("Reloading \"" + DATAFILE + "\"")
time.sleep(1)
|
Python
| 152
| 30.657894
| 147
|
/scripts_gse/sonos_mon.py
| 0.661264
| 0.646301
|
BlastTNG/flight
|
refs/heads/master
|
#! /usr/bin/python
header_file = "./blast_config/include/command_list.h"
start = False
header_single_commands = []
for line in open(header_file, 'r'):
if line.startswith("enum singleCommand"):
start = True
if start:
if "}" in line:
break
line = line.replace("\n", '')
line = line.replace(" ", '')
line = line.replace("\t", '')
words = line.split(",")
header_single_commands.extend(words)
start = False
header_multi_commands = []
for line in open(header_file, 'r'):
if line.startswith("enum multiCommand"):
start = True
if start:
if "}" in line:
break
line = line.replace("\n", '')
line = line.replace(" ", '')
line = line.replace("\t", '')
words = line.split(",")
header_multi_commands.extend(words)
header_single_commands = [element for element in header_single_commands if not element.startswith("enum")]
header_single_commands = [element for element in header_single_commands if (element != "")]
header_multi_commands = [element for element in header_multi_commands if not element.startswith("enum")]
header_multi_commands = [element for element in header_multi_commands if (element != "")]
#print header_single_commands
#print header_multi_commands
#command_list_file = "./blast_config/command_list.c"
command_list_file = "./mcp/commanding/commands.c"
if False:
s_commands_not_in_main_list = []
start = False;
for single_command in header_single_commands:
command_found = False
for line in open(command_list_file, 'r'):
if "MultiCommand" in line:
start = True
if start:
#if "COMMAND" in line:
if "case" in line:
if single_command in line:
command_found = True
print 'I found command', single_command, 'in line: ', line
if start and ("default:" in line):
start = False
if not command_found:
s_commands_not_in_main_list.append(single_command)
#print 'single commands in MultiCommands in commands.c file:', s_commands_not_in_main_list
if True:
m_commands_not_in_main_list = []
start = False;
for multi_command in header_multi_commands:
command_found = False
for line in open(command_list_file, 'r'):
#if "COMMAND" in line:
if "SingleCommand" in line:
start = True
if start:
if "case" in line:
if multi_command in line:
command_found = True
print 'I found command', multi_command, 'in line: ', line
if start and ("default:" in line):
start = False
if not command_found:
m_commands_not_in_main_list.append(multi_command)
#print '\nmulti commands in SingleCommand in command.c file:', m_commands_not_in_main_list
|
Python
| 83
| 38.421688
| 106
|
/check_commanding.py
| 0.530868
| 0.530868
|
BlastTNG/flight
|
refs/heads/master
|
#! /usr/bin/env python
import os
import pylab
import pyfits
image_width = 1536
image_height = 1024
def convert(infilename):
infile = open(infilename, "r")
contents = infile.read()
infile.close()
flat_data = pylab.fromstring(contents, "uint16")
if len(flat_data) != image_width*image_height:
print "data has length", len(flat_data), "which does not match", image_width, "*", image_height
exit()
data = []
for j in range(image_height):
data.append(flat_data[j*image_width: (j+1)*image_width])
data = pylab.array(data)
header = pyfits.core.Header()
header.update("SIMPLE", "T")
header.update("BITPIX", 16)
header.update("EXTEND", "T")
pyfits.writeto(infilename.replace(".raw", ".fits"), data, header)
for filename in os.listdir("."):
if filename.endswith(".raw"):
print "converting", filename
convert(filename)
|
Python
| 33
| 26.575758
| 103
|
/stars/utilities/ebex_images/convert_raw_to_fits.py
| 0.636663
| 0.622393
|
BlastTNG/flight
|
refs/heads/master
|
#!/usr/bin/env /usr/bin/python
import re
from sedobjects import *
#LABEL -> MATE pins "description" [alpha] [bcd] [M-Mmate] [F-Fmate]
connRE = re.compile(r'^'
r'([A-Z0-9_]{1,16})\s+->\s+' #LABEL
r'([A-Z0-9_]{1,16})\s+' #MATE
r'(\d{1,3})\s+' #pins
r'"([^"]{1,255})"' #description
r'(?:\s*(alpha))?' #alpha
r'(?:\s*(bcd))?' #bcd
r'(?:\s+M-([mMfF]))?' #mmate
r'(?:\s+F-([mMfF]))?' #fmate
r'$')
#CMPNAME "Description of the COMPONENT" [< PARTOF]
compRE = re.compile(r'^'
r'([A-Z_][A-Z0-9_]{0,7})\s+' #CMPNAME
r'"([^"]{1,65})"' #description
r'(?:\s+<\s+([A-Z0-9_]{1,8}))?' #PARTOF
r'$')
#JACK [IN] [&]ref "label" CONN/G -> DEST[/jack] [CABLE [&C##] "[desc]" [len]]
jackRE = re.compile(r'^JACK'
'(?:\s*(IN))?\s+' #IN
r'((?:&J?\d{1,5})|[a-z0-9]+)\s+' #ref
r'"([^"]{1,32})"\s+' #label
r'([A-Z0-9_]{1,16}/[mMfF])\s+->\s+' #CONN/G
r'(&?[A-Z0-9_]{1,8})' #DEST
r'(?:/((?:&J?\d{1,5})|[a-z0-9]+))?' #/jack
r'(?:\s+CABLE' #CABLE
r'(?:\s+(&C?[0-9]{1,8}))?\s+' # &C##
r'"([^"]{0,64})"' # desc
r'(?:\s+(\d+))?' # len
r')?$')
#LINE "description" (jack;pin[,pin2,...])[,(jack;pin[,pin2,...]), ...]
lineRE = re.compile(r'^LINE\s+'
r'"([^"]{1,64})"\s+' #description
r'((?:'
r'\((?:(?:&J?\d{1,5})|[a-z0-9]+)[;,]' #jack
r'(?:\s*[A-Za-z0-9]{1,3},?)*\),?\s*' #pin
r')+)$')
#CABLE [&]C## "description" [len]
cableRE = re.compile(r'^CABLE\s+'
r'(&?C?[0-9]{1,8})\s+' #C##
r'"([^"]{1,64})"' #description
r'(?:\s+([0-9]+))?' #len
r'$')
#lookup table of regular expressions corresponding to object classes
RElookup = {Connector: connRE, Component: compRE, Jack: jackRE,
Line: lineRE, Cable: cableRE}
def parse(type, line):
"""parses the string: line into an object of class: type and returns it"""
match = RElookup[type].match(line)
if match:
return type(*match.groups())
else:
return None
if __name__ == "__main__":
print "\nCONNECTOR tests"
conn1 = ('TYPE -> MATE 10 "TYPE has 10 male pins that go with female MATE" '
'alpha bcd M-F')
conn2 = 'CONN -> CONN 0 "A connector with variable num of pins" alpha F-F'
conn3 = 'COMM -> COMM 0 "A connector with non-alphanumeric pins" F-F'
conn4 = 'TEST -> TEST 10 "A connector to test jack mating" M-F F-M'
print (conn1), '\n', parse(Connector,conn1)
print (conn2), '\n', parse(Connector, conn2)
print (conn3), '\n', parse(Connector, conn3)
test_connector = parse(Connector, conn4)
test_connector.mate = test_connector
print (conn4), '\n', test_connector
print "\nCOMPONENT tests"
comp1 = 'COMPA "COMPA is part of COMP1" < COMP1'
comp2 = 'COMP1 "COMP1 is not part of anything"'
comp3 = 'some random string that does not match' #bad declaration
print (comp1), '\n', parse(Component,comp1)
print (comp2), '\n', parse(Component,comp2)
print (comp3), '\n', parse(Component,comp3)
print "\nCABLE tests"
cab1 = 'CABLE 12345 "This cable has no length"'
cab2 = 'CABLE &C12346 "This cable is 350mm long" 350'
print (cab1), '\n', parse(Cable, cab1)
print (cab2), '\n', parse(Cable, cab2)
print "\n JACK tests"
jack1 = 'JACK 1 "connects to COMPA with no cable" CONN/M -> COMPA'
jack2 = 'JACK &J2 "now has cable" CONN2/F -> COMPB/2 CABLE &C4 "cable, len=?"'
jack3 = 'JACK j3 "now has cable" CONN2/F -> COMPB CABLE "cable, len=300" 300'
jack4 = 'JACK 4 "cable desc is blank" TEST/M -> COMP CABLE ""'
jack5 = 'JACK 5 "a possible mate for jack 4" TEST/M -> COMP CABLE "soemthing"'
print (jack1), '\n', parse(Jack, jack1)
print (jack2), '\n', parse(Jack, jack2)
print (jack3), '\n', parse(Jack, jack3)
j4 = parse(Jack, jack4)
j4.conn = test_connector
print (jack4), '\n', j4
j5 = parse(Jack, jack5)
j5.conn = test_connector
print (jack5), '\n', j5
if j5.canMate(j4): print "It CAN mate with jack 4"
else: print "It CAN NOT mate with jack 4"
print "\nLINE tests"
line1 = 'LINE "this line has one pin" (&J22,1)'
line2 = 'LINE "this one has 4 pins" (0,1),(0,2),(1,A),(1,C)'
line3 = 'LINE "shortform for above" (0;1,2),(1;A,C)'
print (line1), '\n', parse(Line, line1)
print (line2), '\n', parse(Line, line2)
print (line3), '\n', parse(Line, line3)
|
Python
| 119
| 34.941177
| 80
|
/sedpy/lineparser.py
| 0.55553
| 0.509937
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.