Skip to content

Commit

Permalink
Merge pull request #13 from kinegratii/develop
Browse files Browse the repository at this point in the history
release v3.1.0
  • Loading branch information
kinegratii authored Jan 18, 2020
2 parents 920f865 + ba81d63 commit db04dd2
Show file tree
Hide file tree
Showing 33 changed files with 626 additions and 228 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,7 @@ ENV/

.idea

node_modules
node_modules
*.code-workspace

demo.py
7 changes: 4 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
language: python
python:
- "3.5"
- "3.6"
- "3.7-dev"
- "3.7"
- "3.8"
branches:
only:
- master
- develop
- /^release-.*$/
- /^beta-.*$/
install:
- pip install -r requirements_dev.txt
script:
- nosetests --with-coverage --cover-package borax
- nose2 --with-coverage --coverage borax
- flake8 borax tests
2 changes: 1 addition & 1 deletion README-en.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ See [online document](https://kinegratii.github.io/borax) for more detail, which

- [x] [Typing Hints](https://www.python.org/dev/peps/pep-0484/)
- [x] [Flake8 Code Style](http://flake8.pycqa.org/en/latest/)
- [x] [nose](https://pypi.org/project/nose/)
- [x] [nose2](https://pypi.org/project/nose2/)
- [x] [Travis CI](https://travis-ci.org)
- [x] [Docsify](https://docsify.js.org)

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

## 概述 & 安装

Borax 是一个的 Python3 开发工具集合库,涉及到:
Borax 是一个 Python3 开发工具集合库,涉及到:

- 设计模式
- 数据结构及其实现
Expand Down Expand Up @@ -111,7 +111,7 @@ print(names) # ['Alice', 'Bob', 'Charlie']

- [x] [Typing Hints](https://www.python.org/dev/peps/pep-0484/)
- [x] [Flake8 Code Style](http://flake8.pycqa.org/en/latest/)
- [x] [nose](https://pypi.org/project/nose/)
- [x] [nose2](https://pypi.org/project/nose2/)
- [x] [Travis CI](https://travis-ci.org)
- [x] [Docsify](https://docsify.js.org)

Expand Down
2 changes: 1 addition & 1 deletion borax/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# coding=utf8

__version__ = '1.4.2'
__version__ = '3.1.0'
__author__ = 'kinegratii'
7 changes: 6 additions & 1 deletion borax/calendars/festivals.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,12 @@ def __init__(self, month, day, year=YEAR_ANY, leap=0, ignore_leap=1, **kwargs):
def match(self, date_obj):
date_obj = self._normalize(date_obj)
if self._ignore_leap and date_obj.leap == 1:
date_obj = date_obj.replace(leap=0)
try:
date_obj = date_obj.replace(leap=0)
except ValueError:
if date_obj.day == 30: # leap month has 30 days and normal one has 29 days
return False
raise
return super().match(date_obj)

def _resolve(self, year):
Expand Down
100 changes: 100 additions & 0 deletions borax/choices3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# coding=utf8

from collections import OrderedDict


class BItem:
_order = 0

def __init__(self, value, label=None, *, order=-1):
self._value = value
self._label = label
if order is None:
BItem._order += 1
self.order = BItem._order
else:
self.order = order

@property
def value(self):
return self._value

@property
def label(self):
return self._label

def __eq__(self, other):
return self._value == other


class BChoicesMeta(type):
def __new__(cls, name, bases, attrs):

fields = {} # {<name>:<BItem>}

parents = [b for b in bases if isinstance(b, BChoicesMeta)]
for kls in parents:
for field_name in kls._fields:
fields[field_name] = kls._fields[field_name]

for k, v in attrs.items():
if k.startswith('_'):
continue
if isinstance(v, BItem):
fields[k] = v
elif isinstance(v, (tuple, list)) and len(v) == 2:
fields[k] = BItem(v[0], v[1])
elif isinstance(v, (int, float, str, bytes)):
fields[k] = BItem(v, k.lower())

# FIXME unordered dict for python3.5

fields = OrderedDict(sorted(fields.items(), key=lambda x: x[1].order))
for field_name, item in fields.items():
attrs[field_name] = item

new_cls = super().__new__(cls, name, bases, attrs)
new_cls._fields = fields
return new_cls

@property
def fields(cls):
return cls._fields

@property
def choices(cls):
return [(item.value, item.label) for _, item in cls.fields.items()]

@property
def values(cls):
return [value for value, _ in cls.choices]

@property
def labels(cls):
return [label for _, label in cls.choices]

@property
def display_lookup(cls):
return {value: label for value, label in cls.choices}

def get_value_display(cls, item):
return cls.display_lookup.get(item)

def __getattr__(self, item):
if item in self.fields:
return self.fields[item]
return super().__getattr__(item)

def __contains__(self, item):
return item in self.values

def __iter__(self):
for item in self.choices:
yield item

def __len__(self):
return len(self.choices)


class BChoices(metaclass=BChoicesMeta):
pass
6 changes: 6 additions & 0 deletions borax/counters/serials.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ def generate(self, num: int) -> List[int]:
self.__add_serials(result)
return result

def generate_next_one(self) -> int:
return self.generate(1)[0]

def __add_serials(self, serials: Iterable[int]) -> None:
for serial in serials:
self._data_set.add(serial)
Expand Down Expand Up @@ -67,6 +70,9 @@ def generate(self, num: int) -> List[str]:
res = super().generate(num)
return list(map(self._convert, res))

def generate_next_one(self) -> str:
return self.generate(1)[0]

def add(self, elements: List[str]) -> None:
elements = map(self._parse_serial, elements)
super().add(elements)
Expand Down
5 changes: 5 additions & 0 deletions borax/datasets/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# coding=utf8

from borax.datasets.dict_datasets import DictDataset

__all__ = ['DictDataset']
35 changes: 35 additions & 0 deletions borax/datasets/dict_datasets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# coding=utf8


from borax.datasets.join_ import join_one, join


class DictDataset:
def __init__(self, data, primary_field=None):
self._data = []
if data:
self._data = list(data)
self._primary_field = primary_field

@property
def data(self):
return self._data

def __iter__(self):
for item in self.data:
yield item

def join(self, values, from_, to_, as_args=None, as_kwargs=None):
join(
self._data,
values=values,
from_=from_,
to_=to_,
as_args=as_args,
as_kwargs=as_kwargs,
)
return self

def join_one(self, values, from_, as_):
join_one(self._data, values=values, from_=from_, as_=as_)
return self
76 changes: 76 additions & 0 deletions borax/datasets/fetch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# coding=utf8
"""
fetch is a enhance module with fetch. And adjust the parameter order of calling to fit the habit.
"""
from functools import partial
from itertools import tee

__all__ = ['Empty', 'fetch', 'ifetch', 'fetch_single', 'ifetch_multiple', 'ifetch_single', 'fetch_as_dict']


class Empty(object):
pass


EMPTY = Empty()


def bget(obj, key, default=Empty):
try:
return getattr(obj, key)
except AttributeError:
pass

try:
return obj[key]
except KeyError:
pass
if default is not EMPTY:
return default

raise ValueError('Item %r has no attr or key for %r' % (obj, key))


def ifetch_single(iterable, key, default=EMPTY, getter=None):
"""
getter() g(item, key):pass
"""

def _getter(item):
if getter:
custom_getter = partial(getter, key=key)
return custom_getter(item)
else:
return partial(bget, key=key, default=default)(item)

return map(_getter, iterable)


def fetch_single(iterable, key, default=EMPTY, getter=None):
return list(ifetch_single(iterable, key, default=default, getter=getter))


def ifetch_multiple(iterable, *keys, defaults=None, getter=None):
defaults = defaults or {}
if len(keys) > 1:
iters = tee(iterable, len(keys))
else:
iters = (iterable,)
iters = [ifetch_single(it, key, default=defaults.get(key, EMPTY), getter=getter) for it, key in zip(iters, keys)]
return iters


def ifetch(iterable, key, *keys, default=EMPTY, defaults=None, getter=None):
if len(keys) > 0:
keys = (key,) + keys
return map(list, ifetch_multiple(iterable, *keys, defaults=defaults, getter=getter))
else:
return ifetch_single(iterable, key, default=default, getter=getter)


def fetch(iterable, key, *keys, default=EMPTY, defaults=None, getter=None):
return list(ifetch(iterable, key, *keys, default=default, defaults=defaults, getter=getter))


def fetch_as_dict(data, key_field, value_value):
return dict([(bget(item, key_field), bget(item, value_value)) for item in data])
30 changes: 30 additions & 0 deletions borax/datasets/join_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# coding=utf8


def join_one(data_list, values, from_, as_, default=None):
if isinstance(values, (list, tuple)):
values = dict(values)
if not isinstance(values, dict):
raise TypeError("Unsupported Type for values param.")
for item in data_list:
if from_ in item:
val = item[from_]
if val in values:
ref_val = values[val]
else:
ref_val = default
item[as_] = ref_val
return data_list


def join(data_list, values, from_, to_, as_args=None, as_kwargs=None):
as_args = as_args or []
as_kwargs = as_kwargs or {}
as_fields = {**{a: a for a in as_args}, **as_kwargs}
dict_values = {v[to_]: v for v in values}
for item in data_list:
kv = item[from_]
val_dic = dict_values[kv]
for f1, f2 in as_fields.items():
item[f2] = val_dic[f1]
return data_list
31 changes: 0 additions & 31 deletions borax/decorators/admin.py

This file was deleted.

Loading

0 comments on commit db04dd2

Please sign in to comment.