code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def expr_deserializer(
expr: str | pl.Expr | list[pl.Expr] | None,
) -> pl.Expr | list[pl.Expr] | None:
"""Deserialize a polars expression or list thereof from json.
This is applied both during deserialization and validation.
"""
if expr is None:
return None
elif isinstance(expr, pl.Exp... | Deserialize a polars expression or list thereof from json.
This is applied both during deserialization and validation.
| expr_deserializer | python | JakobGM/patito | src/patito/_pydantic/column_info.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/column_info.py | MIT |
def expr_or_col_name_deserializer(expr: str | pl.Expr | None) -> pl.Expr | str | None:
"""Deserialize a polars expression or column name from json.
This is applied both during deserialization and validation.
"""
if expr is None:
return None
elif isinstance(expr, pl.Expr):
return exp... | Deserialize a polars expression or column name from json.
This is applied both during deserialization and validation.
| expr_or_col_name_deserializer | python | JakobGM/patito | src/patito/_pydantic/column_info.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/column_info.py | MIT |
def __repr__(self) -> str:
"""Print only Field attributes whose values are not default (mainly None)."""
not_default_field = {
field: getattr(self, field)
for field in self.model_fields
if getattr(self, field) is not self.model_fields[field].default
}
... | Print only Field attributes whose values are not default (mainly None). | __repr__ | python | JakobGM/patito | src/patito/_pydantic/column_info.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/column_info.py | MIT |
def __repr_args__(self) -> "ReprArgs":
"""Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
Can either return:
* name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
* or, just values, e.g.: `[(None, 'foo'), (No... | Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
Can either return:
* name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
* or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
| __repr_args__ | python | JakobGM/patito | src/patito/_pydantic/repr.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/repr.py | MIT |
def __pretty__(
self, fmt: Callable[[Any], Any], **kwargs: Any
) -> Generator[Any, None, None]:
"""Used by devtools (https://python-devtools.helpmanual.io/) to provide a human readable representations of objects."""
yield self.__repr_name__() + "("
yield 1
for name, value in ... | Used by devtools (https://python-devtools.helpmanual.io/) to provide a human readable representations of objects. | __pretty__ | python | JakobGM/patito | src/patito/_pydantic/repr.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/repr.py | MIT |
def display_as_type(obj: Any) -> str:
"""Pretty representation of a type, should be as close as possible to the original type definition string.
Takes some logic from `typing._type_repr`.
"""
if isinstance(obj, types.FunctionType):
return obj.__name__
elif obj is ...:
return "..."
... | Pretty representation of a type, should be as close as possible to the original type definition string.
Takes some logic from `typing._type_repr`.
| display_as_type | python | JakobGM/patito | src/patito/_pydantic/repr.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/repr.py | MIT |
def schema_for_model(cls: type[ModelType]) -> dict[str, dict[str, Any]]:
"""Return schema properties where definition references have been resolved.
Returns:
Field information as a dictionary where the keys are field names and the
values are dictionaries containing metadata information abou... | Return schema properties where definition references have been resolved.
Returns:
Field information as a dictionary where the keys are field names and the
values are dictionaries containing metadata information about the field
itself.
Raises:
TypeError: if a field is an... | schema_for_model | python | JakobGM/patito | src/patito/_pydantic/schema.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/schema.py | MIT |
def validate_polars_dtype(
annotation: type[Any] | None,
dtype: DataType | DataTypeClass | None,
column: str | None = None,
) -> None:
"""Check that the polars dtype is valid for the given annotation. Raises ValueError if not.
Args:
annotation (type[Any] | None): python type annotation
... | Check that the polars dtype is valid for the given annotation. Raises ValueError if not.
Args:
annotation (type[Any] | None): python type annotation
dtype (DataType | DataTypeClass | None): polars dtype
column (Optional[str], optional): column name. Defaults to None.
| validate_polars_dtype | python | JakobGM/patito | src/patito/_pydantic/dtypes/dtypes.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/dtypes/dtypes.py | MIT |
def validate_annotation(
annotation: type[Any] | Any | None, column: str | None = None
) -> None:
"""Check that the provided annotation has polars/patito support (we can resolve it to a default dtype). Raises ValueError if not.
Args:
annotation (type[Any] | None): python type annotation
col... | Check that the provided annotation has polars/patito support (we can resolve it to a default dtype). Raises ValueError if not.
Args:
annotation (type[Any] | None): python type annotation
column (Optional[str], optional): column name. Defaults to None.
| validate_annotation | python | JakobGM/patito | src/patito/_pydantic/dtypes/dtypes.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/dtypes/dtypes.py | MIT |
def is_optional(type_annotation: type[Any] | Any | None) -> bool:
"""Return True if the given type annotation is an Optional annotation.
Args:
type_annotation: The type annotation to be checked.
Returns:
True if the outermost type is Optional.
"""
return (get_origin(type_annotatio... | Return True if the given type annotation is an Optional annotation.
Args:
type_annotation: The type annotation to be checked.
Returns:
True if the outermost type is Optional.
| is_optional | python | JakobGM/patito | src/patito/_pydantic/dtypes/utils.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/dtypes/utils.py | MIT |
def unwrap_optional(type_annotation: type[Any] | Any) -> type:
"""Return the inner, wrapped type of an Optional.
Is a no-op for non-Optional types.
Args:
type_annotation: The type annotation to be dewrapped.
Returns:
The input type, but with the outermost Optional removed.
"""
... | Return the inner, wrapped type of an Optional.
Is a no-op for non-Optional types.
Args:
type_annotation: The type annotation to be dewrapped.
Returns:
The input type, but with the outermost Optional removed.
| unwrap_optional | python | JakobGM/patito | src/patito/_pydantic/dtypes/utils.py | https://github.com/JakobGM/patito/blob/master/src/patito/_pydantic/dtypes/utils.py | MIT |
def test_valids_basic_annotations() -> None:
"""Test type annotations match polars dtypes."""
# base types
assert DtypeResolver(str).valid_polars_dtypes() == STRING_DTYPES
assert DtypeResolver(int).valid_polars_dtypes() == DataTypeGroup(INTEGER_DTYPES)
assert DtypeResolver(float).valid_polars_dtypes... | Test type annotations match polars dtypes. | test_valids_basic_annotations | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_valids_nested_annotations() -> None:
"""Test type annotations match nested polars types like List."""
assert len(DtypeResolver(list).valid_polars_dtypes()) == 0 # needs inner annotation
assert (
DtypeResolver(tuple).valid_polars_dtypes()
== DtypeResolver(list).valid_polars_dtypes()... | Test type annotations match nested polars types like List. | test_valids_nested_annotations | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_dtype_validation() -> None:
"""Ensure python types match polars types."""
validate_polars_dtype(int, pl.Int16) # no issue
with pytest.raises(ValueError, match="Invalid dtype"):
validate_polars_dtype(int, pl.Float64)
with pytest.raises(ValueError, match="Invalid dtype"):
valid... | Ensure python types match polars types. | test_dtype_validation | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_defaults_basic_annotations() -> None:
"""Ensure python types resolve to largest polars type."""
# base types
assert DtypeResolver(str).default_polars_dtype() == pl.String
assert DtypeResolver(int).default_polars_dtype() == pl.Int64
assert DtypeResolver(float).default_polars_dtype() == pl.Fl... | Ensure python types resolve to largest polars type. | test_defaults_basic_annotations | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_defaults_nested_annotations() -> None:
"""Ensure python nested types fallback to largest nested polars type."""
assert DtypeResolver(list).default_polars_dtype() is None # needs inner annotation
assert DtypeResolver(list[str]).default_polars_dtype() == pl.List(pl.String)
assert DtypeResolver(... | Ensure python nested types fallback to largest nested polars type. | test_defaults_nested_annotations | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_annotation_validation() -> None:
"""Check that python types are resolveable."""
validate_annotation(int) # no issue
validate_annotation(Optional[int])
with pytest.raises(ValueError, match="Valid dtypes are:"):
validate_annotation(Union[int, float])
# Unions are unsupported as act... | Check that python types are resolveable. | test_annotation_validation | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_generation_of_unique_data() -> None:
"""Example data generators should be able to generate unique data."""
class UniqueModel(pt.Model):
bool_column: bool
string_column: str = pt.Field(unique=True)
int_column: int = pt.Field(unique=True)
float_column: int = pt.Field(uniq... | Example data generators should be able to generate unique data. | test_generation_of_unique_data | python | JakobGM/patito | tests/test_dummy_data.py | https://github.com/JakobGM/patito/blob/master/tests/test_dummy_data.py | MIT |
def test_enum_field_example_values() -> None:
"""It should produce correct example values for enums."""
class DefaultEnumModel(pt.Model):
row_number: int
# Here the first value will be used as the example value
enum_field: Literal["a", "b", "c"]
# Here the default value will be ... | It should produce correct example values for enums. | test_enum_field_example_values | python | JakobGM/patito | tests/test_dummy_data.py | https://github.com/JakobGM/patito/blob/master/tests/test_dummy_data.py | MIT |
def test_nested_models() -> None:
"""It should be possible to create nested models."""
class NestedModel(pt.Model):
nested_field: int
class ParentModel1(pt.Model):
parent_field: int
nested_model: NestedModel
example_model = ParentModel1.example()
example_df = ParentModel1.... | It should be possible to create nested models. | test_nested_models | python | JakobGM/patito | tests/test_dummy_data.py | https://github.com/JakobGM/patito/blob/master/tests/test_dummy_data.py | MIT |
def test_instantiating_model_from_row() -> None:
"""You should be able to instantiate models from rows."""
class Model(pt.Model):
a: int
polars_dataframe = pl.DataFrame({"a": [1]})
assert Model.from_row(polars_dataframe).a == 1
# Anything besides a dataframe / row should raise TypeError
... | You should be able to instantiate models from rows. | test_instantiating_model_from_row | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_instantiation_from_pandas_row() -> None:
"""You should be able to instantiate models from pandas rows."""
pytest.importorskip("pandas")
class Model(pt.Model):
a: int
polars_dataframe = pl.DataFrame({"a": [1]})
assert Model.from_row(polars_dataframe).a == 1
pandas_dataframe = ... | You should be able to instantiate models from pandas rows. | test_instantiation_from_pandas_row | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_dataframe_class_creation() -> None:
"""Each model should get a custom DataFrame class."""
class CustomModel(pt.Model):
a: int
# The DataFrame class is a sub-class of patito.DataFrame
assert issubclass(CustomModel.DataFrame, pt.DataFrame)
# The LazyFrame class is a sub-class... | Each model should get a custom DataFrame class. | test_model_dataframe_class_creation | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_mapping_to_polars_dtypes() -> None:
"""Model fields should be mappable to polars dtypes."""
assert CompleteModel.dtypes == {
"str_column": pl.String(),
"int_column": pl.Int64(),
"float_column": pl.Float64(),
"bool_column": pl.Boolean(),
"date_column": pl.Date(),
... | Model fields should be mappable to polars dtypes. | test_mapping_to_polars_dtypes | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_joins() -> None:
"""It should produce models compatible with join statements."""
class Left(pt.Model):
left: int = pt.Field(gt=20)
opt_left: Optional[int] = None
class Right(pt.Model):
right: int = pt.Field(gt=20)
opt_right: Optional[int] = None
def test... | It should produce models compatible with join statements. | test_model_joins | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_validator(model: type[pt.Model]) -> None:
"""Test if all field validators have been included correctly."""
with pytest.raises(ValidationError) as e:
model(left=1, opt_left=1, right=1, opt_right=1)
pattern = re.compile(r"Input should be greater than 20")
assert ... | Test if all field validators have been included correctly. | test_model_validator | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_selects() -> None:
"""It should produce models compatible with select statements."""
class MyModel(pt.Model):
a: Optional[int]
b: int = pt.Field(gt=10)
MySubModel = MyModel.select("b")
assert MySubModel.columns == ["b"]
MySubModel(b=11)
with pytest.raises(Validat... | It should produce models compatible with select statements. | test_model_selects | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_prefix_and_suffix() -> None:
"""It should produce models where all fields have been prefixed/suffixed."""
class MyModel(pt.Model):
a: Optional[int]
b: str
NewModel = MyModel.prefix("pre_").suffix("_post")
assert sorted(NewModel.columns) == ["pre_a_post", "pre_b_post"]
... | It should produce models where all fields have been prefixed/suffixed. | test_model_prefix_and_suffix | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_field_renaming() -> None:
"""It should be able to change its field names."""
class MyModel(pt.Model):
a: Optional[int]
b: str
NewModel = MyModel.rename({"b": "B"})
assert sorted(NewModel.columns) == ["B", "a"]
with pytest.raises(
ValueError,
match="T... | It should be able to change its field names. | test_model_field_renaming | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_field_dropping() -> None:
"""Model should be able to drop a subset of its fields."""
class MyModel(pt.Model):
a: int
b: int
c: int
assert sorted(MyModel.drop("c").columns) == ["a", "b"]
assert MyModel.drop(["b", "c"]).columns == ["a"] | Model should be able to drop a subset of its fields. | test_model_field_dropping | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_with_fields() -> None:
"""It should allow whe user to add additional fields."""
class MyModel(pt.Model):
a: int
ExpandedModel = MyModel.with_fields(
b=(int, ...),
c=(int, None),
d=(int, pt.Field(gt=10)),
e=(Optional[int], None),
)
assert sorted(Expa... | It should allow whe user to add additional fields. | test_with_fields | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_enum_annotated_field() -> None:
"""It should use values of enums to infer types."""
class ABCEnum(enum.Enum):
ONE = "a"
TWO = "b"
THREE = "c"
class EnumModel(pt.Model):
column: ABCEnum
assert EnumModel.dtypes["column"] == pl.Enum(["a", "b", "c"])
assert En... | It should use values of enums to infer types. | test_enum_annotated_field | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_schema() -> None:
"""Ensure pt.Field properties are correctly applied to model."""
class Model(pt.Model):
a: int = pt.Field(ge=0, unique=True)
schema = Model.model_schema
def validate_model_schema(schema) -> None:
assert set(schema) == {"properties", "required", "type",... | Ensure pt.Field properties are correctly applied to model. | test_model_schema | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_conflicting_type_dtype() -> None:
"""Ensure model annotation is compatible with Field dtype."""
with pytest.raises(ValueError, match="Invalid dtype String"):
class Test1(pt.Model):
foo: int = pt.Field(dtype=pl.String)
Test1.validate_schema()
with pytest.raises(ValueEr... | Ensure model annotation is compatible with Field dtype. | test_conflicting_type_dtype | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_polars_python_type_harmonization() -> None:
"""Ensure datetime types are correctly transformed to polars types."""
class Test(pt.Model):
date: datetime = pt.Field(dtype=pl.Datetime(time_unit="us"))
time: time
assert Test.valid_dtypes["date"] == {pl.Datetime(time_unit="us")}
as... | Ensure datetime types are correctly transformed to polars types. | test_polars_python_type_harmonization | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_column_infos() -> None:
"""Test that pt.Field and ColumnInfo properties match."""
class Model(pt.Model):
a: int
b: int = pt.Field(constraints=[(pl.col("b") < 10)])
c: int = pt.Field(derived_from=pl.col("a") + pl.col("b"))
d: int = pt.Field(dtype=pl.UInt8)
e: int... | Test that pt.Field and ColumnInfo properties match. | test_column_infos | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_validation_alias():
"""Test that validation alias works in pt.Field.
TODO: Not sure if this actually tests anything correctly.
"""
class AliasModel(pt.Model):
my_val_a: int = pt.Field(validation_alias="myValA")
my_val_b: int = pt.Field(validation_alias=AliasChoices("my_val_b",... | Test that validation alias works in pt.Field.
TODO: Not sure if this actually tests anything correctly.
| test_validation_alias | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_json_schema_extra_is_extended_when_it_exists() -> None:
"""Ensure that the json_schema_extra property is extended with column_info when it is set from the model field."""
class Model(pt.Model):
a: int
b: int = pt.Field(
json_schema_extra={"client_column_metadata": {"group1"... | Ensure that the json_schema_extra property is extended with column_info when it is set from the model field. | test_json_schema_extra_is_extended_when_it_exists | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_dataframe_get_method() -> None:
"""You should be able to retrieve a single row and cast to model."""
class Product(pt.Model):
product_id: int = pt.Field(unique=True)
price: float
df = pt.DataFrame({"product_id": [1, 2], "price": [9.99, 19.99]})
# Validation does nothing, as n... | You should be able to retrieve a single row and cast to model. | test_dataframe_get_method | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_dataframe_set_model_method() -> None:
"""You should be able to set the associated model of a dataframe."""
class MyModel(pt.Model):
pass
modelled_df = pt.DataFrame().set_model(MyModel)
assert modelled_df.model is MyModel
assert MyModel.DataFrame.model is MyModel | You should be able to set the associated model of a dataframe. | test_dataframe_set_model_method | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_fill_nan_with_defaults() -> None:
"""You should be able to fill missing values with declared defaults."""
class DefaultModel(pt.Model):
foo: int = 2
bar: str = "default"
missing_df = pt.DataFrame({"foo": [1, None], "bar": [None, "provided"]})
filled_df = missing_df.set_model(D... | You should be able to fill missing values with declared defaults. | test_fill_nan_with_defaults | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_create_missing_columns_with_defaults() -> None:
"""Columns that have default values should be created if they are missing."""
class NestedModel(pt.Model):
foo: int = 2
small_model: Optional[SmallModel] = None
class DefaultModel(pt.Model):
foo: int = 2
bar: Optional... | Columns that have default values should be created if they are missing. | test_create_missing_columns_with_defaults | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_create_missing_columns_with_dtype() -> None:
"""Ensure optional columns are created by model."""
class DefaultModel(pt.Model):
foo: int
bar: Optional[int] = None
missing_df = pt.DataFrame({"foo": [1, 2]})
filled_df = missing_df.set_model(DefaultModel).fill_null(strategy="defau... | Ensure optional columns are created by model. | test_create_missing_columns_with_dtype | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_preservation_of_model() -> None:
"""The model should be preserved on data frames after method invocations."""
class DummyModel(pt.Model):
a: int
class AnotherDummyModel(pt.Model):
a: int
df_with_model = pt.DataFrame().set_model(DummyModel)
# First many eagerly executed m... | The model should be preserved on data frames after method invocations. | test_preservation_of_model | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_dataframe_model_dtype_casting() -> None:
"""You should be able to cast columns according to model type annotations."""
class DTypeModel(pt.Model):
implicit_int: int
explicit_uint: int = pt.Field(dtype=pl.UInt64)
implicit_date: date
implicit_datetime: datetime
origi... | You should be able to cast columns according to model type annotations. | test_dataframe_model_dtype_casting | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_regular_inferred(tmp_path):
"""The `polars.read_csv` function should infer dtypes."""
csv_path = tmp_path / "foo.csv"
csv_path.write_text("1,2")
regular_df = pl.read_csv(csv_path, has_header=False)
assert regular_df.columns == ["column_1", "column_2"]
... | The `polars.read_csv` function should infer dtypes. | test_correct_columns_and_dtype_on_read_regular_inferred | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_model_dtypes(tmp_path):
"""A model DataFrame should read headerless CSVs with column names and dtypes."""
class Foo(pt.Model):
a: str = pt.Field()
b: int = pt.Field()
csv_path = tmp_path / "foo.csv"
csv_path.write_text("1,2")
model_df = Fo... | A model DataFrame should read headerless CSVs with column names and dtypes. | test_correct_columns_and_dtype_on_read_model_dtypes | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_ordered(tmp_path):
"""A model DataFrame should read headered CSVs with column names and dtypes."""
class Foo(pt.Model):
a: str = pt.Field()
b: int = pt.Field()
csv_path = tmp_path / "foo.csv"
# in model field order
csv_path.write_text("a,... | A model DataFrame should read headered CSVs with column names and dtypes. | test_correct_columns_and_dtype_on_read_ordered | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_ba_float_dtype_override(tmp_path):
"""A model DataFrame should aid CSV reading with column names and dtypes."""
class Foo(pt.Model):
a: str = pt.Field()
b: int = pt.Field()
csv_path = tmp_path / "foo.csv"
# in fkield order
csv_path.write_t... | A model DataFrame should aid CSV reading with column names and dtypes. | test_correct_columns_and_dtype_on_read_ba_float_dtype_override | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_third_float_col(tmp_path):
"""A model DataFrame should aid CSV reading with column names and dtypes."""
class Foo(pt.Model):
a: str = pt.Field()
b: int = pt.Field()
csv_path = tmp_path / "foo.csv"
csv_path.write_text("1,2,3.1")
unspecified... | A model DataFrame should aid CSV reading with column names and dtypes. | test_correct_columns_and_dtype_on_read_third_float_col | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_derived(tmp_path):
"""A model DataFrame should aid CSV reading with column names and dtypes."""
csv_path = tmp_path / "foo.csv"
csv_path.write_text("month,dollars\n1,2.99")
class DerivedModel(pt.Model):
month: int = pt.Field()
dollars: float = ... | A model DataFrame should aid CSV reading with column names and dtypes. | test_correct_columns_and_dtype_on_read_derived | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_alias_gen(tmp_path):
"""A model DataFrame should apply aliases to CSV columns."""
csv_path = tmp_path / "foo.csv"
csv_path.write_text("a,b\n1,2")
class AliasedModel(pt.Model):
model_config = ConfigDict(
alias_generator=AliasGenerator(valida... | A model DataFrame should apply aliases to CSV columns. | test_correct_columns_and_dtype_on_read_alias_gen | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_derive_functionality() -> None:
"""Test of Field(derived_from=...) and DataFrame.derive()."""
class DerivedModel(pt.Model):
underived: int
const_derived: int = pt.Field(derived_from=pl.lit(3))
column_derived: int = pt.Field(derived_from="underived")
expr_derived: int = ... | Test of Field(derived_from=...) and DataFrame.derive(). | test_derive_functionality | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_recursive_derive() -> None:
"""Data.Frame.derive() infers proper derivation order and executes it, then returns columns in the order given by the model."""
class DerivedModel(pt.Model):
underived: int
const_derived: int = pt.Field(derived_from=pl.lit(3))
second_order_derived: i... | Data.Frame.derive() infers proper derivation order and executes it, then returns columns in the order given by the model. | test_recursive_derive | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_drop_method() -> None:
"""We should be able to drop columns not specified by the data frame model."""
class Model(pt.Model):
column_1: int
df = Model.DataFrame({"column_1": [1, 2], "column_2": [3, 4]})
# Originally we have all the columns
assert df.columns == ["column_1", "column... | We should be able to drop columns not specified by the data frame model. | test_drop_method | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_polars_conversion():
"""You should be able to convert a DataFrame to a polars DataFrame."""
class Model(pt.Model):
a: int
b: str
df = Model.DataFrame({"a": [1, 2], "b": ["foo", "bar"]})
polars_df = df.as_polars()
assert isinstance(polars_df, pl.DataFrame)
assert not is... | You should be able to convert a DataFrame to a polars DataFrame. | test_polars_conversion | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_validation_alias() -> None:
"""Ensure validation_alias allows multiple column names to be parsed for one field."""
class AliasModel(pt.Model):
my_val_a: int = pt.Field(validation_alias="myValA")
my_val_b: int = pt.Field(
validation_alias=AliasChoices("my_val_b", "myValB", "... | Ensure validation_alias allows multiple column names to be parsed for one field. | test_validation_alias | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_alias_generator_read_csv() -> None:
"""Ensure validation alias is applied to read_csv."""
class AliasGeneratorModel(pt.Model):
model_config = ConfigDict(
alias_generator=AliasGenerator(validation_alias=str.title),
)
My_Val_A: int
My_Val_B: Optional[int] = N... | Ensure validation alias is applied to read_csv. | test_alias_generator_read_csv | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_is_optional() -> None:
"""It should return True for optional types."""
assert is_optional(Optional[int])
assert is_optional(Union[int, None])
assert not is_optional(int) | It should return True for optional types. | test_is_optional | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_dewrap_optional() -> None:
"""It should return the inner type of Optional types."""
assert unwrap_optional(Optional[int]) is int
assert unwrap_optional(Union[int, None]) is int
assert unwrap_optional(int) is int | It should return the inner type of Optional types. | test_dewrap_optional | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_returns_df() -> None:
"""It should return a DataFrame with the validation results."""
class SimpleModel(pt.Model):
column_1: int
column_2: str
df = pl.DataFrame({"column_1": [1, 2, 3], "column_2": ["a", "b", "c"]})
result = validate(dataframe=df, schema=SimpleModel)... | It should return a DataFrame with the validation results. | test_validation_returns_df | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_allow_missing_nested_column_validation() -> None:
"""Validation should allow missing nested columns."""
class InnerModel(pt.Model):
column_1: int
column_2: str = pt.Field(allow_missing=True)
class OuterModel(pt.Model):
inner: InnerModel
other: str
df_missing_n... | Validation should allow missing nested columns. | test_allow_missing_nested_column_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_drop_superfluous_columns() -> None:
"""Test whether irrelevant columns get filtered out before validation."""
class SingleColumnModel(pt.Model):
column_1: int
test_df = SingleColumnModel.examples().with_columns(
column_that_should_be_dropped=pl.Series([1])
)
result = valid... | Test whether irrelevant columns get filtered out before validation. | test_drop_superfluous_columns | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validate_non_nullable_columns() -> None:
"""Test for validation logic related to missing values."""
class SmallModel(pt.Model):
column_1: int
column_2: Optional[int] = None
# We insert nulls into a non-optional column, causing an exception
wrong_nulls_df = pl.DataFrame().with_... | Test for validation logic related to missing values. | test_validate_non_nullable_columns | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_uniqueness_validation() -> None:
"""It should be able to validate uniqueness."""
class MyModel(pt.Model):
column: int = pt.Field(unique=True)
non_duplicated_df = pt.DataFrame({"column": [1, 2, 3]})
MyModel.validate(non_duplicated_df)
empty_df = pt.DataFrame([pl.Series("column", [... | It should be able to validate uniqueness. | test_uniqueness_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_datetime_validation() -> None:
"""Test for date(time) validation.
Both strings, dates, and datetimes are assigned type "string" in the OpenAPI JSON
schema spec, so this needs to be specifically tested for since the implementation
needs to check the "format" property on the field schema.
""... | Test for date(time) validation.
Both strings, dates, and datetimes are assigned type "string" in the OpenAPI JSON
schema spec, so this needs to be specifically tested for since the implementation
needs to check the "format" property on the field schema.
| test_datetime_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_enum_validation() -> None:
"""Test validation of enum.Enum-typed fields."""
class ABCEnum(enum.Enum):
ONE = "a"
TWO = "b"
THREE = "c"
class EnumModel(pt.Model):
column: ABCEnum
valid_df = pl.DataFrame({"column": ["a", "b", "b", "c"]})
validate(dataframe=va... | Test validation of enum.Enum-typed fields. | test_enum_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_enum_validation() -> None:
"""Test validation of optional enum.Enum-typed fields."""
class ABCEnum(enum.Enum):
ONE = "a"
TWO = "b"
THREE = "c"
class EnumModel(pt.Model):
column: Optional[ABCEnum]
valid_df = pl.DataFrame({"column": ["a", "b", "b", "c"]... | Test validation of optional enum.Enum-typed fields. | test_optional_enum_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_literal_enum_validation() -> None:
"""Test validation of typing.Literal-typed fields."""
class EnumModel(pt.Model):
column: Literal["a", "b", "c"]
valid_df = pl.DataFrame({"column": ["a", "b", "b", "c"]})
validate(dataframe=valid_df, schema=EnumModel)
invalid_df = pl.DataFrame({"... | Test validation of typing.Literal-typed fields. | test_literal_enum_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_literal_enum_validation() -> None:
"""Test validation of optional typing.Literal-typed fields."""
class EnumModel(pt.Model):
column: Optional[Literal["a", "b", "c"]]
valid_df = pl.DataFrame({"column": ["a", "b", "b", "c"]})
validate(dataframe=valid_df, schema=EnumModel)
... | Test validation of optional typing.Literal-typed fields. | test_optional_literal_enum_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_simple_struct_validation() -> None:
"""Test validation of model with struct column."""
valid_df = pl.DataFrame({"positive_struct": [{"x": 1}, {"x": 2}, {"x": 3}]})
_PositiveStructModel.validate(valid_df)
bad_df = pl.DataFrame({"positive_struct": [{"x": -1}, {"x": 2}, {"x": 3}]})
with pytes... | Test validation of model with struct column. | test_simple_struct_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_nested_struct_validation() -> None:
"""Test validation of model with nested struct column."""
class NestedPositiveStructModel(pt.Model):
positive_struct_model: _PositiveStructModel
valid_df = pl.DataFrame(
{
"positive_struct_model": [
{"positive_struct"... | Test validation of model with nested struct column. | test_nested_struct_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_empty_list_validation() -> None:
"""Test validation of model with empty lists."""
class TestModel(pt.Model):
list_field: list[str]
# validate presence of an empty list
df = pl.DataFrame({"list_field": [["a", "b"], []]})
TestModel.validate(df)
# validate when all lists are emp... | Test validation of model with empty lists. | test_empty_list_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_list_struct_validation() -> None:
"""Test validation of model with list of structs column."""
class ListPositiveStructModel(pt.Model):
list_positive_struct: list[_PositiveStruct]
valid_df = pl.DataFrame(
{"list_positive_struct": [[{"x": 1}, {"x": 2}], [{"x": 3}, {"x": 4}, {"x": 5}... | Test validation of model with list of structs column. | test_list_struct_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_struct_validation_with_polars_constraint() -> None:
"""Test validation of models with constrained struct column."""
class Interval(pt.Model):
x_min: int
x_max: int = pt.Field(constraints=pt.col("x_min") <= pt.col("x_max"))
class IntervalModel(pt.Model):
interval: Interval
... | Test validation of models with constrained struct column. | test_struct_validation_with_polars_constraint | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_of_bounds_checks() -> None:
"""Check if value bounds are correctly validated."""
class BoundModel(pt.Model):
le_column: float = pt.Field(le=42.5)
lt_column: float = pt.Field(lt=42.5)
ge_column: float = pt.Field(ge=42.5)
gt_column: float = pt.Field(gt=42.5)
... | Check if value bounds are correctly validated. | test_validation_of_bounds_checks | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_of_dtype_specifiers() -> None:
"""Fields with specific dtype annotations should be validated."""
class DTypeModel(pt.Model):
int_column: int
int_explicit_dtype_column: int = pt.Field(dtype=pl.Int64)
smallint_column: int = pt.Field(dtype=pl.Int8)
unsigned_int_... | Fields with specific dtype annotations should be validated. | test_validation_of_dtype_specifiers | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_custom_constraint_validation() -> None:
"""Users should be able to specify custom constraints."""
class CustomConstraintModel(pt.Model):
even_int: int = pt.Field(
constraints=[(pl.col("even_int") % 2 == 0).alias("even_constraint")]
)
odd_int: int = pt.Field(constrai... | Users should be able to specify custom constraints. | test_custom_constraint_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_anonymous_column_constraints() -> None:
"""You should be able to refer to the field column with an anonymous column."""
class Pair(pt.Model):
# pl.col("_") refers to the given field column
odd_number: int = pt.Field(constraints=pl.col("_") % 2 == 1)
# pt.field is simply an alia... | You should be able to refer to the field column with an anonymous column. | test_anonymous_column_constraints | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_enum() -> None:
"""It should handle optional enums correctly."""
class OptionalEnumModel(pt.Model):
# Old type annotation syntax
optional_enum: Optional[Literal["A", "B"]]
df = pl.DataFrame({"optional_enum": ["A", "B", None]})
OptionalEnumModel.validate(df) | It should handle optional enums correctly. | test_optional_enum | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_pipe_operator() -> None:
"""Ensure that pipe operator works as expected."""
class OptionalEnumModel(pt.Model):
# Old type annotation syntax
optional_enum_1: Optional[Literal["A", "B"]]
# New type annotation syntax
optional_enum_2: Optional[Literal["A", "B"]]
... | Ensure that pipe operator works as expected. | test_optional_pipe_operator | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_of_list_dtypes() -> None:
"""It should be able to validate dtypes organized in lists."""
class ListModel(pt.Model):
int_list: list[int]
int_or_null_list: list[Optional[int]]
nullable_int_list: Optional[list[int]]
nullable_int_or_null_list: Optional[list[Optio... | It should be able to validate dtypes organized in lists. | test_validation_of_list_dtypes | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_nested_list() -> None:
"""It should be able to validate optional structs organized in lists."""
class Inner(pt.Model):
name: str
reliability: bool
level: int
class Outer(pt.Model):
id: str
code: str
label: str
inner_types: Optional[... | It should be able to validate optional structs organized in lists. | test_optional_nested_list | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_nested_field_attrs() -> None:
"""Ensure that constraints are respected even when embedded inside 'anyOf'."""
class Test(pt.Model):
foo: Optional[int] = pt.Field(
dtype=pl.Int64, ge=0, le=100, constraints=pt.field.sum() == 100
)
test_df = Test.DataFrame(
{"foo":... | Ensure that constraints are respected even when embedded inside 'anyOf'. | test_nested_field_attrs | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_column_subset() -> None:
"""Ensure that columns are only validated if they are in the subset."""
class Test(pt.Model):
a: int
b: int = pt.Field(dtype=pl.Int64, ge=0, le=100)
Test.validate(pl.DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]})) # should pass
with pytest.rai... | Ensure that columns are only validated if they are in the subset. | test_validation_column_subset | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_alias_generator() -> None:
"""Allow column name transformations through AliasGenerator."""
df = pl.DataFrame({"my_val_a": [0]})
class NoAliasGeneratorModel(pt.Model):
My_Val_A: int
with pytest.raises(DataFrameValidationError):
NoAliasGeneratorModel.validate(df)
class Alia... | Allow column name transformations through AliasGenerator. | test_alias_generator | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validate_should_not_mutate_the_original_polars_df_when_aliasing(
df: pd.DataFrame | pl.DataFrame, expected: pd.DataFrame | pl.DataFrame
) -> None:
"""Ensure that the original DataFrame is not mutated by the validation process."""
class AliasGeneratorModel(pt.Model):
model_config = ConfigDi... | Ensure that the original DataFrame is not mutated by the validation process. | test_validate_should_not_mutate_the_original_polars_df_when_aliasing | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_alias_generator_func() -> None:
"""Allow column name transformations through a string function."""
df = pl.DataFrame({"my_val_a": [0]})
class NoAliasGeneratorModel(pt.Model):
My_Val_A: int
with pytest.raises(DataFrameValidationError):
NoAliasGeneratorModel.validate(df)
cl... | Allow column name transformations through a string function. | test_alias_generator_func | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_derived_from_ser_deser():
"""Test whether derived_from can be successfully serialized and deserialized."""
for expr in [None, "foo", pl.col("foo"), pl.col("foo") * 2]:
ci = ColumnInfo(derived_from=expr)
# use str for equality check of expressions
# since expr == expr is an expre... | Test whether derived_from can be successfully serialized and deserialized. | test_derived_from_ser_deser | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_constraint_ser_deser():
"""Test whether constraints can be successfully serialized and deserialized."""
for expr in [pl.col("foo") == 2, pl.col("foo") * 2 == 2]:
ci = ColumnInfo(constraints=expr)
# use str for equality check of expressions
# since expr == expr is an expression i... | Test whether constraints can be successfully serialized and deserialized. | test_constraint_ser_deser | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_dtype_ser_deser():
"""Test whether dtypes can be successfully serialized and deserialized."""
for expr in [
pl.Float32,
pl.String,
pl.String(),
pl.Datetime(time_zone="Europe/Oslo"),
pl.Struct({"foo": pl.Int16, "bar": pl.Datetime(time_zone="Europe/Oslo")}),
... | Test whether dtypes can be successfully serialized and deserialized. | test_dtype_ser_deser | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def query_db(query, args=(), one=False):
"""Queries the database and returns a list of dictionaries."""
cur = sqldb.execute(query, args)
rv = cur.fetchall()
return (rv[0] if rv else None) if one else rv | Queries the database and returns a list of dictionaries. | query_db | python | karpathy/arxiv-sanity-preserver | buildsvm.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/buildsvm.py | MIT |
def encode_feedparser_dict(d):
"""
helper function to get rid of feedparser bs with a deep copy.
I hate when libs wrap simple things in their own classes.
"""
if isinstance(d, feedparser.FeedParserDict) or isinstance(d, dict):
j = {}
for k in d.keys():
j[k] = encode_feedparser_dict(d[k])
r... |
helper function to get rid of feedparser bs with a deep copy.
I hate when libs wrap simple things in their own classes.
| encode_feedparser_dict | python | karpathy/arxiv-sanity-preserver | fetch_papers.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/fetch_papers.py | MIT |
def parse_arxiv_url(url):
"""
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
"""
ix = url.rfind('/')
idversion = url[ix+1:] # extract just the id (and the version)
parts = idversion.split('v')
assert len(parts) == 2, 'error parsing url ' + url
return parts... |
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
| parse_arxiv_url | python | karpathy/arxiv-sanity-preserver | fetch_papers.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/fetch_papers.py | MIT |
def query_db(query, args=(), one=False):
"""Queries the database and returns a list of dictionaries."""
cur = g.db.execute(query, args)
rv = cur.fetchall()
return (rv[0] if rv else None) if one else rv | Queries the database and returns a list of dictionaries. | query_db | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def get_user_id(username):
"""Convenience method to look up the id for a username."""
rv = query_db('select user_id from user where username = ?',
[username], one=True)
return rv[0] if rv else None | Convenience method to look up the id for a username. | get_user_id | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def get_username(user_id):
"""Convenience method to look up the username for a user."""
rv = query_db('select username from user where user_id = ?',
[user_id], one=True)
return rv[0] if rv else None | Convenience method to look up the username for a user. | get_username | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def review():
""" user wants to toggle a paper in his library """
# make sure user is logged in
if not g.user:
return 'NO' # fail... (not logged in). JS should prevent from us getting here.
idvv = request.form['pid'] # includes version
if not isvalidid(idvv):
return 'NO' # fail, malformed id. weir... | user wants to toggle a paper in his library | review | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def login():
""" logs in the user. if the username doesn't exist creates the account """
if not request.form['username']:
flash('You have to enter a username')
elif not request.form['password']:
flash('You have to enter a password')
elif get_user_id(request.form['username']) is not None:
# userna... | logs in the user. if the username doesn't exist creates the account | login | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def _tempfile(*args, **kws):
""" Context for temporary file.
Will find a free temporary filename upon entering
and will try to delete the file on leaving
Parameters
----------
suffix : string
optional file suffix
"""
fd, name = tempfile.mkstemp(*args, **kws)
os.close(fd)
... | Context for temporary file.
Will find a free temporary filename upon entering
and will try to delete the file on leaving
Parameters
----------
suffix : string
optional file suffix
| _tempfile | python | karpathy/arxiv-sanity-preserver | utils.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/utils.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.