class Proposals(ObjectType): abstract = String() act_on_alert = Boolean() allocated_time = List(ProposalAllocatedTime) code = String() id = ID() instruments = Field(Instruments) is_p4 = Boolean() is_thesis = Boolean() max_seeing = Float() pi = Field(PI) status = String() tac_comment = List(TacComment) targets = Field(List(Target)) tech_reviews = Field(List(TechReview)) time_requests = List(RequestedTimeM) title = String() transparency = String() S_a_l_t_astronomer = Field(SALTAstronomer)
class GTrade(DjangoObjectType): """ Exposing the whole Trade object to GraphQL """ value = Float() class Meta(object): """ Meta Model for Trade """ model = Trade interfaces = (relay.Node, ) @staticmethod def resolve_value(data, _args, _context, _info): """ Returns the value of a trade (see the model) """ return data.get_value()
class Proposal(ObjectType): abstract = String() is_target_of_opportunity = Boolean() allocated_times = List(ProposalAllocatedTime) code = String() is_p4 = Boolean() is_thesis = Boolean() max_seeing = Float() principal_investigator = Field(User) principal_contact = Field(User) status = String() tac_comments = List(TacComment) targets = Field(List(Target)) tech_reviews = Field(List(TechReview)) time_requirements = List(TimeRequirement) title = String() transparency = String() liaison_salt_astronomer = Field(User) instruments = List(Instrument)
class GInvestmentBucketTrade(DjangoObjectType): """ Exposing the whole Trade object to GraphQL """ value = Float() class Meta(object): """ Meta Model for Trade """ model = TradeBucket interfaces = (relay.Node, ) @staticmethod def resolve_value(data, _info, **_args): """ Returns the value of a trade (see the model) """ return data.current_value()
class Workflow(ObjectType): """Global workflow info.""" id = ID(required=True) name = String() status = String() status_msg = String() host = String() port = Int() owner = String() tasks = List(lambda: Task, description="""Task definitions.""", args=def_args, resolver=get_nodes_by_id) families = List(lambda: Family, description="""Family definitions.""", args=def_args, resolver=get_nodes_by_id) task_proxies = List(lambda: TaskProxy, description="""Task cycle instances.""", args=proxy_args, resolver=get_nodes_by_id) family_proxies = List(lambda: FamilyProxy, description="""Family cycle instances.""", args=proxy_args, resolver=get_nodes_by_id) edges = Field(lambda: Edges, args=edge_args, description="""Graph edges""") api_version = Int() cylc_version = String() last_updated = Float() meta = Field(Meta) newest_runahead_cycle_point = String() newest_cycle_point = String() oldest_cycle_point = String() reloading = Boolean() run_mode = String() state_totals = Field(StateTotals) workflow_log_dir = String() time_zone_info = Field(TimeZone) tree_depth = Int() ns_defn_order = List(String) job_log_names = List(String) states = List(String)
class PaletLine(OdooObjectType): id = Int() product_id = Field(Product) location_id = Field(Location) lot = String() quantity = Int() kilos = Float() uom = String() @staticmethod def resolve_product_id(root, info): return root.produce_product_id @staticmethod def resolve_lot(root, info): return root.lot_id.name @staticmethod def resolve_uom(root, info): return "Cajas" if root.produce_product_id.uom_id.name == "Unidades" else root.product_uom_id.name
class ResultMedia(ObjectType): id = ID gif_format = Field(MediaTypes) url = String() dims = List(Int) duration = Float() preview = String() size = Int() @classmethod def create_from_data(cls, data): parsed_data = {} filtered_data = remove_non_implemented_fields(cls, data) for key, value in filtered_data.items(): if key == 'gif_format': parsed_data.update({key: value.lower() if isinstance(value, str) else None}) else: parsed_data.update({key: value}) return cls(**parsed_data)
def generate_type_dict(model): type_dict = {} for column in model.__table__.columns: if hasattr(model, 'private_fields') and column.name in model.private_fields: continue if column.type.python_type == int: type_dict[column.name] = Int() elif column.type.python_type == str: type_dict[column.name] = String() elif column.type.python_type == datetime.datetime: type_dict[column.name] = DateTime() elif column.type.python_type == datetime.date: type_dict[column.name] = Date() elif column.type.python_type == datetime.time: type_dict[column.name] = Time() elif column.type.python_type == bool: type_dict[column.name] = Boolean() elif column.type.python_type == decimal.Decimal: type_dict[column.name] = Float() else: raise Exception(f'Unknown column type {column.type.python_type}') return type_dict
class Job(ObjectType): class Meta: description = """Jobs.""" id = ID(required=True) submit_num = Int() state = String() # name and cycle_point for filtering/sorting name = String(required=True) cycle_point = String(required=True) task_proxy = Field(lambda: TaskProxy, description="""Associated Task Proxy""", required=True, resolver=get_node_by_id) submitted_time = String() started_time = String() finished_time = String() batch_sys_job_id = ID() batch_sys_name = String() env_script = String() err_script = String() exit_script = String() execution_time_limit = Float() host = String() init_script = String() job_log_dir = String() owner = String() post_script = String() pre_script = String() script = String() work_sub_dir = String() batch_sys_conf = List(String) environment = List(String) directives = List(String) param_env_tmpl = List(String) param_var = List(String) extra_logs = List(String) messages = List(String)
class StreamStore(ObjectType): name = String() start = DateTime() end = DateTime() current = Boolean() renditions = List(StreamRendition) playlist = String(start=DateTime(), duration=Float()) thumbnail = String(date=DateTime(), max_width=Int()) def resolve_playlist(self, info, start=None, duration=60): wseStreamingUrl, wseApplication = itemgetter( 'wseStreamingUrl', 'wseApplication')(self.metadata) store, start, end = (0, 0, 0) return urljoin(wseStreamingUrl, ( '{appplication}/{store}/playlist.m3u8?DVR&wowzadvrplayliststart={start}&wowzadvrplaylistduration={end}'.format( appplication=wseApplication, store=store, start=start, end=end) )) def resolve_thumbnail(self, date, max_width): return ''
class Palet(OdooObjectType): id = Int() name = String() code = String() partner_id = Field(Partner) destiny_partner_id = Field(Partner) total_quantity = Int() total_kilos = Float() lines = List(PaletLine) state = String() order_id = Field(SaleOrder) @staticmethod def resolve_total_quantity(root, info): return sum([line.quantity for line in root.palet_line_ids]) @staticmethod def resolve_total_kilos(root, info): return sum([line.kilos for line in root.palet_line_ids]) @staticmethod def resolve_lines(root, info): return root.palet_line_ids
class Supply(ObjectType): id = ID(required=True) is_active = Boolean(required=True) name = String(required=True) description = String(required=False) skills = List(NonNull(Skill), required=True) quantity = Int(required=True) hourly_salary = Float(required=False) company = Field(lambda: Company, required=True, resolver=company_by_id) # we only have this for now def resolve_description(root, info): if root.description_ext is None: return None return root.description_ext def resolve_skills(root, info): if root.skills is None: return [] return g.skill_loader.load_many(root.skills)
class ResultItem(ObjectType): id = ID() composite = String() created = Float() hasaudio = Boolean() item_id = String() itemurl = String() media = List(ResultMedia) shares = Int() tags = List(String) title = String() url = String() @classmethod def create_from_data(cls, data): parsed_data = {} filtered_data = remove_non_implemented_fields(cls, data) for key, value in filtered_data.items(): if key == 'media': media_items = value[0] if isinstance(value, list) else value media_list = [ ResultMedia.create_from_data(media) for media in move_gif_formats_into_media_payloads(media_items) ] parsed_data.update({key: media_list}) elif key == 'id': parsed_data.update({'item_id': media_list}) else: parsed_data.update({key: value}) return cls(**parsed_data)
def convert_field_to_float(field, registry=None): return Float(description=field.help_text, required=not field.null)
class PercentileData(ObjectType): percentile = Float() value = Float()
def convert_field_to_float(field, registry=None, input_flag=None, nested_fields=False): return Float(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
def convert_field_to_float(field, registry=None): return Float(description=field.help_text)
class DiscountQuoteType(graphene.ObjectType): id = Int() name = String() amount = Float()
def convert_field_to_float(field, registry=None): """ Converts Mongoengine fields to Graphene Float type """ return Float(**get_data_from_field(field))
class TutoringQuote(graphene.InputObjectType): category_id = ID(name='category') academic_level = AcademicLevelEnum() duration = Float() sessions = Int()
class Query(object): priceRule = Field(PriceRuleType, priceRule_id=ID()) discount = Field(DiscountType, discount_id=ID()) multiCourseDiscount = Field(MultiCourseDiscountType, multiCourseDiscount_id=ID()) dateRangeDiscount = Field(DateRangeDiscountType, dateRangeDiscount_id=ID()) paymentMethodDiscount = Field(PaymentMethodDiscountType, paymentMethodDiscount_id=ID()) priceRules = List(PriceRuleType) discounts = List(DiscountType) multiCourseDiscounts = List(MultiCourseDiscountType) dateRangeDiscounts = List(DateRangeDiscountType) paymentMethodDiscounts = List(PaymentMethodDiscountType) priceQuote = Field(PriceQuoteType, method=String(required=True), disabled_discounts=List(ID), price_adjustment=Float(), classes=List(ClassQuote), tutoring=List(TutoringQuote), parent=ID(name='parent', required=True)) def resolve_priceQuote(self, info, **kwargs): quote = price_quote_total(kwargs) return PriceQuoteType(subTotal=quote["sub_total"], priceAdjustment=quote["price_adjustment"], accountBalance=quote["account_balance"], total=quote["total"], discounts=quote["discounts"], parent=kwargs["parent"]) def resolve_priceRule(self, info, **kwargs): return PriceRule.objects.get(id=kwargs.get('priceRule_id')) def resolve_priceRules(self, info, **kwargs): return PriceRule.objects.all() def resolve_discount(self, info, **kwargs): return Discount.objects.get(id=kwargs.get('discount_id')) def resolve_discounts(self, info, **kwargs): return Discount.objects.all() def resolve_multiCourseDiscount(self, info, **kwargs): return MultiCourseDiscount.objects.get( id=kwargs.get('multiCourseDiscount_id')) def resolve_multiCourseDiscounts(self, info, **kwargs): return MultiCourseDiscount.objects.all() def resolve_dateRangeDiscount(self, info, **kwargs): return DateRangeDiscount.objects.get( id=kwargs.get('dateRangeDiscount_id')) def resolve_dateRangeDiscounts(self, info, **kwargs): return DateRangeDiscount.objects.all() def resolve_paymentMethodDiscount(self, info, **kwargs): return PaymentMethodDiscount.objects.get( id=kwargs.get('paymentMethodDiscount_id')) def resolve_paymentMethodDiscounts(self, info, **kwargs): return PaymentMethodDiscount.objects.all()
class WaitTimeStats(ObjectType): avg = Float() min = Float() median = Float() max = Float() percentiles = List(PercentileData, percentiles = List(Float, required = False), ) histogram = List(HistogramBin, min = Float(required=False, default_value=0), max = Float(required=False, default_value=90), bin_size = Float(required=False, default_value=5) ) # parent is a dict containing a "wait_stats_arr" key with a list of WaitTimeStats objects def resolve_avg(parent, info): averages = [] for wait_stats in parent['wait_stats_arr']: avg = wait_stats.get_average() if avg is not None: averages.append(avg) if len(averages) > 0: return round(np.average(averages), ROUND_DIGITS) else: return None def resolve_min(parent, info): percentiles_data = WaitTimeStats.resolve_percentiles(parent, info, [0]) return percentiles_data[0]['value'] if percentiles_data is not None else None def resolve_median(parent, info): percentiles_data = WaitTimeStats.resolve_percentiles(parent, info, [50]) return percentiles_data[0]['value'] if percentiles_data is not None else None def resolve_max(parent, info): percentiles_data = WaitTimeStats.resolve_percentiles(parent, info, [100]) return percentiles_data[0]['value'] if percentiles_data is not None else None def resolve_percentiles(parent, info, percentiles = None): percentile_values_arr = [] if percentiles is None: percentiles = range(0, 101, 5) for wait_stats in parent['wait_stats_arr']: percentile_values = wait_stats.get_percentiles(percentiles) if percentile_values is not None: percentile_values_arr.append(percentile_values) if len(percentile_values_arr) > 0: # todo: handle multiple days percentile_values = percentile_values_arr[0] return get_percentiles_data(percentiles, percentile_values) else: return None def resolve_histogram(parent, info, bin_size = 5, min = 0, max = 90): histograms = [] if bin_size < 0: bin_size = 5 bins = np.arange(min, max + bin_size, bin_size) for wait_stats in parent['wait_stats_arr']: histogram = wait_stats.get_histogram(bins) if histogram is not None: histograms.append(histogram * 100) # convert to percentages if len(histograms) > 0: # todo: handle multiple days histogram = histograms[0] nonzero_buckets = np.nonzero(histogram)[0] if len(nonzero_buckets) > 0: histogram_end_index = nonzero_buckets[-1] + 1 else: histogram_end_index = 0 histogram = histogram[0:histogram_end_index] bins = bins[0:histogram_end_index] return get_histogram_data(histogram, bins, bin_size) else: return None
class FindingType(ObjectType): # noqa pylint: disable=too-many-instance-attributes id = String() # noqa pylint: disable=invalid-name success = Boolean() error_message = String() state = String() vulnerabilities = List(Vulnerability, vuln_type=String(), state=String()) open_vulnerabilities = Int() closed_vulnerabilities = Int() project_name = String() release_date = String() records = JSONString() tracking = List(GenericScalar) severity = GenericScalar() exploit = String() evidence = GenericScalar() comments = List(GenericScalar) observations = List(GenericScalar) report_level = String() title = String() scenario = String() actor = String() description = String() requirements = String() attack_vector_desc = String() threat = String() recommendation = String() affected_systems = String() compromised_attributes = String() compromised_records = Int() cwe_url = String() bts_url = String() kb_url = String() treatment = String() treatment_manager = String() treatment_justification = String() remediated = Boolean() type = String() cvss_version = String() age = Int() last_vulnerability = Int() severity_score = Float() is_exploitable = Boolean() report_date = String() where = String() # Additional attributes of detailed findings client_code = String() client_project = String() probability = Int() detailed_severity = Int() risk = String() risk_level = String() ambit = String() category = String() def __init__(self): super(FindingType, self).__init__() self.id = '' # noqa pylint: disable=invalid-name self.vulnerabilities = [] self.success = False self.error_message = '' self.open_vulnerabilities = 0 self.closed_vulnerabilities = 0 self.project_name = '' self.release_date = '' self.records = {} self.severity = {} self.tracking = [] self.comments = [] self.observations = [] self.report_level = '' self.title = '' self.scenario = '' self.actor = '' self.description = '' self.requirements = '' self.attack_vector_desc = '' self.threat = '' self.recommendation = '' self.affected_systems = '' self.compromised_attributes = '' self.compromised_records = 0 self.cwe_url = '' self.bts_url = '' self.treatment = '' self.treatment_manager = '' self.treatment_justification = '' self.type = '' self.cvss_version = '' self.exploit = '' self.age = 0 self.last_vulnerability = 0 self.severity_score = 0.0 self.is_exploitable = False self.remediated = '' self.report_date = '' self.where = ''
class PriceInput(InputObjectType): currency = String(required=True) amount = Float(required=True)
class Priority(ObjectType): p0_andp1 = Float() p2 = Float() p3 = Float() p4 = Float()
class CreateUserInputType(InputObjectType): first_name = String(required=True) last_name = String(required=True) mass = Float(required=True) age = Int() email = String()
class HistogramBin(ObjectType): count = Float() binStart = Float() binEnd = Float()
class AddRunInputType(InputObjectType): user_id = String(required=True) time = Float(required=True) distance = Float(required=True) date = DateTime()
class BasicStats(ObjectType): count = Int() avg = Float() min = Float() median = Float() max = Float() std = Float() percentiles = List(PercentileData, percentiles = List(Float, required = False), ) histogram = List(HistogramBin, min = Float(required=False, default_value=0), max = Float(required=False), bin_size = Float(required=False, default_value=5) ) countRange = Int( min = Float(required=False), max = Float(required=False), ) values = List(Float) # parent is an array-like containing numeric values def resolve_values(values, info): return values def resolve_count(values, info): return len(values) def resolve_countRange(values, info, min=None, max=None): if min is not None and max is not None: return np.sum((values >= min) & (values < max)) elif min is not None: return np.sum(values >= min) elif max is not None: return np.sum(values < max) else: return len(values) def resolve_avg(values, info): if len(values) > 0: return round(np.average(values), ROUND_DIGITS) else: return None def resolve_std(values, info): if len(values) > 0: return round(np.std(values), ROUND_DIGITS) else: return None def resolve_min(values, info): if len(values) > 0: return round(np.min(values), ROUND_DIGITS) else: return None def resolve_median(values, info): if len(values) > 0: return round(np.median(values), ROUND_DIGITS) else: return None def resolve_max(values, info): if len(values) > 0: return round(np.max(values), ROUND_DIGITS) else: return None def resolve_percentiles(values, info, percentiles = None): if len(values) > 0: if percentiles is None: percentiles = range(0, 101, 5) percentile_values = np.percentile(values, percentiles) return get_percentiles_data(percentiles, percentile_values) else: return None def resolve_histogram(values, info, bin_size = None, min = None, max = None): if len(values) > 0: percentile_values = np.percentile(values, [0, 100]) if bin_size is None or bin_size <= 0: bin_size = 5 bin_min = min if min is not None else 0 # math.floor(percentile_values[0] / bin_size) * bin_size bin_max = max if max is not None else math.ceil(percentile_values[-1] / bin_size) * bin_size + bin_size bins = np.arange(bin_min, bin_max, bin_size) histogram, bin_edges = np.histogram(values, bins) return get_histogram_data(histogram, bins, bin_size) else: return None
class InputPaletLine(InputObjectType): move_line_id = Int() kilos = Float() quantity = Int() produce_product = Int()