uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d58e922c6dd88c06688e2dce | train | class | class EncounterStatusHistoryType(AbstractType):
__resource_type__ = "EncounterStatusHistory"
| class EncounterStatusHistoryType(AbstractType):
| __resource_type__ = "EncounterStatusHistory"
| "Encounter"
class EncounterHospitalizationType(AbstractType):
__resource_type__ = "EncounterHospitalization"
class EncounterLocationType(AbstractType):
__resource_type__ = "EncounterLocation"
class EncounterParticipantType(AbstractType):
__resource_type__ = "EncounterParticipant"
class EncounterStatu... | 64 | 64 | 19 | 8 | 56 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | EncounterStatusHistoryType | EncounterStatusHistoryType | 1,236 | 1,237 | 1,236 | 1,236 | 3fdeabf614381400b2c0ff3602014a09fda88c7e | bigcode/the-stack | train |
9b4ee375a7f214534d12e2ac | train | class | class ObservationReferenceRangeType(AbstractType):
__resource_type__ = "ObservationReferenceRange"
| class ObservationReferenceRangeType(AbstractType):
| __resource_type__ = "ObservationReferenceRange"
| MedicationStatement"
class MedicationStatementDosageType(AbstractType):
__resource_type__ = "MedicationStatementDosage"
class ObservationType(AbstractType):
__resource_type__ = "Observation"
class ObservationComponentType(AbstractType):
__resource_type__ = "ObservationComponent"
class ObservationRefer... | 64 | 64 | 19 | 8 | 56 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | ObservationReferenceRangeType | ObservationReferenceRangeType | 1,288 | 1,289 | 1,288 | 1,288 | 6770f544e4e8a4087f2edb599d8b8a91c4bf1d0d | bigcode/the-stack | train |
60041faf0c4059bf86be3bb6 | train | class | class MedicationStatementDosageType(AbstractType):
__resource_type__ = "MedicationStatementDosage"
| class MedicationStatementDosageType(AbstractType):
| __resource_type__ = "MedicationStatementDosage"
| class MedicationAdministrationType(AbstractType):
__resource_type__ = "MedicationAdministration"
class MedicationAdministrationDosageType(AbstractType):
__resource_type__ = "MedicationAdministrationDosage"
class MedicationStatementType(AbstractType):
__resource_type__ = "MedicationStatement"
class Medic... | 64 | 64 | 21 | 9 | 55 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | MedicationStatementDosageType | MedicationStatementDosageType | 1,276 | 1,277 | 1,276 | 1,276 | af77b375cb8480cc8cdb0a1490cb8742509aec8e | bigcode/the-stack | train |
5e65cc02b1ef2d3c8c06b1c8 | train | class | class DiagnosticReportImageType(AbstractType):
__resource_type__ = "DiagnosticReportImage"
| class DiagnosticReportImageType(AbstractType):
| __resource_type__ = "DiagnosticReportImage"
| ocalDevice"
class ProcedurePerformerType(AbstractType):
__resource_type__ = "ProcedurePerformer"
class ProcedureRequestType(AbstractType):
__resource_type__ = "ProcedureRequest"
class DiagnosticReportType(AbstractType):
__resource_type__ = "DiagnosticReport"
class DiagnosticReportImageType(AbstractTyp... | 64 | 64 | 19 | 8 | 56 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | DiagnosticReportImageType | DiagnosticReportImageType | 1,116 | 1,117 | 1,116 | 1,116 | b340568f26a52c1586cbafb1ba483a9c0bd5cf13 | bigcode/the-stack | train |
b151ee50d629167abb09740d | train | class | class ScheduleType(AbstractType):
__resource_type__ = "Schedule"
| class ScheduleType(AbstractType):
| __resource_type__ = "Schedule"
| Type):
__resource_type__ = "Flag"
class LocationType(AbstractType):
__resource_type__ = "Location"
class LocationPositionType(AbstractType):
__resource_type__ = "LocationPosition"
class SlotType(AbstractType):
__resource_type__ = "Slot"
class ScheduleType(AbstractType):
| 64 | 64 | 15 | 6 | 58 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | ScheduleType | ScheduleType | 652 | 653 | 652 | 652 | 34353d4b2951a8034416ba5e601f9c55420f53f5 | bigcode/the-stack | train |
9f3c7487c3f0e345b7a84220 | train | class | class ImplementationGuidePackageResourceType(AbstractType):
__resource_type__ = "ImplementationGuidePackageResource"
| class ImplementationGuidePackageResourceType(AbstractType):
| __resource_type__ = "ImplementationGuidePackageResource"
| GuideDependencyType(AbstractType):
__resource_type__ = "ImplementationGuideDependency"
class ImplementationGuideGlobalType(AbstractType):
__resource_type__ = "ImplementationGuideGlobal"
class ImplementationGuidePackageType(AbstractType):
__resource_type__ = "ImplementationGuidePackage"
class Implementat... | 64 | 64 | 21 | 9 | 55 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | ImplementationGuidePackageResourceType | ImplementationGuidePackageResourceType | 1,540 | 1,541 | 1,540 | 1,540 | fae2deb5fc9d879112859530cd0d0849f26c3a46 | bigcode/the-stack | train |
2855720b7ddd098540e13d0a | train | class | class OrderType(AbstractType):
__resource_type__ = "Order"
| class OrderType(AbstractType):
| __resource_type__ = "Order"
| _type__ = "PatientAnimal"
class PatientCommunicationType(AbstractType):
__resource_type__ = "PatientCommunication"
class PatientContactType(AbstractType):
__resource_type__ = "PatientContact"
class PatientLinkType(AbstractType):
__resource_type__ = "PatientLink"
class OrderType(AbstractType):
| 64 | 64 | 15 | 6 | 58 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | OrderType | OrderType | 1,008 | 1,009 | 1,008 | 1,008 | b16fa32e77ed253eaf365110fd4bcbb73c281f6a | bigcode/the-stack | train |
add71cb5c677fafde3fe1b23 | train | class | class GoalOutcomeType(AbstractType):
__resource_type__ = "GoalOutcome"
| class GoalOutcomeType(AbstractType):
| __resource_type__ = "GoalOutcome"
| "DocumentManifest"
class DocumentManifestContentType(AbstractType):
__resource_type__ = "DocumentManifestContent"
class DocumentManifestRelatedType(AbstractType):
__resource_type__ = "DocumentManifestRelated"
class GoalType(AbstractType):
__resource_type__ = "Goal"
class GoalOutcomeType(AbstractType)... | 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | GoalOutcomeType | GoalOutcomeType | 1,156 | 1,157 | 1,156 | 1,156 | 4ceeb35dff7f20ea23c7962e228e5ade9a7c5a84 | bigcode/the-stack | train |
b169aaec93d8e953013b0575 | train | class | class Primitive:
"""FHIR Primitive Data Type Base Class"""
__fhir_release__: str = "R4"
__visit_name__: Optional[str] = None
regex: Optional[Pattern[str]] = None
@classmethod
def is_primitive(cls) -> bool:
""" """
return True
@classmethod
def fhir_type_name(cls) -> Opt... | class Primitive:
| """FHIR Primitive Data Type Base Class"""
__fhir_release__: str = "R4"
__visit_name__: Optional[str] = None
regex: Optional[Pattern[str]] = None
@classmethod
def is_primitive(cls) -> bool:
""" """
return True
@classmethod
def fhir_type_name(cls) -> Optional[str]:
... | "integer",
"unsignedInt",
"positiveInt",
"uri",
"oid",
"uuid",
"canonical",
"url",
"markdown",
"xhtml",
"date",
"dateTime",
"instant",
"time",
]
class Primitive:
| 64 | 64 | 93 | 3 | 61 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | Primitive | Primitive | 56 | 71 | 56 | 56 | 49a8bb6e3c86ea4c4b79ab028b32069271c3a42f | bigcode/the-stack | train |
f2752f21ec33ee9d0ae51388 | train | class | class HealthcareServiceType(AbstractType):
__resource_type__ = "HealthcareService"
| class HealthcareServiceType(AbstractType):
| __resource_type__ = "HealthcareService"
| MemberHistoryType(AbstractType):
__resource_type__ = "FamilyMemberHistory"
class FamilyMemberHistoryConditionType(AbstractType):
__resource_type__ = "FamilyMemberHistoryCondition"
class ExplanationOfBenefitType(AbstractType):
__resource_type__ = "ExplanationOfBenefit"
class HealthcareServiceType(Abstrac... | 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | HealthcareServiceType | HealthcareServiceType | 1,456 | 1,457 | 1,456 | 1,456 | a8902cfbf5773f66aa8bea7bd8075a42e403a9d0 | bigcode/the-stack | train |
c08b7eb4846f9b09448ecd6a | train | class | class BundleEntryResponseType(AbstractType):
__resource_type__ = "BundleEntryResponse"
| class BundleEntryResponseType(AbstractType):
| __resource_type__ = "BundleEntryResponse"
| "AuditEventSource"
class BundleType(AbstractType):
__resource_type__ = "Bundle"
class BundleEntryType(AbstractType):
__resource_type__ = "BundleEntry"
class BundleEntryRequestType(AbstractType):
__resource_type__ = "BundleEntryRequest"
class BundleEntryResponseType(AbstractType):
| 64 | 64 | 19 | 8 | 56 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | BundleEntryResponseType | BundleEntryResponseType | 720 | 721 | 720 | 720 | acba187f876c7b26b338cdb8178f817d15ec4cb1 | bigcode/the-stack | train |
ec9e41a0a290aaf7cc8f1268 | train | class | class VisionPrescriptionDispenseType(AbstractType):
__resource_type__ = "VisionPrescriptionDispense"
| class VisionPrescriptionDispenseType(AbstractType):
| __resource_type__ = "VisionPrescriptionDispense"
| Entry"
class SupplyRequestType(AbstractType):
__resource_type__ = "SupplyRequest"
class SupplyRequestWhenType(AbstractType):
__resource_type__ = "SupplyRequestWhen"
class VisionPrescriptionType(AbstractType):
__resource_type__ = "VisionPrescription"
class VisionPrescriptionDispenseType(AbstractType):
| 64 | 64 | 21 | 9 | 55 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | VisionPrescriptionDispenseType | VisionPrescriptionDispenseType | 1,624 | 1,625 | 1,624 | 1,624 | dc46fe4692ac20e04325d77b73bf576d27f518d7 | bigcode/the-stack | train |
a215116d2a40949f04b036ba | train | class | class ConceptMapType(AbstractType):
__resource_type__ = "ConceptMap"
| class ConceptMapType(AbstractType):
| __resource_type__ = "ConceptMap"
| = "Composition"
class CompositionAttesterType(AbstractType):
__resource_type__ = "CompositionAttester"
class CompositionEventType(AbstractType):
__resource_type__ = "CompositionEvent"
class CompositionSectionType(AbstractType):
__resource_type__ = "CompositionSection"
class ConceptMapType(AbstractTyp... | 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | ConceptMapType | ConceptMapType | 892 | 893 | 892 | 892 | 28dd2341baf1f5c11b7d70ed07c0cee13db8948f | bigcode/the-stack | train |
1a041fc81b2ac386bab17a6b | train | class | class ConditionStageType(AbstractType):
__resource_type__ = "ConditionStage"
| class ConditionStageType(AbstractType):
| __resource_type__ = "ConditionStage"
| class ConceptMapElementTargetDependsOnType(AbstractType):
__resource_type__ = "ConceptMapElementTargetDependsOn"
class ConditionType(AbstractType):
__resource_type__ = "Condition"
class ConditionEvidenceType(AbstractType):
__resource_type__ = "ConditionEvidence"
class ConditionStageType(AbstractType):
| 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | ConditionStageType | ConditionStageType | 920 | 921 | 920 | 920 | 7a833b2c69fef6ced3ad1edb277e29f9a67d8a3a | bigcode/the-stack | train |
d91be6fdb5063d0d508576e1 | train | class | class ContractRuleType(AbstractType):
__resource_type__ = "ContractRule"
| class ContractRuleType(AbstractType):
| __resource_type__ = "ContractRule"
| _type__ = "Contract"
class ContractActorType(AbstractType):
__resource_type__ = "ContractActor"
class ContractFriendlyType(AbstractType):
__resource_type__ = "ContractFriendly"
class ContractLegalType(AbstractType):
__resource_type__ = "ContractLegal"
class ContractRuleType(AbstractType):
| 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | ContractRuleType | ContractRuleType | 1,344 | 1,345 | 1,344 | 1,344 | f55c8767f887cac3db7be0e85e7b4e3ec3a73d06 | bigcode/the-stack | train |
8a877856cdb1175f38035bc6 | train | class | class MoneyType(AbstractType):
__resource_type__ = "Money"
| class MoneyType(AbstractType):
| __resource_type__ = "Money"
| (AbstractType):
__resource_type__ = "TimingRepeat"
class DurationType(AbstractType):
__resource_type__ = "Duration"
class AgeType(AbstractType):
__resource_type__ = "Age"
class CountType(AbstractType):
__resource_type__ = "Count"
class MoneyType(AbstractType):
| 64 | 64 | 15 | 6 | 58 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | MoneyType | MoneyType | 604 | 605 | 604 | 604 | a0fd043d63016c6ebef5eb7f7a0c2d0facc2e630 | bigcode/the-stack | train |
d218b5c330d574b6352ef3ac | train | class | class MessageHeaderSourceType(AbstractType):
__resource_type__ = "MessageHeaderSource"
| class MessageHeaderSourceType(AbstractType):
| __resource_type__ = "MessageHeaderSource"
| "
class MessageHeaderType(AbstractType):
__resource_type__ = "MessageHeader"
class MessageHeaderDestinationType(AbstractType):
__resource_type__ = "MessageHeaderDestination"
class MessageHeaderResponseType(AbstractType):
__resource_type__ = "MessageHeaderResponse"
class MessageHeaderSourceType(Abstrac... | 64 | 64 | 19 | 8 | 56 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | MessageHeaderSourceType | MessageHeaderSourceType | 1,588 | 1,589 | 1,588 | 1,588 | f938687107ab3c99ba641c04b708072f7f6a23ad | bigcode/the-stack | train |
e47f00b2b6dd0a0bfa515017 | train | class | class CommunicationRequestType(AbstractType):
__resource_type__ = "CommunicationRequest"
| class CommunicationRequestType(AbstractType):
| __resource_type__ = "CommunicationRequest"
| class ClinicalImpressionRuledOutType(AbstractType):
__resource_type__ = "ClinicalImpressionRuledOut"
class CommunicationType(AbstractType):
__resource_type__ = "Communication"
class CommunicationPayloadType(AbstractType):
__resource_type__ = "CommunicationPayload"
class CommunicationRequestType(Abstract... | 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | CommunicationRequestType | CommunicationRequestType | 868 | 869 | 868 | 868 | 9d3ab7fb90819135529ed66d54bd53bd1aae31d0 | bigcode/the-stack | train |
b9b45e99abb0ff5b8565da1f | train | class | class ClaimResponseItemDetailSubDetailType(AbstractType):
__resource_type__ = "ClaimResponseItemDetailSubDetail"
| class ClaimResponseItemDetailSubDetailType(AbstractType):
| __resource_type__ = "ClaimResponseItemDetailSubDetail"
| ItemAdjudication"
class ClaimResponseItemDetailType(AbstractType):
__resource_type__ = "ClaimResponseItemDetail"
class ClaimResponseItemDetailAdjudicationType(AbstractType):
__resource_type__ = "ClaimResponseItemDetailAdjudication"
class ClaimResponseItemDetailSubDetailType(AbstractType):
| 64 | 64 | 25 | 11 | 53 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | ClaimResponseItemDetailSubDetailType | ClaimResponseItemDetailSubDetailType | 832 | 833 | 832 | 832 | 05f028aeff73cdc657f38ca8ce712eeb5b4ce730 | bigcode/the-stack | train |
2aa57b39c36dd9d9a8a949d1 | train | class | class DistanceType(AbstractType):
__resource_type__ = "Distance"
| class DistanceType(AbstractType):
| __resource_type__ = "Distance"
| Type(AbstractType):
__resource_type__ = "Duration"
class AgeType(AbstractType):
__resource_type__ = "Age"
class CountType(AbstractType):
__resource_type__ = "Count"
class MoneyType(AbstractType):
__resource_type__ = "Money"
class DistanceType(AbstractType):
| 64 | 64 | 15 | 6 | 58 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | DistanceType | DistanceType | 608 | 609 | 608 | 608 | 76189bbf9f14032fda6d3538929b0f00b1def3b0 | bigcode/the-stack | train |
38e00aaae45e83bcf5bb5137 | train | class | class MedicationDispenseType(AbstractType):
__resource_type__ = "MedicationDispense"
| class MedicationDispenseType(AbstractType):
| __resource_type__ = "MedicationDispense"
| PackageType(AbstractType):
__resource_type__ = "ImplementationGuidePackage"
class ImplementationGuidePackageResourceType(AbstractType):
__resource_type__ = "ImplementationGuidePackageResource"
class ImplementationGuidePageType(AbstractType):
__resource_type__ = "ImplementationGuidePage"
class Medication... | 64 | 64 | 19 | 8 | 56 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | MedicationDispenseType | MedicationDispenseType | 1,548 | 1,549 | 1,548 | 1,548 | 6cf6deb07843e437b1891ea2b0cb4a5cabb55101 | bigcode/the-stack | train |
e64a3a585d67d5dfb821bb6c | train | class | class ContractActorType(AbstractType):
__resource_type__ = "ContractActor"
| class ContractActorType(AbstractType):
| __resource_type__ = "ContractActor"
| "MedicationProduct"
class MedicationProductBatchType(AbstractType):
__resource_type__ = "MedicationProductBatch"
class MedicationProductIngredientType(AbstractType):
__resource_type__ = "MedicationProductIngredient"
class ContractType(AbstractType):
__resource_type__ = "Contract"
class ContractActorT... | 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | ContractActorType | ContractActorType | 1,332 | 1,333 | 1,332 | 1,332 | d518d728aad25539e78a4ae53792ed31baaf4994 | bigcode/the-stack | train |
1c2cf7777bba7649586cdc4a | train | class | class GroupMemberType(AbstractType):
__resource_type__ = "GroupMember"
| class GroupMemberType(AbstractType):
| __resource_type__ = "GroupMember"
| __resource_type__ = "Goal"
class GoalOutcomeType(AbstractType):
__resource_type__ = "GoalOutcome"
class GroupType(AbstractType):
__resource_type__ = "Group"
class GroupCharacteristicType(AbstractType):
__resource_type__ = "GroupCharacteristic"
class GroupMemberType(AbstractType):
| 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | GroupMemberType | GroupMemberType | 1,168 | 1,169 | 1,168 | 1,168 | f054f04bd55fc7feebf19f3d6a96e3ad621995aa | bigcode/the-stack | train |
e961bbb49a8bf9f4a050883f | train | class | class SpecimenContainerType(AbstractType):
__resource_type__ = "SpecimenContainer"
| class SpecimenContainerType(AbstractType):
| __resource_type__ = "SpecimenContainer"
| "
class SpecimenType(AbstractType):
__resource_type__ = "Specimen"
class SpecimenCollectionType(AbstractType):
__resource_type__ = "SpecimenCollection"
class SpecimenTreatmentType(AbstractType):
__resource_type__ = "SpecimenTreatment"
class SpecimenContainerType(AbstractType):
| 64 | 64 | 19 | 8 | 56 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | SpecimenContainerType | SpecimenContainerType | 1,640 | 1,641 | 1,640 | 1,640 | 64d539d2b88251379b539b5bb21d907535d880db | bigcode/the-stack | train |
c39a8e2fce3308464f57ee35 | train | class | class MedicationProductType(AbstractType):
__resource_type__ = "MedicationProduct"
| class MedicationProductType(AbstractType):
| __resource_type__ = "MedicationProduct"
| = "OperationOutcomeIssue"
class MedicationType(AbstractType):
__resource_type__ = "Medication"
class MedicationPackageType(AbstractType):
__resource_type__ = "MedicationPackage"
class MedicationPackageContentType(AbstractType):
__resource_type__ = "MedicationPackageContent"
class MedicationProductTyp... | 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | MedicationProductType | MedicationProductType | 1,316 | 1,317 | 1,316 | 1,316 | 49f0207a3a5558df5c8feecb6fbf8ecbaf89b1f3 | bigcode/the-stack | train |
2be99afdf086bec7b71e6e12 | train | class | class CommunicationPayloadType(AbstractType):
__resource_type__ = "CommunicationPayload"
| class CommunicationPayloadType(AbstractType):
| __resource_type__ = "CommunicationPayload"
| Type(AbstractType):
__resource_type__ = "ClinicalImpressionInvestigations"
class ClinicalImpressionRuledOutType(AbstractType):
__resource_type__ = "ClinicalImpressionRuledOut"
class CommunicationType(AbstractType):
__resource_type__ = "Communication"
class CommunicationPayloadType(AbstractType):
| 64 | 64 | 17 | 7 | 57 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | CommunicationPayloadType | CommunicationPayloadType | 864 | 865 | 864 | 864 | 3b81f1ad5019e4f5f8049b50baf88d168e3930d6 | bigcode/the-stack | train |
9704ed7e9b0a6cb35a8c3ebc | train | class | class HealthcareServiceServiceTypeType(AbstractType):
__resource_type__ = "HealthcareServiceServiceType"
| class HealthcareServiceServiceTypeType(AbstractType):
| __resource_type__ = "HealthcareServiceServiceType"
| (AbstractType):
__resource_type__ = "HealthcareService"
class HealthcareServiceAvailableTimeType(AbstractType):
__resource_type__ = "HealthcareServiceAvailableTime"
class HealthcareServiceNotAvailableType(AbstractType):
__resource_type__ = "HealthcareServiceNotAvailable"
class HealthcareServiceServiceTy... | 64 | 64 | 21 | 9 | 55 | iatechicken/fhir.resources | fhir/resources/DSTU2/fhirtypes.py | Python | HealthcareServiceServiceTypeType | HealthcareServiceServiceTypeType | 1,468 | 1,469 | 1,468 | 1,468 | a2b84429544947d6ef4a1abe473e19d56ecc5288 | bigcode/the-stack | train |
d7d07c374558ed110d59a29c | train | function | def add_note_to_track(track, note, mf):
if not note.pitch == 0: #pitch of 0 means no note is being played
volume = 100
channel = 0
mf.addNote(track, channel, note.pitch, note.time, note.duration, volume)
| def add_note_to_track(track, note, mf):
| if not note.pitch == 0: #pitch of 0 means no note is being played
volume = 100
channel = 0
mf.addNote(track, channel, note.pitch, note.time, note.duration, volume)
| :
def __init__(self, time = 0, pitch = 0):
self.duration = tick_length
self.time = time
self.pitch = pitch
def add_dur(self):
self.duration += tick_length
###Function Definitions
def add_note_to_track(track, note, mf):
| 64 | 64 | 65 | 11 | 52 | v3rm1/ml_bach_fugue | Full Pipeline/text_to_midi.py | Python | add_note_to_track | add_note_to_track | 15 | 19 | 15 | 15 | 828f6a43e42b592acc93f687a509a1a1503fdd5c | bigcode/the-stack | train |
29b51baca3f268b33a9be76d | train | class | class Note:
def __init__(self, time = 0, pitch = 0):
self.duration = tick_length
self.time = time
self.pitch = pitch
def add_dur(self):
self.duration += tick_length
| class Note:
| def __init__(self, time = 0, pitch = 0):
self.duration = tick_length
self.time = time
self.pitch = pitch
def add_dur(self):
self.duration += tick_length
| from midiutil.MidiFile import MIDIFile
tick_length = 0.25
###Class Definitions
class Note:
| 25 | 64 | 51 | 3 | 21 | v3rm1/ml_bach_fugue | Full Pipeline/text_to_midi.py | Python | Note | Note | 6 | 12 | 6 | 6 | 664d2ce71dd0c8818cb917de8f712970708e4c21 | bigcode/the-stack | train |
6cfeb8704df7681a516425de | train | class | class TestHelmValuesFactory:
@pytest.fixture
def factory(self, config: Config) -> HelmValuesFactory:
return HelmValuesFactory(config.helm_chart_names, container_runtime="docker")
def test_create_gcp_platform_values_with_nfs_storage(
self,
cluster_name: str,
gcp_platform_conf... | class TestHelmValuesFactory:
@pytest.fixture
| def factory(self, config: Config) -> HelmValuesFactory:
return HelmValuesFactory(config.helm_chart_names, container_runtime="docker")
def test_create_gcp_platform_values_with_nfs_storage(
self,
cluster_name: str,
gcp_platform_config: PlatformConfig,
factory: HelmValuesFa... | from dataclasses import replace
from unittest import mock
import pytest
from neuro_config_client import ACMEEnvironment, IdleJobConfig, Resources
from yarl import URL
from platform_operator.helm_values import HelmValuesFactory
from platform_operator.models import (
BucketsConfig,
BucketsProvider,
Config,
... | 113 | 256 | 18,065 | 12 | 101 | neuro-inc/platform-operator | tests/unit/test_helm_values.py | Python | TestHelmValuesFactory | TestHelmValuesFactory | 24 | 2,451 | 24 | 25 | 2070b6284b8a3bbad0a27bbfe5b317963f7a5ecf | bigcode/the-stack | train |
1aa98258c6f5ddc7e00eff2f | train | function | def update_head(dataset_id, dataset_path, hexsha, cookies=None):
"""Pass HEAD commit references back to OpenNeuro"""
# We may want to detect if we need to run validation here?
validate_dataset(dataset_id, dataset_path, hexsha)
r = requests.post(url=GRAPHQL_ENDPOINT,
json=draft_revi... | def update_head(dataset_id, dataset_path, hexsha, cookies=None):
| """Pass HEAD commit references back to OpenNeuro"""
# We may want to detect if we need to run validation here?
validate_dataset(dataset_id, dataset_path, hexsha)
r = requests.post(url=GRAPHQL_ENDPOINT,
json=draft_revision_mutation(dataset_id, hexsha), cookies=cookies)
if r.stat... | ': 'mutation ($datasetId: ID!, $ref: String!) { updateRef(datasetId: $datasetId, ref: $ref) }',
'variables': {'datasetId': dataset_id, 'ref': ref}
}
def update_head(dataset_id, dataset_path, hexsha, cookies=None):
| 64 | 64 | 97 | 15 | 49 | tommydino93/openneuro | services/datalad/datalad_service/common/draft.py | Python | update_head | update_head | 16 | 23 | 16 | 16 | 4fbe9e45ce27e23eacb6fbdad4847f938ee33f29 | bigcode/the-stack | train |
52dae19488aae110eed8b6f8 | train | function | def draft_revision_mutation(dataset_id, ref):
"""Update the draft HEAD reference to an new git commit id (hexsha)."""
return {
'query': 'mutation ($datasetId: ID!, $ref: String!) { updateRef(datasetId: $datasetId, ref: $ref) }',
'variables': {'datasetId': dataset_id, 'ref': ref}
}
| def draft_revision_mutation(dataset_id, ref):
| """Update the draft HEAD reference to an new git commit id (hexsha)."""
return {
'query': 'mutation ($datasetId: ID!, $ref: String!) { updateRef(datasetId: $datasetId, ref: $ref) }',
'variables': {'datasetId': dataset_id, 'ref': ref}
}
| import requests
import pygit2
from datalad_service.config import GRAPHQL_ENDPOINT
from datalad_service.tasks.validator import validate_dataset
def draft_revision_mutation(dataset_id, ref):
| 38 | 64 | 83 | 10 | 27 | tommydino93/openneuro | services/datalad/datalad_service/common/draft.py | Python | draft_revision_mutation | draft_revision_mutation | 8 | 13 | 8 | 8 | ca9d83fe42f9def9d8d9f0a534fa1212f1845858 | bigcode/the-stack | train |
9fb456aacc97f175521b3cf6 | train | function | def dataReader(spiderName):
try:
conn = MySQLdb.connect(
'localhost',
'root',
'hoangminh99',
'db_thesis',
charset="utf8",
use_unicode=True,
)
cursor = conn.cursor()
cursor.execute('''SELECT id, url FROM `{0}`;'''... | def dataReader(spiderName):
| try:
conn = MySQLdb.connect(
'localhost',
'root',
'hoangminh99',
'db_thesis',
charset="utf8",
use_unicode=True,
)
cursor = conn.cursor()
cursor.execute('''SELECT id, url FROM `{0}`;'''.format(spiderName))
... | import MySQLdb
from itemadapter import ItemAdapter
def dataReader(spiderName):
| 19 | 64 | 126 | 7 | 11 | hoanglm-2435/Thesis-fork | crawler/crawl_service/queries/readdata.py | Python | dataReader | dataReader | 5 | 21 | 5 | 5 | 96e8536dc6ff056dc764e0ad3b62a0b2fe90e374 | bigcode/the-stack | train |
d6bcc695f1ed76736d74814c | train | function | def format_layout(name, conf):
"""
Format a layout dictionary for writing to .dat file
@param name: layout name as in .lis file
@param conf: layout configuration
@type conf: dictionary
"""
res = "%s {\n" % (name, )
# Take subscans info from conf dictionary
subscans = conf.pop("subsca... | def format_layout(name, conf):
| """
Format a layout dictionary for writing to .dat file
@param name: layout name as in .lis file
@param conf: layout configuration
@type conf: dictionary
"""
res = "%s {\n" % (name, )
# Take subscans info from conf dictionary
subscans = conf.pop("subscans", [])
logger.debug("got ... | +
"${duration}\t" +
"${offset_frame}\t" +
"${offset_lon}\t" +
"${offset_lat}")
"""
Used to convert an instance of L{subscan.SkydipSubscan} into its representation
in the .lis file
"""
def... | 64 | 64 | 161 | 7 | 57 | flyingfrog81/basie | src/templates.py | Python | format_layout | format_layout | 101 | 116 | 101 | 101 | 4948f9e1313c22e60ed41c4516a878e77c36ba43 | bigcode/the-stack | train |
86b3ec2e1431fb4a0a70cbf4 | train | class | class UserSerializer(ModelSerializer):
"""A class providing (de-)serialization of `User` instances."""
# ID field must be explicitly set as the default id field is read-only.
id = IntegerField(min_value=0)
class Meta:
"""Metadata defined for the Django REST Framework."""
model = User
... | class UserSerializer(ModelSerializer):
| """A class providing (de-)serialization of `User` instances."""
# ID field must be explicitly set as the default id field is read-only.
id = IntegerField(min_value=0)
class Meta:
"""Metadata defined for the Django REST Framework."""
model = User
fields = ('id', 'name', 'discri... | ")
if not fields_to_update:
# Raise ValidationError when only id field is given.
raise ValidationError(
{api_settings.NON_FIELD_ERRORS_KEY: ["Insufficient data provided."]}
)
User.objects.bulk_update(updated, fields_to_update)
return updated
... | 64 | 64 | 159 | 6 | 57 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | UserSerializer | UserSerializer | 337 | 356 | 337 | 337 | 441af820d49dc9be4a3e14fb5141efc77a84420d | bigcode/the-stack | train |
5fa5467dd55cbd8e6af2fae4 | train | class | class InfractionSerializer(ModelSerializer):
"""A class providing (de-)serialization of `Infraction` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Infraction
fields = (
'id',
'inserted_at',
'expires_at',
... | class InfractionSerializer(ModelSerializer):
| """A class providing (de-)serialization of `Infraction` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Infraction
fields = (
'id',
'inserted_at',
'expires_at',
'active',
'user',
... | exist. This means that we cannot have both an allow
# and a deny for the same item, and we cannot have duplicates of the
# same item.
validators = [
UniqueTogetherValidator(
queryset=FilterList.objects.all(),
fields=['content', 'type'],
... | 106 | 107 | 358 | 7 | 99 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | InfractionSerializer | InfractionSerializer | 140 | 186 | 140 | 140 | 4caabc9fed3144a42ffe6de39e57418f5105abc2 | bigcode/the-stack | train |
a0289130916ff19bf99ed97e | train | class | class BotSettingSerializer(ModelSerializer):
"""A class providing (de-)serialization of `BotSetting` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = BotSetting
fields = ('name', 'data')
| class BotSettingSerializer(ModelSerializer):
| """A class providing (de-)serialization of `BotSetting` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = BotSetting
fields = ('name', 'data')
| models import (
BotSetting,
DeletedMessage,
DocumentationLink,
FilterList,
Infraction,
MessageDeletionContext,
Nomination,
NominationEntry,
OffTopicChannelName,
OffensiveMessage,
Reminder,
Role,
User
)
class BotSettingSerializer(ModelSerializer):
| 64 | 64 | 52 | 7 | 57 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | BotSettingSerializer | BotSettingSerializer | 32 | 39 | 32 | 32 | 0671f148a6c60a3090823f4f8dfb8a7d3478ced7 | bigcode/the-stack | train |
758411ac3cb88e7540696e05 | train | class | class DeletedMessageSerializer(ModelSerializer):
"""
A class providing (de-)serialization of `DeletedMessage` instances.
The serializer generally requires a valid `deletion_context` to be
given, which should be created beforehand. See the `DeletedMessage`
model for more information.
"""
au... | class DeletedMessageSerializer(ModelSerializer):
| """
A class providing (de-)serialization of `DeletedMessage` instances.
The serializer generally requires a valid `deletion_context` to be
given, which should be created beforehand. See the `DeletedMessage`
model for more information.
"""
author = PrimaryKeyRelatedField(
queryset=U... | ,
User
)
class BotSettingSerializer(ModelSerializer):
"""A class providing (de-)serialization of `BotSetting` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = BotSetting
fields = ('name', 'data')
class DeletedMessageSerializer(ModelSerialize... | 64 | 64 | 179 | 7 | 57 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | DeletedMessageSerializer | DeletedMessageSerializer | 42 | 70 | 42 | 42 | 10d00e15afdb27dedbc7377e1dda02908f838d29 | bigcode/the-stack | train |
7fd823a3acf70cfb0de02af7 | train | class | class UserListSerializer(ListSerializer):
"""List serializer for User model to handle bulk updates."""
def create(self, validated_data: list) -> list:
"""Override create method to optimize django queries."""
new_users = []
seen = set()
for user_dict in validated_data:
... | class UserListSerializer(ListSerializer):
| """List serializer for User model to handle bulk updates."""
def create(self, validated_data: list) -> list:
"""Override create method to optimize django queries."""
new_users = []
seen = set()
for user_dict in validated_data:
if user_dict["id"] in seen:
... | author = PrimaryKeyRelatedField(queryset=User.objects.all())
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Reminder
fields = (
'active',
'author',
'jump_url',
'channel_id',
'content',
'expi... | 142 | 142 | 476 | 7 | 135 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | UserListSerializer | UserListSerializer | 265 | 334 | 265 | 265 | 41c5ff078e1a1308ad65ee574169c14df2830318 | bigcode/the-stack | train |
7f6dc82fe5acc0d7b751c55a | train | class | class RoleSerializer(ModelSerializer):
"""A class providing (de-)serialization of `Role` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Role
fields = ('id', 'name', 'colour', 'permissions', 'position')
| class RoleSerializer(ModelSerializer):
| """A class providing (de-)serialization of `Role` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Role
fields = ('id', 'name', 'colour', 'permissions', 'position')
| Metadata defined for the Django REST Framework."""
model = Reminder
fields = (
'active',
'author',
'jump_url',
'channel_id',
'content',
'expiration',
'id',
'mentions',
'failures'
)
class ... | 64 | 64 | 58 | 6 | 58 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | RoleSerializer | RoleSerializer | 255 | 262 | 255 | 255 | 0718e014da6f7b120d1bd1908c4fbdc90dd8abc4 | bigcode/the-stack | train |
565b218d94c8f59fda0aa8e2 | train | class | class ReminderSerializer(ModelSerializer):
"""A class providing (de-)serialization of `Reminder` instances."""
author = PrimaryKeyRelatedField(queryset=User.objects.all())
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Reminder
fields = (
'ac... | class ReminderSerializer(ModelSerializer):
| """A class providing (de-)serialization of `Reminder` instances."""
author = PrimaryKeyRelatedField(queryset=User.objects.all())
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Reminder
fields = (
'active',
'author',
'j... | topic channel name. As the model
only has a single attribute, it is unnecessary to create a nested dictionary.
Additionally, this allows off topic channel name routes to simply return an
array of names instead of objects, saving on bandwidth.
"""
return obj.name
class ReminderSe... | 64 | 64 | 99 | 6 | 57 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | ReminderSerializer | ReminderSerializer | 233 | 252 | 233 | 233 | fd9a074af910444334cd8546aa10562a7714affa | bigcode/the-stack | train |
0db3f71dd04e835284a3340b | train | class | class OffTopicChannelNameSerializer(ModelSerializer):
"""A class providing (de-)serialization of `OffTopicChannelName` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = OffTopicChannelName
fields = ('name',)
def to_representation(self, obj: Of... | class OffTopicChannelNameSerializer(ModelSerializer):
| """A class providing (de-)serialization of `OffTopicChannelName` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = OffTopicChannelName
fields = ('name',)
def to_representation(self, obj: OffTopicChannelName) -> str:
"""
Return ... | '])
user_data = UserSerializer(user).data
ret['user'] = user_data
actor = User.objects.get(id=ret['actor'])
actor_data = UserSerializer(actor).data
ret['actor'] = actor_data
return ret
class OffTopicChannelNameSerializer(ModelSerializer):
| 64 | 64 | 154 | 9 | 54 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | OffTopicChannelNameSerializer | OffTopicChannelNameSerializer | 212 | 230 | 212 | 212 | d91de046aa0318043ac769fa62ba630fcbcad4c2 | bigcode/the-stack | train |
f4e8b3048182fc2a648d9001 | train | class | class FilterListSerializer(ModelSerializer):
"""A class providing (de-)serialization of `FilterList` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = FilterList
fields = ('id', 'created_at', 'updated_at', 'type', 'allowed', 'content', 'comment')
... | class FilterListSerializer(ModelSerializer):
| """A class providing (de-)serialization of `FilterList` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = FilterList
fields = ('id', 'created_at', 'updated_at', 'type', 'allowed', 'content', 'comment')
# This validator ensures only one fil... | class DocumentationLinkSerializer(ModelSerializer):
"""A class providing (de-)serialization of `DocumentationLink` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = DocumentationLink
fields = ('package', 'base_url', 'inventory_url')
class FilterLis... | 64 | 64 | 185 | 7 | 57 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | FilterListSerializer | FilterListSerializer | 115 | 137 | 115 | 115 | ac9f111ce7e44d39582a7622d51289f242579a46 | bigcode/the-stack | train |
2fe8edc788871129f03d4e3b | train | class | class ExpandedInfractionSerializer(InfractionSerializer):
"""
A class providing expanded (de-)serialization of `Infraction` instances.
In addition to the fields of `Infraction` objects themselves, this
serializer also attaches the `user` and `actor` fields when serializing.
"""
def to_represen... | class ExpandedInfractionSerializer(InfractionSerializer):
| """
A class providing expanded (de-)serialization of `Infraction` instances.
In addition to the fields of `Infraction` objects themselves, this
serializer also attaches the `user` and `actor` fields when serializing.
"""
def to_representation(self, instance: Infraction) -> dict:
"""Ret... | ': [f'{infr_type} infractions cannot be hidden.']})
if not hidden and infr_type in ('note', ):
raise ValidationError({'hidden': [f'{infr_type} infractions must be hidden.']})
return attrs
class ExpandedInfractionSerializer(InfractionSerializer):
| 64 | 64 | 165 | 10 | 53 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | ExpandedInfractionSerializer | ExpandedInfractionSerializer | 189 | 209 | 189 | 189 | 34aea67a500ebab3ce821277fcb22656878cbd78 | bigcode/the-stack | train |
ed351447914858f1719ef61d | train | class | class OffensiveMessageSerializer(ModelSerializer):
"""A class providing (de-)serialization of `OffensiveMessage` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = OffensiveMessage
fields = ('id', 'channel_id', 'delete_date')
| class OffensiveMessageSerializer(ModelSerializer):
| """A class providing (de-)serialization of `OffensiveMessage` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = OffensiveMessage
fields = ('id', 'channel_id', 'delete_date')
| )
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Nomination
fields = (
'id', 'active', 'user', 'inserted_at', 'end_reason', 'ended_at', 'reviewed', 'entries'
)
class OffensiveMessageSerializer(ModelSerializer):
| 64 | 64 | 58 | 7 | 57 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | OffensiveMessageSerializer | OffensiveMessageSerializer | 391 | 398 | 391 | 391 | 4f226563b96d1fddbd72ee7d2798500e03f9c7fa | bigcode/the-stack | train |
0dfa3e89fe130ca51dad49b1 | train | class | class NominationSerializer(ModelSerializer):
"""A class providing (de-)serialization of `Nomination` instances."""
entries = NominationEntrySerializer(many=True, read_only=True)
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Nomination
fields = (
... | class NominationSerializer(ModelSerializer):
| """A class providing (de-)serialization of `Nomination` instances."""
entries = NominationEntrySerializer(many=True, read_only=True)
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Nomination
fields = (
'id', 'active', 'user', 'inserted_at', '... | RelatedField(
queryset=Nomination.objects.all(),
write_only=True
)
class Meta:
"""Metadata defined for the Django REST framework."""
model = NominationEntry
fields = ('nomination', 'actor', 'reason', 'inserted_at')
class NominationSerializer(ModelSerializer):
| 64 | 64 | 94 | 7 | 57 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | NominationSerializer | NominationSerializer | 377 | 388 | 377 | 377 | c57462484cfae5230db7ae4f44c77d060ebb29b1 | bigcode/the-stack | train |
82a88c258cbcff9e5cd1fd5d | train | class | class DocumentationLinkSerializer(ModelSerializer):
"""A class providing (de-)serialization of `DocumentationLink` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = DocumentationLink
fields = ('package', 'base_url', 'inventory_url')
| class DocumentationLinkSerializer(ModelSerializer):
| """A class providing (de-)serialization of `DocumentationLink` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = DocumentationLink
fields = ('package', 'base_url', 'inventory_url')
| """
messages = validated_data.pop('deletedmessage_set')
deletion_context = MessageDeletionContext.objects.create(**validated_data)
for message in messages:
DeletedMessage.objects.create(
deletion_context=deletion_context,
**message
... | 64 | 64 | 57 | 7 | 56 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | DocumentationLinkSerializer | DocumentationLinkSerializer | 105 | 112 | 105 | 105 | 93ea2aa218591ca6c09395297d6dc4bc130b123f | bigcode/the-stack | train |
5c612c56a05b8e05ac8fb028 | train | class | class NominationEntrySerializer(ModelSerializer):
"""A class providing (de-)serialization of `NominationEntry` instances."""
# We need to define it here, because we don't want that nomination ID
# return inside nomination response entry, because ID is already available
# as top-level field. Queryset is... | class NominationEntrySerializer(ModelSerializer):
| """A class providing (de-)serialization of `NominationEntry` instances."""
# We need to define it here, because we don't want that nomination ID
# return inside nomination response entry, because ID is already available
# as top-level field. Queryset is required if field is not read only.
nominatio... | def create(self, validated_data: dict) -> User:
"""Override create method to catch IntegrityError."""
try:
return super().create(validated_data)
except IntegrityError:
raise ValidationError({"id": ["User with ID already present."]})
class NominationEntrySerializer(Mod... | 64 | 64 | 136 | 8 | 56 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | NominationEntrySerializer | NominationEntrySerializer | 359 | 374 | 359 | 359 | 78f2139165ef903f1cbd73ee2e84e5ff8e8095f3 | bigcode/the-stack | train |
599e6ba5028e9a2bcb24d400 | train | class | class MessageDeletionContextSerializer(ModelSerializer):
"""A class providing (de-)serialization of `MessageDeletionContext` instances."""
actor = PrimaryKeyRelatedField(queryset=User.objects.all(), allow_null=True)
deletedmessage_set = DeletedMessageSerializer(many=True)
class Meta:
"""Metada... | class MessageDeletionContextSerializer(ModelSerializer):
| """A class providing (de-)serialization of `MessageDeletionContext` instances."""
actor = PrimaryKeyRelatedField(queryset=User.objects.all(), allow_null=True)
deletedmessage_set = DeletedMessageSerializer(many=True)
class Meta:
"""Metadata defined for the Django REST Framework."""
mod... | .
required=False
)
class Meta:
"""Metadata defined for the Django REST Framework."""
model = DeletedMessage
fields = (
'id', 'author',
'channel_id', 'content',
'embeds', 'deletion_context',
'attachments'
)
class MessageDel... | 70 | 70 | 234 | 8 | 62 | KrishnaKanth1729/site | pydis_site/apps/api/serializers.py | Python | MessageDeletionContextSerializer | MessageDeletionContextSerializer | 73 | 102 | 73 | 73 | dcef7766c9a1966e4c6c94280b8087b1d5a04ead | bigcode/the-stack | train |
c461019e7aea62b8184d281c | train | function | async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the configuration entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
[
PhilipsTVRemote(
... | async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
| """Set up the configuration entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
[
PhilipsTVRemote(
coordinator,
config_entry.data[CONF_SYSTEM],
config_entry.unique_id,
)
]
)
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import LOGGER, PhilipsTVDataUpdateCoordinator
from .const import CONF_SYSTEM, DOMAIN
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
| 64 | 64 | 88 | 32 | 31 | johnmmclaughlin/core | homeassistant/components/philips_js/remote.py | Python | async_setup_entry | async_setup_entry | 21 | 36 | 21 | 25 | f6c1019f384d7b0b21685914490a717c53ecc4a9 | bigcode/the-stack | train |
179d03fc4a237f4967effacc | train | class | class PhilipsTVRemote(RemoteEntity):
"""Device that sends commands."""
def __init__(
self,
coordinator: PhilipsTVDataUpdateCoordinator,
system: SystemType,
unique_id: str,
) -> None:
"""Initialize the Philips TV."""
self._tv = coordinator.api
self._co... | class PhilipsTVRemote(RemoteEntity):
| """Device that sends commands."""
def __init__(
self,
coordinator: PhilipsTVDataUpdateCoordinator,
system: SystemType,
unique_id: str,
) -> None:
"""Initialize the Philips TV."""
self._tv = coordinator.api
self._coordinator = coordinator
self.... | )
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import LOGGER, PhilipsTVDataUpdateCoordinator
from .const import CONF_SYSTEM, DOMAIN
asy... | 154 | 154 | 514 | 8 | 146 | johnmmclaughlin/core | homeassistant/components/philips_js/remote.py | Python | PhilipsTVRemote | PhilipsTVRemote | 39 | 114 | 39 | 39 | 3670da4ce1bcd6b20c2a218ccd29dbff86fb7112 | bigcode/the-stack | train |
c7028affc92fddd1736376d6 | train | function | def run():
model = MODEL_DISPATCHER[config.BASE_MODEL](pretrained=True)
model.to(device)
train_dataset = BengaliDatasetTrain(
folds=config.TRAINING_FOLDS,
image_height=config.IMG_HEIGHT,
image_width=config.IMG_WIDTH,
mean=config.MODEL_MEAN,
std=config.MODEL_STD,
... | def run():
| model = MODEL_DISPATCHER[config.BASE_MODEL](pretrained=True)
model.to(device)
train_dataset = BengaliDatasetTrain(
folds=config.TRAINING_FOLDS,
image_height=config.IMG_HEIGHT,
image_width=config.IMG_WIDTH,
mean=config.MODEL_MEAN,
std=config.MODEL_STD,
)
trai... | import os
import torch
import torch.nn as nn
import engine
from dataset import BengaliDatasetTrain
import config
from model_dispatcher import MODEL_DISPATCHER
from torch.utils.data import DataLoader
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def run():
| 63 | 103 | 344 | 3 | 60 | oke-aditya/kaggle_submissions | Advanced/Bengali.AI_Image_Classification/src/train.py | Python | run | run | 13 | 60 | 13 | 13 | a5340e58f6305c64b386746b339a0054f1873029 | bigcode/the-stack | train |
4933ee0e45d3fccd339562b2 | train | function | def fit(data, filter_names, apertures, model_dir, output, n_data_min=3,
extinction_law=None, av_range=None, distance_range=None,
output_format=('F', 6.), output_convolved=False,
remove_resolved=False):
"""
Fit a set of sources with models
Parameters
----------
data : str
... | def fit(data, filter_names, apertures, model_dir, output, n_data_min=3,
extinction_law=None, av_range=None, distance_range=None,
output_format=('F', 6.), output_convolved=False,
remove_resolved=False):
| """
Fit a set of sources with models
Parameters
----------
data : str
Filename of the file containing the data, one source per line (see
documentation for a description of the required format).
filter_names : tuple or list
List of filter names (given as individual string... | , remove_resolved=remove_resolved)
# Add wavelength to filters
for i, f in enumerate(self.filters):
if 'wav' not in f:
f['wav'] = self.models.wavelengths[i]
# Set Av law
self.av_law = extinction_law.get_av(self.models.wavelengths)
# Set scale model ... | 256 | 256 | 1,094 | 55 | 200 | keflavich/sedfitter | sedfitter/fit.py | Python | fit | fit | 114 | 237 | 114 | 117 | 7fb6cf19e89f909d9590f421ade828cf9d4a2828 | bigcode/the-stack | train |
4a695f7b3f403ac289a19966 | train | class | class Fitter(object):
"""
A fitter class that can be used to fit sources.
This class is initialized using a particular set of models, and with
specific fit parameters. It can then be used to fit data given by Source
instances, and returns a FitInfo instance. Once initialized, the fit
parameters... | class Fitter(object):
| """
A fitter class that can be used to fit sources.
This class is initialized using a particular set of models, and with
specific fit parameters. It can then be used to fit data given by Source
instances, and returns a FitInfo instance. Once initialized, the fit
parameters cannot be changed, be... | from __future__ import print_function, division
# Still to implement:
# - Performance monitoring
# - Remove resolved models
# - Optional FITS input/output
# - Output convolved fluxes
import numpy as np
from astropy import units as u
from . import timer
from .models import Models
from .source import Source
from .uti... | 105 | 256 | 895 | 5 | 99 | keflavich/sedfitter | sedfitter/fit.py | Python | Fitter | Fitter | 22 | 111 | 22 | 22 | 28fe42cac53fc4df048443d11a32730859ea894b | bigcode/the-stack | train |
12a297f2fd312b473d13d182 | train | function | def k_sorted(arr_in, k):
o_arr = []
for i in range(k+1):
heapq.heappush(o_arr, arr_in[i])
index = 0
for i in range(k+1, len(arr_in)):
arr_in[index] = heapq.heappop(o_arr)
index += 1
heapq.heappush(o_arr, arr_in[i])
while len(o_arr) > 0:
arr_in[index] = heapq.h... | def k_sorted(arr_in, k):
| o_arr = []
for i in range(k+1):
heapq.heappush(o_arr, arr_in[i])
index = 0
for i in range(k+1, len(arr_in)):
arr_in[index] = heapq.heappop(o_arr)
index += 1
heapq.heappush(o_arr, arr_in[i])
while len(o_arr) > 0:
arr_in[index] = heapq.heappop(o_arr)
ind... | """Sort a k sorted array """
import heapq
def k_sorted(arr_in, k):
| 19 | 64 | 122 | 8 | 10 | lakshyarawal/pythonPractice | Heap/k_sorted.py | Python | k_sorted | k_sorted | 5 | 17 | 5 | 5 | c4c750eda817b4315efb3633c02ac80efe82d3d9 | bigcode/the-stack | train |
09e080b42748f73e43290f2f | train | function | def main():
n_arr = [10, 9, 7, 8, 4, 70, 50, 60]
k_sorted(n_arr, 4)
| def main():
| n_arr = [10, 9, 7, 8, 4, 70, 50, 60]
k_sorted(n_arr, 4)
| q.heappop(o_arr)
index += 1
heapq.heappush(o_arr, arr_in[i])
while len(o_arr) > 0:
arr_in[index] = heapq.heappop(o_arr)
index += 1
print(arr_in)
def main():
| 64 | 64 | 40 | 3 | 61 | lakshyarawal/pythonPractice | Heap/k_sorted.py | Python | main | main | 20 | 22 | 20 | 20 | fe0a020a9bd6521ea18caecd7ee6b490c8321db8 | bigcode/the-stack | train |
36de56dae6dfab6b33b5bda3 | train | class | class DisassociateRouteTableResponse(SdkResponse):
"""
Attributes:
openapi_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.
"... | class DisassociateRouteTableResponse(SdkResponse):
| """
Attributes:
openapi_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.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class DisassociateRouteTableResponse(SdkResponse):
| 52 | 191 | 639 | 11 | 40 | huaweicloud/huaweicloud-sdk-python-v3 | huaweicloud-sdk-vpc/huaweicloudsdkvpc/v2/model/disassociate_route_table_response.py | Python | DisassociateRouteTableResponse | DisassociateRouteTableResponse | 11 | 112 | 11 | 13 | 886eebbcebd66a49c87627fc92737a5523e4eec4 | bigcode/the-stack | train |
3a1bde26958ae5b412b4a43a | train | class | class ConformerStreamingCascadedU2Encoder(AbsEncoder):
"""Conformer encoder module.
Args:
input_size (int): Input dimension.
output_size (int): Dimention of attention.
attention_heads (int): The number of heads of multi head attention.
linear_units (int): The number of un... | class ConformerStreamingCascadedU2Encoder(AbsEncoder):
| """Conformer encoder module.
Args:
input_size (int): Input dimension.
output_size (int): Dimention of attention.
attention_heads (int): The number of heads of multi head attention.
linear_units (int): The number of units of position-wise feed forward.
num_blocks (... | _backend.transformer.layer_norm import LayerNorm
from espnet.nets.pytorch_backend.transformer.multi_layer_conv import Conv1dLinear
from espnet.nets.pytorch_backend.transformer.multi_layer_conv import MultiLayeredConv1d
from espnet.nets.pytorch_backend.transformer.positionwise_feed_forward import (
PositionwiseF... | 256 | 256 | 3,854 | 14 | 241 | jinggaizi/test-2 | espnet2/asr/encoder/conformer_streaming_cascaded_encoder_dynamic_u2.py | Python | ConformerStreamingCascadedU2Encoder | ConformerStreamingCascadedU2Encoder | 35 | 447 | 35 | 35 | 5d86e295eef5dab59d27009eea3d1f64de7090fa | bigcode/the-stack | train |
8245e1d4cb58215e9b5e9940 | train | function | def get_dataflow(config):
# - Get train/test datasets
if idist.get_local_rank() > 0:
# Ensure that only local rank 0 download the dataset
# Thus each node will download a copy of the dataset
idist.barrier()
train_dataset, test_dataset = utils.get_train_test_datasets(config["data_pat... | def get_dataflow(config):
# - Get train/test datasets
| if idist.get_local_rank() > 0:
# Ensure that only local rank 0 download the dataset
# Thus each node will download a copy of the dataset
idist.barrier()
train_dataset, test_dataset = utils.get_train_test_datasets(config["data_path"])
if idist.get_local_rank() == 0:
# Ensure... | pu" and with_amp:
raise RuntimeError("The value of with_amp should be False if backend is xla")
with idist.Parallel(backend=backend, **spawn_kwargs) as parallel:
parallel.run(training, config)
def get_dataflow(config):
# - Get train/test datasets
| 64 | 64 | 210 | 14 | 50 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | get_dataflow | get_dataflow | 204 | 225 | 204 | 205 | 137001fc54d8a52334afb236a7a6a54aff9e8c33 | bigcode/the-stack | train |
0768056b024826d0662f3849 | train | function | def training(local_rank, config):
rank = idist.get_rank()
manual_seed(config["seed"] + rank)
device = idist.device()
logger = setup_logger(name="CIFAR10-Training")
log_basic_info(logger, config)
output_path = config["output_path"]
if rank == 0:
if config["stop_iteration"] is None... | def training(local_rank, config):
| rank = idist.get_rank()
manual_seed(config["seed"] + rank)
device = idist.device()
logger = setup_logger(name="CIFAR10-Training")
log_basic_info(logger, config)
output_path = config["output_path"]
if rank == 0:
if config["stop_iteration"] is None:
now = datetime.now().... | from datetime import datetime
from pathlib import Path
import fire
import torch
import torch.nn as nn
import torch.optim as optim
import utils
from torch.cuda.amp import GradScaler, autocast
import ignite
import ignite.distributed as idist
from ignite.contrib.engines import common
from ignite.contrib.handlers import ... | 119 | 256 | 958 | 7 | 111 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | training | training | 21 | 135 | 21 | 22 | 2f88cab778085794196811a3c5988525753cec10 | bigcode/the-stack | train |
d59fd2a229f4152995c702f7 | train | function | def create_evaluator(model, metrics, config, tag="val"):
with_amp = config["with_amp"]
device = idist.device()
@torch.no_grad()
def evaluate_step(engine: Engine, batch):
model.eval()
x, y = batch[0], batch[1]
if x.device != device:
x = x.to(device, non_blocking=True)... | def create_evaluator(model, metrics, config, tag="val"):
| with_amp = config["with_amp"]
device = idist.device()
@torch.no_grad()
def evaluate_step(engine: Engine, batch):
model.eval()
x, y = batch[0], batch[1]
if x.device != device:
x = x.to(device, non_blocking=True)
y = y.to(device, non_blocking=True)
... | "Resume from a checkpoint: {checkpoint_fp.as_posix()}")
checkpoint = torch.load(checkpoint_fp.as_posix(), map_location="cpu")
Checkpoint.load_objects(to_load=to_save, checkpoint=checkpoint)
return trainer
def create_evaluator(model, metrics, config, tag="val"):
| 64 | 64 | 183 | 14 | 49 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | create_evaluator | create_evaluator | 355 | 379 | 355 | 355 | 36da98bd3dcd00bfc776527969813427030ad7eb | bigcode/the-stack | train |
4df2105b2cffc24e87bce7a3 | train | function | def get_save_handler(config):
if config["with_clearml"]:
from ignite.contrib.handlers.clearml_logger import ClearMLSaver
return ClearMLSaver(dirname=config["output_path"])
return DiskSaver(config["output_path"], require_empty=False)
| def get_save_handler(config):
| if config["with_clearml"]:
from ignite.contrib.handlers.clearml_logger import ClearMLSaver
return ClearMLSaver(dirname=config["output_path"])
return DiskSaver(config["output_path"], require_empty=False)
| name, metric in metrics.items():
metric.attach(evaluator, name)
if idist.get_rank() == 0 and (not config["with_clearml"]):
common.ProgressBar(desc=f"Evaluation ({tag})", persist=False).attach(evaluator)
return evaluator
def get_save_handler(config):
| 64 | 64 | 51 | 6 | 57 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | get_save_handler | get_save_handler | 382 | 388 | 382 | 382 | eeb83c413748eafc58230f35d6970b812c0daea4 | bigcode/the-stack | train |
7e1812dc707522f5f9c7686d | train | function | def initialize(config):
model = utils.get_model(config["model"])
# Adapt model for distributed settings if configured
model = idist.auto_model(model)
optimizer = optim.SGD(
model.parameters(),
lr=config["learning_rate"],
momentum=config["momentum"],
weight_decay=config["... | def initialize(config):
| model = utils.get_model(config["model"])
# Adapt model for distributed settings if configured
model = idist.auto_model(model)
optimizer = optim.SGD(
model.parameters(),
lr=config["learning_rate"],
momentum=config["momentum"],
weight_decay=config["weight_decay"],
... | num_workers=config["num_workers"], shuffle=True, drop_last=True,
)
test_loader = idist.auto_dataloader(
test_dataset, batch_size=2 * config["batch_size"], num_workers=config["num_workers"], shuffle=False,
)
return train_loader, test_loader
def initialize(config):
| 64 | 64 | 188 | 4 | 59 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | initialize | initialize | 228 | 251 | 228 | 228 | c8a895324d6f41c511791faf593c1ebcb9f9d631 | bigcode/the-stack | train |
12093b2d257bfaa1b8094eaf | train | function | def log_metrics(logger, epoch, elapsed, tag, metrics):
metrics_output = "\n".join([f"\t{k}: {v}" for k, v in metrics.items()])
logger.info(f"\nEpoch {epoch} - Evaluation time (seconds): {elapsed:.2f} - {tag} metrics:\n {metrics_output}")
| def log_metrics(logger, epoch, elapsed, tag, metrics):
| metrics_output = "\n".join([f"\t{k}: {v}" for k, v in metrics.items()])
logger.info(f"\nEpoch {epoch} - Evaluation time (seconds): {elapsed:.2f} - {tag} metrics:\n {metrics_output}")
| _rate"]),
(le * config["num_epochs"], 0.0),
]
lr_scheduler = PiecewiseLinear(optimizer, param_name="lr", milestones_values=milestones_values)
return model, optimizer, criterion, lr_scheduler
def log_metrics(logger, epoch, elapsed, tag, metrics):
| 64 | 64 | 71 | 13 | 50 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | log_metrics | log_metrics | 254 | 256 | 254 | 254 | e9570ab1e0a3fbca8e2af0a8ea8dba69f59a1946 | bigcode/the-stack | train |
14d3e1c9fd6a9f516190026f | train | function | def run(
seed=543,
data_path="/tmp/cifar10",
output_path="/tmp/output-cifar10/",
model="resnet18",
batch_size=512,
momentum=0.9,
weight_decay=1e-4,
num_workers=12,
num_epochs=24,
learning_rate=0.4,
num_warmup_epochs=4,
validate_every=3,
checkpoint_every=1000,
back... | def run(
seed=543,
data_path="/tmp/cifar10",
output_path="/tmp/output-cifar10/",
model="resnet18",
batch_size=512,
momentum=0.9,
weight_decay=1e-4,
num_workers=12,
num_epochs=24,
learning_rate=0.4,
num_warmup_epochs=4,
validate_every=3,
checkpoint_every=1000,
back... | """Main entry to train an model on CIFAR10 dataset.
Args:
seed (int): random state seed to set. Default, 543.
data_path (str): input dataset path. Default, "/tmp/cifar10".
output_path (str): output path. Default, "/tmp/output-cifar10".
model (str): model name (from torchvision) ... | .ITERATION_STARTED(once=config["stop_iteration"]))
def _():
logger.info(f"Stop training on {trainer.state.iteration} iteration")
trainer.terminate()
try:
trainer.run(train_loader, max_epochs=config["num_epochs"])
except Exception as e:
logger.exception("")
... | 221 | 221 | 737 | 143 | 78 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | run | run | 138 | 201 | 138 | 160 | 47679cbba0c2233338571383e6d6fd88f0e2ecf7 | bigcode/the-stack | train |
0af9bd88ccab06117d0c69cc | train | function | def create_trainer(model, optimizer, criterion, lr_scheduler, train_sampler, config, logger):
device = idist.device()
# Setup Ignite trainer:
# - let's define training step
# - add other common handlers:
# - TerminateOnNan,
# - handler to setup learning rate scheduling,
# - ModelC... | def create_trainer(model, optimizer, criterion, lr_scheduler, train_sampler, config, logger):
| device = idist.device()
# Setup Ignite trainer:
# - let's define training step
# - add other common handlers:
# - TerminateOnNan,
# - handler to setup learning rate scheduling,
# - ModelCheckpoint
# - RunningAverage` on `train_step` output
# - Two progress bars on epo... | "- CUDA version: {torch.version.cuda}")
logger.info(f"- CUDNN version: {cudnn.version()}")
logger.info("\n")
logger.info("Configuration:")
for key, value in config.items():
logger.info(f"\t{key}: {value}")
logger.info("\n")
if idist.get_world_size() > 1:
logger.info("\nDist... | 142 | 142 | 474 | 20 | 122 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | create_trainer | create_trainer | 285 | 352 | 285 | 286 | bf5f4549fc8079c21cbdc53b0f4ac3448900df73 | bigcode/the-stack | train |
cfb113dc9af377aa0cf02465 | train | function | def log_basic_info(logger, config):
logger.info(f"Train {config['model']} on CIFAR10")
logger.info(f"- PyTorch version: {torch.__version__}")
logger.info(f"- Ignite version: {ignite.__version__}")
if torch.cuda.is_available():
# explicitly import cudnn as
# torch.backends.cudnn can not b... | def log_basic_info(logger, config):
| logger.info(f"Train {config['model']} on CIFAR10")
logger.info(f"- PyTorch version: {torch.__version__}")
logger.info(f"- Ignite version: {ignite.__version__}")
if torch.cuda.is_available():
# explicitly import cudnn as
# torch.backends.cudnn can not be pickled with hvd spawning procs
... | , tag, metrics):
metrics_output = "\n".join([f"\t{k}: {v}" for k, v in metrics.items()])
logger.info(f"\nEpoch {epoch} - Evaluation time (seconds): {elapsed:.2f} - {tag} metrics:\n {metrics_output}")
def log_basic_info(logger, config):
| 71 | 72 | 242 | 8 | 63 | Anubha13kumari/ignite | examples/contrib/cifar10/main.py | Python | log_basic_info | log_basic_info | 259 | 282 | 259 | 259 | ce31dda2ffe15da9e288079f62158840d90a646b | bigcode/the-stack | train |
46fbd1d4b17ed22d1da9473f | train | function | def list2excel(arr: list, filename: str):
writer = pd.ExcelWriter(filename)
pd.DataFrame(arr).to_excel(writer)
writer.save()
| def list2excel(arr: list, filename: str):
| writer = pd.ExcelWriter(filename)
pd.DataFrame(arr).to_excel(writer)
writer.save()
| import pandas as pd
def list2excel(arr: list, filename: str):
| 17 | 64 | 34 | 12 | 4 | lgasyou/spark-scheduler-configuration-optimizer | optimizer/util/excelutil.py | Python | list2excel | list2excel | 4 | 7 | 4 | 4 | 430fcca5e76f83c0ee058d04ab97be9f6f4c4425 | bigcode/the-stack | train |
208c5f822a5e84ed8ea4c5bc | train | function | def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tke_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on... | def main():
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tke_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHON... | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
| 26 | 64 | 94 | 3 | 22 | moradia100/TKE-Website | tke_project/manage.py | Python | main | main | 7 | 17 | 7 | 7 | 3cc34871ebde44ea22f6cb628d11f6f00c1bc8b2 | bigcode/the-stack | train |
167dbb53c72de0690434f3e6 | train | function | def lambda_handler(event, context):
logger.info('Got event {}'.format(event))
try:
properties = event['ResourceProperties']
region = os.environ['AWS_REGION']
client = boto3.client('securityhub', region_name=region)
responseData = {}
if event['RequestType'] == 'Create':
... | def lambda_handler(event, context):
| logger.info('Got event {}'.format(event))
try:
properties = event['ResourceProperties']
region = os.environ['AWS_REGION']
client = boto3.client('securityhub', region_name=region)
responseData = {}
if event['RequestType'] == 'Create':
response = client.create_a... | import logging
import os
import boto3
import cfnresponse
logger = logging.getLogger()
logger.setLevel(level=logging.INFO)
def lambda_handler(event, context):
| 35 | 72 | 241 | 7 | 28 | musayev-io/Cloud-AWS | Network-Firewall/lambda-src/create_action_target.py | Python | lambda_handler | lambda_handler | 11 | 34 | 11 | 11 | bf379faf425abe679b2d99da91d4f8defc4038c6 | bigcode/the-stack | train |
61c8d1ce81fe73306e36dec2 | train | function | def compute_diff(files, format='html'):
io = daff.TableIO()
dapp = daff.Coopy(io)
t1 = dapp.loadTable(files['prev_raw_file'], 'local')
t2 = dapp.loadTable(files['raw_file'], 'remote')
if format == 'both':
r1 = daff.diffAsHtml(t1, t2)
r2 = daff.diffAsAnsi(t1, t2)
return (r1, r... | def compute_diff(files, format='html'):
| io = daff.TableIO()
dapp = daff.Coopy(io)
t1 = dapp.loadTable(files['prev_raw_file'], 'local')
t2 = dapp.loadTable(files['raw_file'], 'remote')
if format == 'both':
r1 = daff.diffAsHtml(t1, t2)
r2 = daff.diffAsAnsi(t1, t2)
return (r1, r2)
if format == 'html':
retu... | ss.save_local(private_output_file, private_sheets=True)
state['workbook'] = ss.public_workbook()
write_destination(destination, state)
return {
'prev_raw_file': prev_raw_file,
'raw_file': raw_file
}
def compute_diff(files, format='html'):
| 64 | 64 | 139 | 9 | 55 | paulfitz/sheetsite | sheetsite/chain.py | Python | compute_diff | compute_diff | 99 | 110 | 99 | 99 | 979365d741a7f5fbd40147743c07bfd7f919b28a | bigcode/the-stack | train |
223f9fb767227d19b25a578a | train | function | def apply_chain(site, path):
if not(os.path.exists(path)):
os.makedirs(path)
source = site['source']
destination = site['destination']
tweaks = site.get('tweaks')
wb = None
raw_file = os.path.join(path, 'raw.json')
if 'cache' in source:
wb = read_source({
'fil... | def apply_chain(site, path):
| if not(os.path.exists(path)):
os.makedirs(path)
source = site['source']
destination = site['destination']
tweaks = site.get('tweaks')
wb = None
raw_file = os.path.join(path, 'raw.json')
if 'cache' in source:
wb = read_source({
'filename': raw_file
})
... | import daff
import os
from sheetsite.ids import process_ids
from sheetsite.sheet import Sheets
from sheetsite.site import Site
from sheetsite.source import read_source
from sheetsite.destination import write_destination
import shutil
def apply_chain(site, path):
| 55 | 194 | 648 | 7 | 47 | paulfitz/sheetsite | sheetsite/chain.py | Python | apply_chain | apply_chain | 11 | 96 | 11 | 12 | a10c926971b215716169af05049f9d357230ff66 | bigcode/the-stack | train |
34f957dc7252852856c19434 | train | class | class Client(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self.on_page_load)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def on_page_load(self):
self.app.quit()
| class Client(QWebPage):
| def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self.on_page_load)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def on_page_load(self):
self.app.quit()
| QUrl
from PyQt4.QtWebKit import QWebPage
import bs4 as bs
import urllib.request
import os
import datetime
###############################################################
path_of_brandwise = 'C:\\LavaWebScraper\\BrandWiseFiles\\'
###############################################################
class Client(Q... | 63 | 64 | 70 | 6 | 57 | Automation-of-New-Launches-Review/LavaWebScraper | bluboo.py | Python | Client | Client | 18 | 28 | 18 | 18 | 5c87f37319a7b6058affbed6e4ed5eca5d2d4b8c | bigcode/the-stack | train |
9097d9811ed2208c663cb24d | train | class | class NotesDialog(Toplevel):
''' `toc` means Table of Contents. '''
def __init__(
self, master, finding, header, current_person, treebard,
pressed=None, *args, **kwargs):
Toplevel.__init__(self, master, *args, **kwargs)
self.root = master
self.finding ... | class NotesDialog(Toplevel):
| ''' `toc` means Table of Contents. '''
def __init__(
self, master, finding, header, current_person, treebard,
pressed=None, *args, **kwargs):
Toplevel.__init__(self, master, *args, **kwargs)
self.root = master
self.finding = finding
self.header... | Header, Radiobutton, Frame)
from custom_combobox_widget import Combobox
from autofill import EntryAutoHilited
from toykinter_widgets import run_statusbar_tooltips
from right_click_menu import RightClickMenu, make_rc_menus
from messages_context_help import notes_dlg_help_msg, links_dlg_help_msg
from styles import ... | 255 | 256 | 6,459 | 6 | 248 | ProfessorUdGuru/treebard_gps | app/python/notes.py | Python | NotesDialog | NotesDialog | 37 | 803 | 37 | 37 | 0fcdb12249cf3de33df1e997911f4277d6a091d7 | bigcode/the-stack | train |
aa2e2731c773fa88faa581e4 | train | function | def get_bow_choices(item_choice,wp_en,x,y,disp_name):
item = None
if item_choice == 'Bow'+wp_en:
equippable_component = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=3)
item = Entity(x, y, 'D', libtcod.black, disp_name, equippable=equippable_component)
elif item_choice == 'Recurve Bow'+wp... | def get_bow_choices(item_choice,wp_en,x,y,disp_name):
| item = None
if item_choice == 'Bow'+wp_en:
equippable_component = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=3)
item = Entity(x, y, 'D', libtcod.black, disp_name, equippable=equippable_component)
elif item_choice == 'Recurve Bow'+wp_en:
equippable_component = Equippable(Equipme... | import tcod as libtcod
from components.equipment import EquipmentSlots
from components.equippable import Equippable
from entity import Entity
def get_bow_choices(item_choice,wp_en,x,y,disp_name):
| 48 | 117 | 391 | 16 | 31 | averytorres/WazHack-Clone | item_choice_definition/weapon_choices_values/bow_choices.py | Python | get_bow_choices | get_bow_choices | 7 | 28 | 7 | 7 | 1ed553312e265cea67fb6222e328ecc6cf2c68f8 | bigcode/the-stack | train |
31fbfbf1d069a4b820db5042 | train | function | def get_op_definition(instruction, doc, existing_info):
"""Generates the TableGen op definition for the given SPIR-V instruction.
Arguments:
- instruction: the instruction's SPIR-V JSON grammar
- doc: the instruction's SPIR-V HTML doc
- existing_info: a dict containing potential manually specified sect... | def get_op_definition(instruction, doc, existing_info):
| """Generates the TableGen op definition for the given SPIR-V instruction.
Arguments:
- instruction: the instruction's SPIR-V JSON grammar
- doc: the instruction's SPIR-V HTML doc
- existing_info: a dict containing potential manually specified sections for
this instruction
Returns:
- A stri... | else:
arg_type = 'OptionalAttr<I32ArrayAttr>'
elif kind == 'LiteralString' or \
kind == 'LiteralContextDependentNumber' or \
kind == 'LiteralExtInstInteger' or \
kind == 'LiteralSpecConstantOpInteger' or \
kind == 'PairLiteralIntegerIdRef' or \
kind == 'PairIdRefLiteralInteger'... | 223 | 223 | 745 | 12 | 211 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | get_op_definition | get_op_definition | 340 | 424 | 340 | 340 | 2ebcf7eaabf59f1b1d78e7d17e2e76407a66971c | bigcode/the-stack | train |
5a570072261ae6562369b467 | train | function | def update_td_op_definitions(path, instructions, docs, filter_list):
"""Updates SPIRVOps.td with newly generated op definition.
Arguments:
- path: path to SPIRVOps.td
- instructions: SPIR-V JSON grammar for all instructions
- docs: SPIR-V HTML doc for all instructions
- filter_list: a list containi... | def update_td_op_definitions(path, instructions, docs, filter_list):
| """Updates SPIRVOps.td with newly generated op definition.
Arguments:
- path: path to SPIRVOps.td
- instructions: SPIR-V JSON grammar for all instructions
- docs: SPIR-V HTML doc for all instructions
- filter_list: a list containing new opnames to include
Returns:
- A string containing all t... | )
results = rest[0]
extras = rest[1].strip(' }\n')
if extras:
extras = '\n {}\n'.format(extras)
return {
# Prefix with 'Op' to make it consistent with SPIR-V spec
'opname': 'Op{}'.format(opname),
'traits': traits,
'assembly': assembly,
'arguments': args,
'results': res... | 116 | 116 | 388 | 15 | 101 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | update_td_op_definitions | update_td_op_definitions | 482 | 528 | 482 | 482 | 9f204753dd2eddf2016a0851811201c4ab01e2d3 | bigcode/the-stack | train |
03e33c0117fb77c348e5d26b | train | function | def gen_operand_kind_enum_attr(operand_kind):
"""Generates the TableGen I32EnumAttr definition for the given operand kind.
Returns:
- The operand kind's name
- A string containing the TableGen I32EnumAttr definition
"""
if 'enumerants' not in operand_kind:
return '', ''
kind_name = operand_kind[... | def gen_operand_kind_enum_attr(operand_kind):
| """Generates the TableGen I32EnumAttr definition for the given operand kind.
Returns:
- The operand kind's name
- A string containing the TableGen I32EnumAttr definition
"""
if 'enumerants' not in operand_kind:
return '', ''
kind_name = operand_kind['kind']
kind_acronym = ''.join([c for c in k... | ublists(items, offset):
"""Split the list of items into multiple sublists.
This is to make sure the string composed from each sublist won't exceed
80 characters.
Arguments:
- items: a list of strings
- offset: the offset in calculating each sublist's length
"""
chuncks = []
chunk = []
chunk_le... | 164 | 164 | 548 | 10 | 153 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | gen_operand_kind_enum_attr | gen_operand_kind_enum_attr | 112 | 160 | 112 | 112 | d7d4ed183102e35de031b3728e9544e2b0af4682 | bigcode/the-stack | train |
c7c49def0d0815f72081eed1 | train | function | def map_spec_operand_to_ods_argument(operand):
"""Maps a operand in SPIR-V JSON spec to an op argument in ODS.
Arguments:
- A dict containing the operand's kind, quantifier, and name
Returns:
- A string containing both the type and name for the argument
"""
kind = operand['kind']
quantifier = oper... | def map_spec_operand_to_ods_argument(operand):
| """Maps a operand in SPIR-V JSON spec to an op argument in ODS.
Arguments:
- A dict containing the operand's kind, quantifier, and name
Returns:
- A string containing both the type and name for the argument
"""
kind = operand['kind']
quantifier = operand.get('quantifier', '')
# These instructio... | # Only keep the definitions from now on
defs = [enum[1] for enum in defs]
# Substitute the old section
content = content[0] + AUTOGEN_ENUM_SECTION_MARKER + '\n\n' + \
'\n\n'.join(defs) + "\n\n// End " + AUTOGEN_ENUM_SECTION_MARKER \
+ content[2];
with open(path, 'w') as f:
f.write(content)
... | 163 | 163 | 545 | 11 | 152 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | map_spec_operand_to_ods_argument | map_spec_operand_to_ods_argument | 282 | 337 | 282 | 282 | 3fc83c64f3832f1ebf399c36b78d021bb52e973d | bigcode/the-stack | train |
34e6ee8a65fd4e9b1b8cde5c | train | function | def get_spirv_doc_from_html_spec():
"""Extracts instruction documentation from SPIR-V HTML spec.
Returns:
- A dict mapping from instruction opcode to documentation.
"""
response = requests.get(SPIRV_HTML_SPEC_URL)
spec = response.content
from bs4 import BeautifulSoup
spirv = BeautifulSoup(spec, 'htm... | def get_spirv_doc_from_html_spec():
| """Extracts instruction documentation from SPIR-V HTML spec.
Returns:
- A dict mapping from instruction opcode to documentation.
"""
response = requests.get(SPIRV_HTML_SPEC_URL)
spec = response.content
from bs4 import BeautifulSoup
spirv = BeautifulSoup(spec, 'html.parser')
section_anchor = spirv... | -----\n\n'
AUTOGEN_ENUM_SECTION_MARKER = 'enum section. Generated from SPIR-V spec; DO NOT MODIFY!'
AUTOGEN_OPCODE_SECTION_MARKER = (
'opcode section. Generated from SPIR-V spec; DO NOT MODIFY!')
def get_spirv_doc_from_html_spec():
| 63 | 64 | 195 | 10 | 54 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | get_spirv_doc_from_html_spec | get_spirv_doc_from_html_spec | 42 | 65 | 42 | 42 | f0f21bbe9f66349ea12b082a811e75cc33f06e23 | bigcode/the-stack | train |
854bad76a6c7606413a7b58a | train | function | def update_td_enum_attrs(path, operand_kinds, filter_list):
"""Updates SPIRBase.td with new generated enum definitions.
Arguments:
- path: the path to SPIRBase.td
- operand_kinds: a list containing all operand kinds' grammar
- filter_list: a list containing new enums to add
"""
with open(path, 'r')... | def update_td_enum_attrs(path, operand_kinds, filter_list):
| """Updates SPIRBase.td with new generated enum definitions.
Arguments:
- path: the path to SPIRBase.td
- operand_kinds: a list containing all operand kinds' grammar
- filter_list: a list containing new enums to add
"""
with open(path, 'r') as f:
content = f.read()
content = content.split(AUT... | : inst['opcode'])
opcode = gen_opcode(filter_instrs)
# Substitute the opcode
content = content[0] + AUTOGEN_OPCODE_SECTION_MARKER + '\n\n' + \
opcode + '\n\n// End ' + AUTOGEN_OPCODE_SECTION_MARKER \
+ content[2]
with open(path, 'w') as f:
f.write(content)
def update_td_enum_attrs(path, op... | 96 | 96 | 322 | 14 | 82 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | update_td_enum_attrs | update_td_enum_attrs | 239 | 272 | 239 | 239 | 222ac430affd2e26370ac22e2f408516aa00aba6 | bigcode/the-stack | train |
c46d1c74b1acbbd9f9978792 | train | function | def gen_opcode(instructions):
""" Generates the TableGen definition to map opname to opcode
Returns:
- A string containing the TableGen SPV_OpCode definition
"""
max_len = max([len(inst['opname']) for inst in instructions])
def_fmt_str = 'def SPV_OC_{name} {colon:>{offset}} '\
'I32EnumAttrCa... | def gen_opcode(instructions):
| """ Generates the TableGen definition to map opname to opcode
Returns:
- A string containing the TableGen SPV_OpCode definition
"""
max_len = max([len(inst['opname']) for inst in instructions])
def_fmt_str = 'def SPV_OC_{name} {colon:>{offset}} '\
'I32EnumAttrCase<"{name}", {value}>;'
opco... | \n{cases}\n ]> {{\n'\
' let returnType = "::mlir::spirv::{name}";\n'\
' let convertFromStorage = '\
'"static_cast<::mlir::spirv::{name}>($_self.getInt())";\n'\
' let cppNamespace = "::mlir::spirv";\n}}'.format(
name=kind_name, cases=case_names)
return kind_name, case_defs... | 120 | 121 | 406 | 6 | 113 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | gen_opcode | gen_opcode | 163 | 200 | 163 | 163 | 932317a343de0663ef1b3db9aa7a0135399663c9 | bigcode/the-stack | train |
2d4f04f27575e11b070f7983 | train | function | def update_td_opcodes(path, instructions, filter_list):
"""Updates SPIRBase.td with new generated opcode cases.
Arguments:
- path: the path to SPIRBase.td
- instructions: a list containing all SPIR-V instructions' grammar
- filter_list: a list containing new opnames to add
"""
with open(path, 'r')... | def update_td_opcodes(path, instructions, filter_list):
| """Updates SPIRBase.td with new generated opcode cases.
Arguments:
- path: the path to SPIRBase.td
- instructions: a list containing all SPIR-V instructions' grammar
- filter_list: a list containing new opnames to add
"""
with open(path, 'r') as f:
content = f.read()
content = content.split... | '\
' let convertFromStorage = '\
'"static_cast<::mlir::spirv::{name}>($_self.getInt())";\n'\
' let cppNamespace = "::mlir::spirv";\n}}'.format(
name='Opcode', lst=opcode_list)
return opcode_str + '\n\n' + enum_attr
def update_td_opcodes(path, instructi... | 90 | 90 | 301 | 12 | 77 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | update_td_opcodes | update_td_opcodes | 203 | 236 | 203 | 203 | 708b8db5e07fd0384e0abdf613dd1f05bed22634 | bigcode/the-stack | train |
b0992ff33dc24680ed2c8d64 | train | function | def snake_casify(name):
"""Turns the given name to follow snake_case convension."""
name = re.sub('\W+', '', name).split()
name = [s.lower() for s in name]
return '_'.join(name)
| def snake_casify(name):
| """Turns the given name to follow snake_case convension."""
name = re.sub('\W+', '', name).split()
name = [s.lower() for s in name]
return '_'.join(name)
| _MARKER + '\n\n' + \
'\n\n'.join(defs) + "\n\n// End " + AUTOGEN_ENUM_SECTION_MARKER \
+ content[2];
with open(path, 'w') as f:
f.write(content)
def snake_casify(name):
| 64 | 64 | 52 | 7 | 57 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | snake_casify | snake_casify | 275 | 279 | 275 | 275 | 978532690a64eb064ebb37f8e9c5e5293bcdb868 | bigcode/the-stack | train |
797297f04e3c18d1bda94191 | train | function | def split_list_into_sublists(items, offset):
"""Split the list of items into multiple sublists.
This is to make sure the string composed from each sublist won't exceed
80 characters.
Arguments:
- items: a list of strings
- offset: the offset in calculating each sublist's length
"""
chuncks = []
... | def split_list_into_sublists(items, offset):
| """Split the list of items into multiple sublists.
This is to make sure the string composed from each sublist won't exceed
80 characters.
Arguments:
- items: a list of strings
- offset: the offset in calculating each sublist's length
"""
chuncks = []
chunk = []
chunk_len = 0
for item in ite... | containing all instructions' grammar
"""
response = requests.get(SPIRV_JSON_SPEC_URL)
spec = response.content
import json
spirv = json.loads(spec)
return spirv['operand_kinds'], spirv['instructions']
def split_list_into_sublists(items, offset):
| 64 | 64 | 159 | 11 | 53 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | split_list_into_sublists | split_list_into_sublists | 84 | 109 | 84 | 84 | 4053dbaf97234b129caac8420e35378d04ddf6ea | bigcode/the-stack | train |
50d48854c7b0edd678ed1bae | train | function | def get_spirv_grammar_from_json_spec():
"""Extracts operand kind and instruction grammar from SPIR-V JSON spec.
Returns:
- A list containing all operand kinds' grammar
- A list containing all instructions' grammar
"""
response = requests.get(SPIRV_JSON_SPEC_URL)
spec = response.content
import json... | def get_spirv_grammar_from_json_spec():
| """Extracts operand kind and instruction grammar from SPIR-V JSON spec.
Returns:
- A list containing all operand kinds' grammar
- A list containing all instructions' grammar
"""
response = requests.get(SPIRV_JSON_SPEC_URL)
spec = response.content
import json
spirv = json.loads(spec)
return sp... | body.tr.td.p
opname = inst_html.a['id']
# Ignore the first line, which is just the opname.
doc[opname] = inst_html.text.split('\n', 1)[1].strip()
return doc
def get_spirv_grammar_from_json_spec():
| 64 | 64 | 98 | 11 | 52 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | get_spirv_grammar_from_json_spec | get_spirv_grammar_from_json_spec | 68 | 81 | 68 | 68 | 3d4dd51fd3f17f38df50ae6563ee0f0628623a02 | bigcode/the-stack | train |
16a7d0ac09798fae983f93b5 | train | function | def extract_td_op_info(op_def):
"""Extracts potentially manually specified sections in op's definition.
Arguments: - A string containing the op's TableGen definition
- doc: the instruction's SPIR-V HTML doc
Returns:
- A dict containing potential manually specified sections
"""
# Get opname
opname ... | def extract_td_op_info(op_def):
| """Extracts potentially manually specified sections in op's definition.
Arguments: - A string containing the op's TableGen definition
- doc: the instruction's SPIR-V HTML doc
Returns:
- A dict containing potential manually specified sections
"""
# Get opname
opname = [o[8:-2] for o in re.findall('... | ('assembly', None)
if assembly is None:
assembly = ' ``` {.ebnf}\n'\
' [TODO]\n'\
' ```\n\n'\
' For example:\n\n'\
' ```\n'\
' [TODO]\n'\
' ```\n '
return fmt_str.format(
opname=opname,
t... | 143 | 144 | 480 | 8 | 135 | atulkulk/mlir | utils/spirv/gen_spirv_dialect.py | Python | extract_td_op_info | extract_td_op_info | 427 | 479 | 427 | 427 | 6a9ede042c4645c92839fcb7e4f33cbc35e7d80d | bigcode/the-stack | train |
b58bf5f4304329b949f3362f | train | function | def build_predictions_dictionary(data, class_label_map):
"""Builds a predictions dictionary from predictions data in CSV file.
Args:
data: Pandas DataFrame with the predictions data for a single image.
class_label_map: Class labelmap from string label name to an integer.
Returns:
Dictionary with key... | def build_predictions_dictionary(data, class_label_map):
| """Builds a predictions dictionary from predictions data in CSV file.
Args:
data: Pandas DataFrame with the predictions data for a single image.
class_label_map: Class labelmap from string label name to an integer.
Returns:
Dictionary with keys suitable for passing to
OpenImagesDetectionChalleng... | ['LabelName'].map(lambda x: class_label_map[x]).as_matrix(),
standard_fields.InputDataFields.groundtruth_group_of:
data_boxes['IsGroupOf'].as_matrix().astype(int),
standard_fields.InputDataFields.groundtruth_image_classes:
data_labels['LabelName'].map(lambda x: class_label_map[x])
... | 87 | 87 | 290 | 10 | 77 | Loonride/deeplens-cv | dlcv/object_detection/tensorflow_detect/metrics/oid_od_challenge_evaluation_utils.py | Python | build_predictions_dictionary | build_predictions_dictionary | 63 | 90 | 63 | 63 | fd0c0405875e5921d453454b14b26c358b4147c4 | bigcode/the-stack | train |
019686a4351a49061fa0fb47 | train | function | def build_groundtruth_boxes_dictionary(data, class_label_map):
"""Builds a groundtruth dictionary from groundtruth data in CSV file.
Args:
data: Pandas DataFrame with the groundtruth data for a single image.
class_label_map: Class labelmap from string label name to an integer.
Returns:
A dictionary ... | def build_groundtruth_boxes_dictionary(data, class_label_map):
| """Builds a groundtruth dictionary from groundtruth data in CSV file.
Args:
data: Pandas DataFrame with the groundtruth data for a single image.
class_label_map: Class labelmap from string label name to an integer.
Returns:
A dictionary with keys suitable for passing to
OpenImagesDetectionChalle... | to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================... | 119 | 119 | 397 | 12 | 106 | Loonride/deeplens-cv | dlcv/object_detection/tensorflow_detect/metrics/oid_od_challenge_evaluation_utils.py | Python | build_groundtruth_boxes_dictionary | build_groundtruth_boxes_dictionary | 25 | 60 | 25 | 25 | 66e91d943fed5631110311eaca798d7c8d7c5e50 | bigcode/the-stack | train |
0dd4ad17a27a294fedb0df2c | train | function | def _connection_checker(func):
"""Decorator to check session has expired or not."""
@functools.wraps(func)
def inner_connection_checker(self, *args, **kwargs):
LOG.debug('in _connection_checker')
for attempts in range(5):
try:
return func(self, *args, **kwargs)
... | def _connection_checker(func):
| """Decorator to check session has expired or not."""
@functools.wraps(func)
def inner_connection_checker(self, *args, **kwargs):
LOG.debug('in _connection_checker')
for attempts in range(5):
try:
return func(self, *args, **kwargs)
except exception.Volu... | ,
ignore_errors=ignore_errors
)
@utils.synchronized('_attach_volume')
def _attach_volume(self, context, volume, properties, remote=False):
return super(QnapISCSIDriver, self)._attach_volume(context, volume,
properties, remot... | 64 | 64 | 164 | 6 | 58 | lightsey/cinder | cinder/volume/drivers/qnap.py | Python | _connection_checker | _connection_checker | 1,114 | 1,135 | 1,114 | 1,114 | f674debf3ff814986b425419968908139bd83fd6 | bigcode/the-stack | train |
7437fa6acfb81b40047bd739 | train | class | class Util(object):
_dictCondRetriveFormCache = {}
_dictCacheRetriveFormCache = {}
_condRetriveFormCache = threading.Condition()
@classmethod
def retriveFormCache(cls, lockKey, func, keepTime=0):
cond = None
cls._condRetriveFormCache.acquire()
try:
if (lockKey n... | class Util(object):
| _dictCondRetriveFormCache = {}
_dictCacheRetriveFormCache = {}
_condRetriveFormCache = threading.Condition()
@classmethod
def retriveFormCache(cls, lockKey, func, keepTime=0):
cond = None
cls._condRetriveFormCache.acquire()
try:
if (lockKey not in cls._dictCondR... | return_ip = []
ip_list = root.find('func').find('ownContent')
ip_list_tree = ip_list.findall('IPInfo')
for IP in ip_list_tree:
ipv4 = (IP.find('IP').find('IP1').text + '.' +
IP.find('IP').find('IP2').text + '.' +
... | 133 | 133 | 446 | 4 | 128 | lightsey/cinder | cinder/volume/drivers/qnap.py | Python | Util | Util | 2,167 | 2,219 | 2,167 | 2,167 | 635addbeb93370b0bba5b2819371697b939db1d4 | bigcode/the-stack | train |
d24070a49011d03c066393f2 | train | class | @interface.volumedriver
class QnapISCSIDriver(san.SanISCSIDriver):
"""QNAP iSCSI based cinder driver
.. code-block:: none
Version History:
1.0.0:
Initial driver (Only iSCSI).
1.2.001:
Add supports for Thin Provisioning, SSD Cache, Deduplication,
... | @interface.volumedriver
class QnapISCSIDriver(san.SanISCSIDriver):
| """QNAP iSCSI based cinder driver
.. code-block:: none
Version History:
1.0.0:
Initial driver (Only iSCSI).
1.2.001:
Add supports for Thin Provisioning, SSD Cache, Deduplication,
Compression and CHAP.
1.2.002:
Add support f... | import time
from defusedxml import cElementTree as ET
import eventlet
from oslo_concurrency import lockutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import units
import requests
import six
from six.moves import url... | 256 | 256 | 9,910 | 21 | 235 | lightsey/cinder | cinder/volume/drivers/qnap.py | Python | QnapISCSIDriver | QnapISCSIDriver | 62 | 1,111 | 62 | 63 | ba6b8a02d82d31287996c159b54479c83ce57c96 | bigcode/the-stack | train |
10366ca18a4677ac0c58fc4a | train | class | class QnapAPIExecutor(object):
"""Makes QNAP API calls for ES NAS."""
es_create_lun_lock = threading.Lock()
es_delete_lun_lock = threading.Lock()
es_lun_locks = {}
def __init__(self, *args, **kwargs):
"""Init function."""
self.sid = None
self.username = kwargs['username']
... | class QnapAPIExecutor(object):
| """Makes QNAP API calls for ES NAS."""
es_create_lun_lock = threading.Lock()
es_delete_lun_lock = threading.Lock()
es_lun_locks = {}
def __init__(self, *args, **kwargs):
"""Init function."""
self.sid = None
self.username = kwargs['username']
self.password = kwargs['p... | IDriver, self)._detach_volume(
context, attach_info,
volume, properties,
force=force, remote=remote,
ignore_errors=ignore_errors
)
@utils.synchronized('_attach_volume')
def _attach_volume(self, context, volume, properties, remote=False):
return su... | 256 | 256 | 5,311 | 7 | 248 | lightsey/cinder | cinder/volume/drivers/qnap.py | Python | QnapAPIExecutor | QnapAPIExecutor | 1,138 | 1,792 | 1,138 | 1,138 | 8469445ba8875e0a9152fcb1d85b8eb560ea8376 | bigcode/the-stack | train |
025c18a813cd5ac4deca08f4 | train | class | class QnapAPIExecutorTES(QnapAPIExecutor):
"""Makes QNAP API calls for TES NAS."""
tes_create_lun_lock = threading.Lock()
@_connection_checker
def create_lun(self, volume, pool_name, create_lun_name, reserve,
ssd_cache, compress, dedup):
"""Create lun."""
self.tes_cre... | class QnapAPIExecutorTES(QnapAPIExecutor):
| """Makes QNAP API calls for TES NAS."""
tes_create_lun_lock = threading.Lock()
@_connection_checker
def create_lun(self, volume, pool_name, create_lun_name, reserve,
ssd_cache, compress, dedup):
"""Create lun."""
self.tes_create_lun_lock.acquire()
lun_thin_al... | data=_('Create target failed'))
root = ET.fromstring(res_details['data'])
targetIndex = root.find('result').text
return targetIndex
@_connection_checker
def delete_target(self, target_index):
"""Delete target on nas."""
res_details = self._get_res_details(
... | 175 | 176 | 587 | 11 | 164 | lightsey/cinder | cinder/volume/drivers/qnap.py | Python | QnapAPIExecutorTES | QnapAPIExecutorTES | 2,093 | 2,164 | 2,093 | 2,093 | 56a570e677c0b8ce05603bbe0f044f3a4b4a093c | bigcode/the-stack | train |
901df499cc3d42ec66261f9a | train | class | class QnapAPIExecutorTS(QnapAPIExecutor):
"""Makes QNAP API calls for TS NAS."""
create_lun_lock = threading.Lock()
delete_lun_lock = threading.Lock()
lun_locks = {}
@_connection_checker
def create_lun(self, volume, pool_name, create_lun_name, reserve,
ssd_cache, compress, de... | class QnapAPIExecutorTS(QnapAPIExecutor):
| """Makes QNAP API calls for TS NAS."""
create_lun_lock = threading.Lock()
delete_lun_lock = threading.Lock()
lun_locks = {}
@_connection_checker
def create_lun(self, volume, pool_name, create_lun_name, reserve,
ssd_cache, compress, dedup):
"""Create lun."""
se... | 0':
raise exception.VolumeBackendAPIException(
data=_('Get target info failed'))
target_list = root.find('targetInfo')
target_tree = target_list.findall('row')
for target in target_tree:
if target_index == target.find('targetIndex').text:
... | 256 | 256 | 2,317 | 11 | 244 | lightsey/cinder | cinder/volume/drivers/qnap.py | Python | QnapAPIExecutorTS | QnapAPIExecutorTS | 1,795 | 2,090 | 1,795 | 1,795 | 3c202c2dd6bb7437fdad9f57d9ebfa7002ec120f | bigcode/the-stack | train |
6cf3a68970c778fbaf101871 | train | class | class Command(BaseCommand):
"""
Required command class for the custom Django send_email_reminders command.
The script should run once every hour, preferably near the beginning of the hour.
"""
def handle(self, *args, **options):
"""
Send an email to each user that should get a remi... | class Command(BaseCommand):
| """
Required command class for the custom Django send_email_reminders command.
The script should run once every hour, preferably near the beginning of the hour.
"""
def handle(self, *args, **options):
"""
Send an email to each user that should get a reminder with a customised messa... | """Module for the custom Django send_email_reminders command."""
from datetime import datetime
from datetime import time
from time import perf_counter
import pytz
from django.conf import settings
from django.core.mail import send_mail
from django.core.management import BaseCommand
from django.templatetags.static impor... | 110 | 256 | 1,407 | 5 | 104 | bexmckinnon/codewof | codewof/users/management/commands/send_email_reminders.py | Python | Command | Command | 19 | 175 | 19 | 19 | 68f69da1925773a484c9dc550b69e15ac920ab9c | bigcode/the-stack | train |
8b65dd24826a8451701d2644 | train | function | def scan(dirs):
'''
Return a list of importable files
'''
ret = collections.OrderedDict()
ret['python'] = collections.OrderedDict()
ret['cython'] = collections.OrderedDict()
ret['ext'] = collections.OrderedDict()
ret['imp'] = collections.OrderedDict()
for dir_ in dirs:
for fn... | def scan(dirs):
| '''
Return a list of importable files
'''
ret = collections.OrderedDict()
ret['python'] = collections.OrderedDict()
ret['cython'] = collections.OrderedDict()
ret['ext'] = collections.OrderedDict()
ret['imp'] = collections.OrderedDict()
for dir_ in dirs:
for fn_ in os.listdir(... | lib
import collections
PY_END = ('.py', '.pyc', '.pyo')
PYEXT_END = tuple(importlib.machinery.EXTENSION_SUFFIXES)
CYTHON_END = ('.pyx',)
SKIP_DIRNAMES = ('__pycache__',)
def scan(dirs):
| 64 | 64 | 102 | 5 | 59 | Akm0d/pop | pop/scanner.py | Python | scan | scan | 16 | 28 | 16 | 16 | 09eaff4f6a74a1e81a45feb6a91df1b5ab609a89 | bigcode/the-stack | train |
cf1b9ae3096d10155a6c6445 | train | function | def _apply_scan(ret, dir_, fn_):
'''
Convert the scan data into
'''
if fn_.startswith('_'):
return
if os.path.basename(dir_) in SKIP_DIRNAMES:
return
full = os.path.join(dir_, fn_)
if '.' not in full:
return
bname = full[:full.rindex('.')]
if fn_.endswith(PY_E... | def _apply_scan(ret, dir_, fn_):
| '''
Convert the scan data into
'''
if fn_.startswith('_'):
return
if os.path.basename(dir_) in SKIP_DIRNAMES:
return
full = os.path.join(dir_, fn_)
if '.' not in full:
return
bname = full[:full.rindex('.')]
if fn_.endswith(PY_END):
if bname not in ret[... | ret['ext'] = collections.OrderedDict()
ret['imp'] = collections.OrderedDict()
for dir_ in dirs:
for fn_ in os.listdir(dir_):
_apply_scan(ret, dir_, fn_)
return ret
def _apply_scan(ret, dir_, fn_):
| 64 | 64 | 186 | 11 | 52 | Akm0d/pop | pop/scanner.py | Python | _apply_scan | _apply_scan | 31 | 51 | 31 | 31 | 24ff2b40ef93e4d6cc32f9bba9dc455a7882769c | bigcode/the-stack | train |
dcbe9186af207ba2d1b9215d | train | function | def build_single_tx(amount, fees, outputs, addr, privkey, network):
'''
Builds a tx for which:
* sum(Tx_ins) = amount + fees
* Tx_outs = outputs
* Tx_ins are owned by addr/privkey
Parameters:
amount = amount proposed by the buyer
fees = fees proposed b... | def build_single_tx(amount, fees, outputs, addr, privkey, network):
| '''
Builds a tx for which:
* sum(Tx_ins) = amount + fees
* Tx_outs = outputs
* Tx_ins are owned by addr/privkey
Parameters:
amount = amount proposed by the buyer
fees = fees proposed by the buyer
outputs = outputs proposed by the seller
... | '''
if (addr is None) or (len(addr) == 0): return 0
utxos = blockr_unspent(TESTNET, addr)
return sum([utxo['value'] for utxo in utxos]) / 100000000.0
def build_single_tx(amount, fees, outputs, addr, privkey, network):
| 78 | 78 | 260 | 17 | 60 | LaurentMT/pybargain_demo_client | pybargain_demo_client/helpers/wallet_helper.py | Python | build_single_tx | build_single_tx | 23 | 50 | 23 | 23 | 0c217b7585998a27beebb145b353267fd87eae08 | bigcode/the-stack | train |
8bc732b53d5284c9a83275c0 | train | function | def get_balance(addr):
'''
Gets balance (in satoshis) associated to a list of addresses
Parameters:
addr = a list of testnet addresses
'''
if (addr is None) or (len(addr) == 0): return 0
utxos = blockr_unspent(TESTNET, addr)
return sum([utxo['value'] for utxo in utxos]) / 100000... | def get_balance(addr):
| '''
Gets balance (in satoshis) associated to a list of addresses
Parameters:
addr = a list of testnet addresses
'''
if (addr is None) or (len(addr) == 0): return 0
utxos = blockr_unspent(TESTNET, addr)
return sum([utxo['value'] for utxo in utxos]) / 100000000.0
| #!/usr/bin/env python
from bitcoin.transaction import select
from pybargain_protocol.constants import TESTNET
from pybargain_protocol.helpers.bc_api import blockr_unspent
from pybargain_protocol.helpers.build_check_tx import build_tx_with_change
'''
UTILITY METHODS
'''
def get_balance(addr):
| 64 | 64 | 97 | 5 | 59 | LaurentMT/pybargain_demo_client | pybargain_demo_client/helpers/wallet_helper.py | Python | get_balance | get_balance | 11 | 20 | 11 | 11 | c60c87b88ac9a2aad88b3f54350c995e2b395d4a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.