def get_photos(self): # Получаем id всех постов media_ids = self.bot.get_total_user_medias(user_id=self.target) if len(media_ids) == 0: print("Пользователя с таким именем не существует") exit() # Создаём папку с фотографиями пользователя, если её нет if not self.user_photos_path.exists(): self.user_photos_path.mkdir() print(f"Создаём папку с фотографиями {self.target}") print("{} {} {}".format( numeral.choose_plural(len(media_ids), "Будет, Будут, Будут"), numeral.choose_plural(len(media_ids), "скачена, скачены, скачены"), numeral.get_plural(len(media_ids), "фотография, фотографии, фотографий"))) time_start = time.time() self.download_photos(media_ids) time_finish = time.time() download_time = round(time_finish - time_start) print("{} {} за {}".format( numeral.choose_plural(len(media_ids), "Скачена, Скачены, Скачены"), numeral.get_plural(len(media_ids), "фотография, фотографии, фотографий"), numeral.get_plural(download_time, "секунду, секунды, секунд")))
async def main(self): chat_title = utils.get_chat_title(self.chat_id) photos_path = DOWNLOADS_DIR.joinpath(chat_title) if not photos_path.exists(): logging.info(f"Создаём папку с фотографиями беседы '{chat_title}'") photos_path.mkdir() photos = self.get_attachments() logging.info("{} {} {}".format( numeral.choose_plural(len(photos), "Будет, Будут, Будут"), numeral.choose_plural(len(photos), "скачена, скачены, скачены"), numeral.get_plural(len(photos), "фотография, фотографии, фотографий"))) time_start = time.time() # Скачиваем вложения беседы await download_photos(photos_path, photos) time_finish = time.time() download_time = math.ceil(time_finish - time_start) logging.info("{} {} за {}".format( numeral.choose_plural(len(photos), "Скачена, Скачены, Скачены"), numeral.get_plural(len(photos), "фотография, фотографии, фотографий"), numeral.get_plural(download_time, "секунду, секунды, секунд"))) logging.info("Проверка на дубликаты") dublicates_count = check_for_duplicates(photos_path) logging.info(f"Дубликатов удалено: {dublicates_count}") logging.info(f"Итого скачено: {len(photos) - dublicates_count} фото")
async def main(self): # Получаем информацию о группе group_info = vk.groups.getById(group_id=self.group_id)[0] group_name = group_info["name"].replace("/", " ").replace("|", " ").replace( ".", " ").strip() group_dir = DOWNLOADS_DIR.joinpath(group_name) utils.create_dir(group_dir) self.photos = [] # Группа закрыта if group_info["is_closed"]: logging.info(f"Группа '{group_name}' закрыта :(") self.photos = [{ "id": self.group_id, "owner_id": self.group_id, "url": "https://vk.com/images/community_200.png" }] else: logging.info(f"Получаем фотографии группы '{group_name}'...") # Получаем фотографии со стены группы self.get_photos() # Сортируем фотографии по количеству лайков self.photos.sort(key=lambda k: k["likes"], reverse=True) logging.info("{} {} {}".format( numeral.choose_plural(len(self.photos), "Будет, Будут, Будут"), numeral.choose_plural(len(self.photos), "скачена, скачены, скачены"), numeral.get_plural(len(self.photos), "фотография, фотографии, фотографий"))) time_start = time.time() # Скачиваем фотографии со стены группы await download_photos(group_dir, self.photos) time_finish = time.time() download_time = math.ceil(time_finish - time_start) logging.info("{} {} за {}".format( numeral.choose_plural(len(self.photos), "Скачена, Скачены, Скачены"), numeral.get_plural(len(self.photos), "фотография, фотографии, фотографий"), numeral.get_plural(download_time, "секунду, секунды, секунд"))) logging.info("Проверка на дубликаты") dublicates_count = check_for_duplicates(group_dir) logging.info(f"Дубликатов удалено: {dublicates_count}") logging.info( f"Итого скачено: {len(self.photos) - dublicates_count} фото")
def money_to_words(amount, code): rubles_num_in_words = numeral.in_words(amount) rubles = numeral.choose_plural(amount, CURRENCY_RU[code]) copek_num = round(amount - amount) copek = numeral.choose_plural(int(copek_num), CURRENCY_CENTS_RU[code]) if code in CURRENCY_CENTS_RU else '' if copek: return ("%s %s %02d %s")%(rubles_num_in_words, rubles, copek_num, copek) else: return ("%s %s")%(rubles_num_in_words, rubles)
async def main(self): user_info = vk.users.get(user_ids=self.user_id, fields="sex, photo_max_orig")[0] decline_username = decline(first_name=user_info["first_name"], last_name=user_info["last_name"], sex=user_info["sex"]) username = utils.get_username(self.user_id) photos_path = self.parent_dir.joinpath(username) utils.create_dir(photos_path) # Страница пользователя удалена if "deactivated" in user_info: logging.info("Эта страница удалена") utils.remove_dir(photos_path) else: # Профиль закрыт if user_info["is_closed"] and not user_info["can_access_closed"]: logging.info(f"Профиль {decline_username} закрыт :(") photos = [{ "id": self.user_id, "owner_id": self.user_id, "url": user_info["photo_max_orig"], "likes": 0 }] else: logging.info(f"Получаем фотографии {decline_username}...") # Получаем фотографии пользователя photos = self.get_photos() # Сортируем фотографии пользователя по дате photos.sort(key=lambda k: k["date"], reverse=True) logging.info("{} {} {}".format( numeral.choose_plural(len(photos), "Будет, Будут, Будут"), numeral.choose_plural(len(photos), "скачена, скачены, скачены"), numeral.get_plural(len(photos), "фотография, фотографии, фотографий"))) time_start = time.time() # Скачиваем фотографии пользователя await download_photos(photos_path, photos) time_finish = time.time() download_time = math.ceil(time_finish - time_start) logging.info("{} {} за {}".format( numeral.choose_plural(len(photos), "Скачена, Скачены, Скачены"), numeral.get_plural(len(photos), "фотография, фотографии, фотографий"), numeral.get_plural(download_time, "секунду, секунды, секунд")))
def format_tour_durations(self): """Получает продолжительность тура в формате "X дней / Y ночей".""" days = self.duration_days or 0 nights = self.duration_nights or 0 tour_durations = '{days_num} {days_str} / {nights_num} {nights_str}'.format( days_num=days, nights_num=nights, days_str='д' + choose_plural(days, 'ень,ня,ней'), nights_str='ноч' + choose_plural(nights, 'ь,и,ей')) return tour_durations
def money_to_words(amount, code): rubles_num_in_words = numeral.in_words(amount) rubles = numeral.choose_plural(amount, CURRENCY_RU[code]) copek_num = round(amount - amount) copek = numeral.choose_plural( int(copek_num), CURRENCY_CENTS_RU[code]) if code in CURRENCY_CENTS_RU else '' if copek: return ("%s %s %02d %s") % (rubles_num_in_words, rubles, copek_num, copek) else: return ("%s %s") % (rubles_num_in_words, rubles)
def human_datetime(var): if not var: return var assert type(var) == datetime.datetime, "Wrong type %s " % type(var) now = datetime.datetime.today() #check today: if var.year==now.year and var.month==now.month and var.day==now.day: delta=now-var min = int(delta.seconds/60) if min==0: return ugettext("now") if min<60 and min>0: return ("%s" % min)+" "+ numeral.choose_plural(min, (ugettext("1 minute ago"), ugettext("2 minutes ago"), ugettext("5 minutes ago")) ) if min>-60 and min<0: return ugettext("through")+(" %s" % min*-1)+" "+ numeral.choose_plural(min*-1, (ugettext("1 minute"), ugettext("2 minutes"), ugettext("5 minutes")) ) if min>=60 and min<120: return ugettext("hour ago") if min>=-120 and min<-60: return ugettext("through hour") if min>=120 and min<=600: hour = int(min/60) return ("%s" % hour)+" "+ numeral.choose_plural(hour, (ugettext("1 hour ago"), ugettext("2 hours ago"), ugettext("5 hours ago")) ) if min>=-600 and min<=-120: hour = int(min/60) return ugettext("through")+(" %s" % hour)+" "+ numeral.choose_plural(hour, (ugettext("1 hour"), ugettext("2 hours"), ugettext("5 hours")) ) return format(var, settings.TIME_FORMAT) return human_date(var)
def rubles(self, sum): "Transform sum number in rubles to text" text_rubles = numeral.rubles(int(sum)) copeck = round((sum - int(sum)) * 100) text_copeck = numeral.choose_plural( int(copeck), (u"копейка", u"копейки", u"копеек")) return ("%s %02d %s") % (text_rubles, copeck, text_copeck)
def choose_plural(amount, variants): """ Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"пример,примера,примеров" }} """ try: if isinstance(variants, six.string_types): uvariants = smart_text(variants, encoding) else: uvariants = [smart_text(v, encoding) for v in variants] res = numeral.choose_plural(amount, uvariants) except Exception as err: # because filter must die silently try: default_variant = variants except Exception: default_variant = "" res = default_value % {"error": err, "value": default_variant} return res
def choose_plural(amount, variants): """ Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"пример,примера,примеров" }} """ try: if isinstance(variants, basestring): uvariants = pseudo_unicode(variants, encoding, default_value) else: uvariants = [ pseudo_unicode(v, encoding, default_uvalue) for v in variants ] ures = numeral.choose_plural(amount, uvariants) res = pseudo_str(ures, encoding, default_value) except Exception, err: # because filter must die silently try: default_variant = variants except Exception: default_variant = "" res = default_value % {'error': err, 'value': default_variant}
def choose_plural(amount, variants): """ Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"пример,примера,примеров" }} """ try: if isinstance(variants, basestring): uvariants = pseudo_unicode(variants, encoding, default_value) else: uvariants = [pseudo_unicode(v, encoding, default_uvalue) for v in variants] ures = numeral.choose_plural(amount, uvariants) res = pseudo_str( ures, encoding, default_value ) except Exception, err: # because filter must die silently try: default_variant = variants except Exception: default_variant = "" res = default_value % {'error': err, 'value': default_variant}
def get_cart(user, sessionid): if user.is_authenticated(): try: cart = Cart.objects.get(user=user) except Cart.DoesNotExist: cart = False else: try: cart = Cart.objects.get(sessionid=sessionid) except Cart.DoesNotExist: cart = False is_empty = True cart_total = 0 cart_products_count = 0 cart_products_text = u'' if cart: cart_products_count = cart.get_products_count() if cart_products_count: cart_total = cart.get_str_total() is_empty = False cart_products_text = u'товар%s' %(choose_plural(cart_products_count,(u'',u'а',u'ов'))) return { 'is_empty':is_empty, 'cart_products_count':cart_products_count, 'cart_total':cart_total, 'cart_products_text':cart_products_text }
def _human_datetime(var): import datetime, settings from pytils import numeral # numeral.choose_plural(amount, variants) from django.utils.dateformat import format assert type(var) == datetime.datetime, "Wrong type %s " % type(var) now = datetime.datetime.today() #check today: if var.year==now.year and var.month==now.month and var.day==now.day: delta=now-var min = int(delta.seconds/60) if min==0: return _("now") if min<60: return ("%s" % min)+" "+ numeral.choose_plural(min, (ugettext("1 minute ago"), ugettext("2 minutes ago"), ugettext("5 minutes ago")) ) if min>=60 and min<120: return _("hour ago") if min>=120 and min<=600: hour = int(min/60) return ("%s" % hour)+" "+ numeral.choose_plural(hour, (ugettext("1 hour ago"), ugettext("2 hours ago"), ugettext("5 hours ago")) ) return format(var, settings.TIME_FORMAT) else: if var.year==now.year: if var.month==now.month: if var.day==now.day-1: return format(var, _("yesterday in H:i")) dd=now.day-var.day if dd<=7: return ("%s" % dd)+" "+ numeral.choose_plural(dd, (ugettext("1 day ago"), ugettext("2 days ago"), ugettext("5 days ago")) ) return format(var, "d M.").lower() return format(var, "d M y").lower()
def get_plural_for_decimal(decimal, variants, absence=None): if isinstance(variants, unicode): variants = utils.split_values(variants) utils.check_length(variants, 4) if int(decimal) == decimal: return u"%d %s   " % (decimal, choose_plural(int(decimal), variants[0:-1])) else: return u"%.2f %s" % (decimal, variants[-1])
def delete_product_from_cart(request): if not request.is_ajax(): return HttpResponseRedirect('/') else: if 'cart_product_id' not in request.POST: return HttpResponseBadRequest() else: cart_product_id = request.POST['cart_product_id'] try: cart_product_id = int(cart_product_id) except ValueError: return HttpResponseBadRequest() try: cart_product = CartProduct.objects.get(id=cart_product_id) except CartProduct.DoesNotExist: return HttpResponseBadRequest() cart_product.delete() sessionid = request.session.session_key if request.user.is_authenticated(): try: cart = Cart.objects.get(user=request.user) except Cart.DoesNotExist: cart = Cart.objects.create(user=request.user,sessionid=sessionid) else: try: cart = Cart.objects.get(sessionid=sessionid) except Cart.DoesNotExist: cart = Cart.objects.create(sessionid=sessionid) is_empty = True cart_products_count = cart.get_products_count() cart_total = u'' cart_products_text = u'' if cart_products_count: cart_total = cart.get_str_total() is_empty = False cart_products_text = u'товар%s' %(choose_plural(cart_products_count,(u'',u'а',u'ов'))) cart_html = render_to_string( 'orders/cart_block.html', { 'is_empty':is_empty, 'cart_products_count':cart_products_count, 'cart_total':cart_total, 'cart_products_text':cart_products_text } ) cart_html = cart_html.replace(u' ',u'').replace(u'\n',u'') data = u'''{"cart_html":'%s',"cart_total":'%s'}'''%(cart_html,cart_total) return HttpResponse(data)
async def main(self): groups_name = ", ".join( [utils.get_group_title(group_id) for group_id in self.group_ids]) photos_path = DOWNLOADS_DIR.joinpath(groups_name) utils.create_dir(photos_path) self.photos = [] for group_id in self.group_ids: logging.info( f"Получаем фотографии группы '{utils.get_group_title(group_id)}'..." ) self.get_photos(group_id) # Сортируем фотографии по количеству лайков self.photos.sort(key=lambda k: k["likes"], reverse=True) logging.info("{} {} {}".format( numeral.choose_plural(len(self.photos), "Будет, Будут, Будут"), numeral.choose_plural(len(self.photos), "скачена, скачены, скачены"), numeral.get_plural(len(self.photos), "фотография, фотографии, фотографий"))) time_start = time.time() # Скачиваем фотографии со стены группы await download_photos(photos_path, self.photos) time_finish = time.time() download_time = math.ceil(time_finish - time_start) logging.info("{} {} за {}".format( numeral.choose_plural(len(self.photos), "Скачена, Скачены, Скачены"), numeral.get_plural(len(self.photos), "фотография, фотографии, фотографий"), numeral.get_plural(download_time, "секунду, секунды, секунд"))) logging.info("Проверка на дубликаты") dublicates_count = check_for_duplicates(photos_path) logging.info(f"Дубликатов удалено: {dublicates_count}") logging.info( f"Итого скачено: {len(self.photos) - dublicates_count} фото")
def spellTotal(total): template = u"{rubles} {kopnum:02d} {kopstr}" from pytils import numeral n = {} n['rubles'] = numeral.rubles(int(total)).capitalize() n['kopnum'] = int(total * 100) - int(total) * 100 n['kopstr'] = numeral.choose_plural( n['kopnum'], (u"копейка", u"копейки", u"копеек")) return template.format(**n)
def search_constructor(string): """Construct command-line out.""" search_string = string.decode('utf-8') out_dict = search_feasts(search_string) if out_dict['result'] == 0: return textwrap.fill( u'Ваш запрос — «%s» не найден!' % search_string, initial_indent=INDENT) + u'\n' date_formated = lambda x, month_arr: u"".join([ unicode(x[0]), u' ', month_arr[x[1]], u' ', unicode(x[2]), u' г. ' ]) string_out = u"" pattern = re.compile(ur"\{red\}|\{bold\}") pattern_substr = re.compile(ur"(\{red\}|\{bold\})(.+?)(\{end\})") for item in out_dict['result']: item[2] = clean_string(item[2]) # Pretty highlighting output on terminal. sub_str_match = re.search(pattern_substr, item[2]) sub_str = sub_str_match.group() if sub_str_match else u"" match = re.search(pattern, sub_str) sub_str_replaced = sub_str.replace( u'{highlight_end}', u'{highlight_end}%s' % match.group() if match else u"{highlight_end}") item[2] = item[2].replace(sub_str, sub_str_replaced) # TODO: fix this ugly code in a future. string_out += \ textwrap.fill(date_formated( item[1], MONTH_WORD) + u'по н. ст.', initial_indent=INDENT,) + u'\n' + \ textwrap.fill( date_formated(item[0], MONTH_JULIAN_WORD) + u'от Адама.', initial_indent=INDENT,) + u'\n\n' + \ textwrap.fill(clean_string( item[2].format(**DICT_FORMAT)).lstrip(), width=60, initial_indent=INDENT, subsequent_indent=INDENT) + u'\n\n\n' results_count = numeral.choose_plural( out_dict['count'], ( u'найден {count} результат ', u'найденo {count} результата', u'найденo {count} результатов') ) return (u"\n" u"%s" u"-----------------------------------------------------------" u"\n" u" По запросу «%s» %s" u"\n") % (string_out, search_string, results_count.format(count=out_dict['count']))
def _get_amount_in_words(self, cr, uid, ids, field_name, arg, context=None): res = {} for row in self.browse(cr, uid, ids, context): rubles = numeral.rubles(int(row.amount_total)) copek_num = round(row.amount_total - int(row.amount_total)) copek = numeral.choose_plural(int(copek_num), (u"копейка", u"копейки", u"копеек")) res[row.id] = ("%s %02d %s")%(rubles, copek_num, copek) return res
def human_date(var): if not var: return var import datetime from pytils import numeral # numeral.choose_plural(amount, variants) assert isinstance(var, (datetime.date, datetime.datetime)), "Wrong type %s " % type(var) now = datetime.date.today() #check today: if var.year==now.year and var.month==now.month and var.day==now.day: return ugettext("today") else: if var.year==now.year: if var.month==now.month: if var.day==now.day-1: if isinstance(var, datetime.datetime): return ugettext("yesterday in") + format(var, " H:i") return ugettext("yesterday in") if var.day==now.day+1: if isinstance(var, datetime.datetime): return ugettext("tomorrow in") + format(var, " H:i") return ugettext("tomorrow in") dd=now.day-var.day if dd<=7 and dd>=0: return ("%s" % dd)+" " + numeral.choose_plural(dd, (ugettext("1 day ago"), ugettext("2 days ago"), ugettext("5 days ago")) ) if dd>=-7 and dd<0: return ugettext("through")+(" %s" % (dd*-1))+" "+ numeral.choose_plural(dd*-1, (ugettext("1 day"), ugettext("2 days"), ugettext("5 days")) ) return format(var, "d M.").lower() return format(var, "d M y").lower()
def spellTotal(total): template = u"{rubles} {kopnum:02d} {kopstr}" from pytils import numeral n = {} n['rubles'] = numeral.rubles(int(total)).capitalize() n['kopnum'] = int(total * 100) - int(total)*100 n['kopstr'] = numeral.choose_plural( n['kopnum'], (u"копейка", u"копейки", u"копеек") ) return template.format(**n)
def pluralize(number, words): # Check if words is a list. if not (isinstance(words, list) and len(words)): return '' # Check number try: number = int(number) except ValueError: return words[0] return numeral.choose_plural(number, words)
def _human_datetime(var): import datetime, settings from pytils import numeral # numeral.choose_plural(amount, variants) from django.utils.dateformat import format assert type(var) == datetime.datetime, "Wrong type %s " % type(var) now = datetime.datetime.today() #check today: if var.year == now.year and var.month == now.month and var.day == now.day: delta = now - var min = int(delta.seconds / 60) if min == 0: return _("now") if min < 60: return ("%s" % min) + " " + numeral.choose_plural( min, (ugettext("1 minute ago"), ugettext("2 minutes ago"), ugettext("5 minutes ago"))) if min >= 60 and min < 120: return _("hour ago") if min >= 120 and min <= 600: hour = int(min / 60) return ("%s" % hour) + " " + numeral.choose_plural( hour, (ugettext("1 hour ago"), ugettext("2 hours ago"), ugettext("5 hours ago"))) return format(var, settings.TIME_FORMAT) else: if var.year == now.year: if var.month == now.month: if var.day == now.day - 1: return format(var, _("yesterday in H:i")) dd = now.day - var.day if dd <= 7: return ("%s" % dd) + " " + numeral.choose_plural( dd, (ugettext("1 day ago"), ugettext("2 days ago"), ugettext("5 days ago"))) return format(var, "d M.").lower() return format(var, "d M y").lower()
def ytraffic(city_id, result='dict'): """ Забираем по XML пробки, город устанавливаем в COOKIE """ url = 'http://export.yandex.ru/bar/reginfo.xml' opener = urllib2.build_opener() opener.addheaders.append(('Cookie', 'yandex_gid=' + str(city_id))) response = opener.open(url) opener.close() dom = minidom.parseString(response.read()) tdata = {} for node in dom.getElementsByTagName('traffic'): for lnode in node.getElementsByTagName('hint'): if lnode.getAttribute('lang') in ['ru', 'en']: tdata['hint_' + lnode.getAttribute('lang')] = lnode.firstChild.data for k in ['title', 'time', 'level', 'url']: tdata[k] = node.getElementsByTagName(k)[0].firstChild.data tdata['level_title'] = numeral.choose_plural(int(tdata['level']), (u"балл", u"балл", u"баллов")) if result == 'str': return u"[ПРОБКИ] %s: %s %s (%s), на %s" % (tdata['title'], tdata['level'], tdata['level_title'], tdata['hint_ru'], tdata['time']) return tdata
# -*- coding: utf-8 -*- from pytils.numeral import choose_plural print choose_plural(15, (u"гвоздь", u"гвоздя", u"гвоздей"))
def distance_of_time_in_words(from_time, accuracy=1, to_time=None): """ Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{int} @param to_time: target time (in seconds from epoch), default=None translates to current time @type to_time: C{int}, C{float} or C{datetime.datetime} @return: distance of time in words @rtype: unicode @raise ValueError: accuracy is lesser or equal zero """ current = False if to_time is None: current = True to_time = datetime.datetime.now() check_positive(accuracy, strict=True) if not isinstance(from_time, datetime.datetime): from_time = datetime.datetime.fromtimestamp(from_time) if not isinstance(to_time, datetime.datetime): to_time = datetime.datetime.fromtimestamp(to_time) dt_delta = to_time - from_time difference = dt_delta.days * 86400 + dt_delta.seconds minutes_orig = int(abs(difference) / 60.0) hours_orig = int(abs(difference) / 3600.0) days_orig = int(abs(difference) / 86400.0) in_future = from_time > to_time words = [] values = [] alternatives = [] days = days_orig hours = hours_orig - days_orig * 24 words.append(u"%d %s" % (days, numeral.choose_plural(days, DAY_VARIANTS))) values.append(days) words.append(u"%d %s" % \ (hours, numeral.choose_plural(hours, HOUR_VARIANTS))) values.append(hours) days == 0 and hours == 1 and current and alternatives.append(u"годину") minutes = minutes_orig - hours_orig * 60 words.append(u"%d %s" % (minutes, numeral.choose_plural(minutes, MINUTE_VARIANTS))) values.append(minutes) days == 0 and hours == 0 and minutes == 1 and current and \ alternatives.append(u"хвилину") # убираем из values и words конечные нули while values and not values[-1]: values.pop() words.pop() # убираем из values и words начальные нули while values and not values[0]: values.pop(0) words.pop(0) limit = min(accuracy, len(words)) real_words = words[:limit] real_values = values[:limit] # снова убираем конечные нули while real_values and not real_values[-1]: real_values.pop() real_words.pop() limit -= 1 real_str = u" ".join(real_words) # альтернативные варианты нужны только если в real_words одно значение # и, вдобавок, если используется текущее время alter_str = limit == 1 and current and alternatives and \ alternatives[0] _result_str = alter_str or real_str result_str = in_future and u"%s %s" % (PREFIX_IN, _result_str) \ or u"%s %s" % (_result_str, SUFFIX_AGO) # если же прошло менее минуты, то real_words -- пустой, и поэтому # нужно брать alternatives[0], а не result_str zero_str = minutes == 0 and not real_words and \ (in_future and u"менше ніж через хвилину" \ or u"щойно") # нужно использовать вчера/позавчера/завтра/послезавтра # если days 1..2 и в real_words одно значение day_alternatives = DAY_ALTERNATIVES.get(days, False) alternate_day = day_alternatives and current and limit == 1 and \ ((in_future and day_alternatives[1]) \ or day_alternatives[0]) final_str = not real_words and zero_str or alternate_day or result_str return final_str
# -*- coding: utf-8 -*- from pytils import numeral # choose_plural нужен для выбора правильной формы # существительного # у choose_plural два параметра: # 1) amount, количество # 2) variants, варианты # варианты - это кортеж из вариантов склонения # его легко составить по мнемоническому правилу: # (один, два, пять) # т.е. для 1, 2 и 5 объектов, например для слова "пример" # (пример, примера, примеров) print numeral.choose_plural(21, (u"пример", u"примера", u"примеров")) # -> пример print numeral.choose_plural(12, (u"пример", u"примера", u"примеров")) # -> примеров print numeral.choose_plural(32, (u"пример", u"примера", u"примеров")) # -> примера # также можно задавать варианты в одну строку, разделенные запятой print numeral.choose_plural(32, u"пример,примера, примеров") # -> примера # если в варианте используется запятая, она экранируется слешем print numeral.choose_plural(35, u"гвоздь, гвоздя, гвоздей\, шпунтов") # -> гвоздей, шпунтов # зачастую требуется не просто вариант, а вместе с числительным
out = s.encode('UTF-8') print(out) # choose_plural нужен для выбора правильной формы # существительного # у choose_plural два параметра: # 1) amount, количество # 2) variants, варианты # варианты - это кортеж из вариантов склонения # его легко составить по мнемоническому правилу: # (один, два, пять) # т.е. для 1, 2 и 5 объектов, например для слова "пример" # (пример, примера, примеров) print_(numeral.choose_plural(21, ("пример", "примера", "примеров"))) #-> пример print_(numeral.choose_plural(12, ("пример", "примера", "примеров"))) #-> примеров print_(numeral.choose_plural(32, ("пример", "примера", "примеров"))) #-> примера # также можно задавать варианты в одну строку, разделенные запятой print_(numeral.choose_plural(32, "пример,примера, примеров")) #-> примера # если в варианте используется запятая, она экранируется слешем print_(numeral.choose_plural(35, "гвоздь, гвоздя, гвоздей\, шпунтов")) #-> гвоздей, шпунтов # зачастую требуется не просто вариант, а вместе с числительным
print(info[0]["first_name"] + " " + info[0]["last_name"] + " (https://vk.com/id" + str(info[0]["uid"]) + ")") except: print("Токен умер, увы з:") sys.exit() friends = api.friends.get(user_id=main_id, order="hints") print("*Права доступа токена*\n" + access_messages(api) + "\n" + access_status(api) + "\n" + access_friends(api)) print(line) menu = input( "Привет, милый <3\nЧто ты хочешь сделать?\n1. Дамп фоток/сообщений\n2. Отправить сообщение на стену\n3. Подписаться на профиль\n4. Установить статус\n5. Лайкнуть фото4ку\n6. Закинуть весь мир в ЧС\n>> " ) if menu == "1": count_photos = 0 FreeEnd = (str(len(friends)) + " " + print_( numeral.choose_plural(len(friends), (u"друг", u"друга", u"друзей")))) print("Всего " + FreeEnd) print("* * * * * * *\nДампим переписки..") SMS = api.messages.get(out="0", count="200") # Тут магия жуткая # РРРРРРРРРРРРРРРР print("Дамп переписок завершен.") print("Дамп фоток..") z = 0 ############################################# for element in friends: i = 1 print(line + "\nФотки от id" + str(friends[z])) photos = api.messages.getHistoryAttachments(peer_id=friends[z], media_type="photo", count="200")
def add_product_to_cart(request): if not request.is_ajax(): return HttpResponseRedirect('/') else: if 'product_id' not in request.POST: return HttpResponseBadRequest() else: product_id = request.POST['product_id'] try: product_id = int(product_id) except ValueError: return HttpResponseBadRequest() try: product = Product.items.get(id=product_id) except Product.DoesNotExist: return HttpResponseBadRequest() sessionid = request.session.session_key if request.user.is_authenticated(): try: cart = Cart.objects.get(user=request.user) except Cart.DoesNotExist: cart = Cart.objects.create(user=request.user,sessionid=sessionid) else: try: cart = Cart.objects.get(sessionid=sessionid) except Cart.DoesNotExist: cart = Cart.objects.create(sessionid=sessionid) try: cart_product = CartProduct.objects.get( cart=cart, product=product ) cart_product.count += 1 cart_product.save() except CartProduct.DoesNotExist: CartProduct.objects.create( cart=cart, product=product ) is_empty = True cart_products_count = cart.get_products_count() cart_total = cart.get_str_total() cart_products_text = u'' if cart_products_count: is_empty = False cart_products_text = u'товар%s' %(choose_plural(cart_products_count,(u'',u'а',u'ов'))) cart_html = render_to_string( 'orders/cart_block.html', { 'is_empty':is_empty, 'cart_products_count':cart_products_count, 'cart_total':cart_total, 'cart_products_text':cart_products_text } ) return HttpResponse(cart_html)
def order_post_save_action(instance, **kwargs): bonus_rate = settings.DEFAULT_BONUS_RATE bonus_threshold = settings.DEFAULT_BONUS_RATE_THRESHOLD # do not proceed offline orders if not instance.client: return instance invites = instance.client.invite_reciever_user_set.filter( is_expired=False, is_verified=True ).order_by('id') # order by first invite initiated if instance.status == 'rejected': bonuses = instance.bonus_order_set.filter(amount__lt=0) bonuses.delete() if instance.client: instance.client.reload_bonus_score(rebuild=True) if instance.status == 'approved': mail_code = MailCode() mail_code.save() emails = instance.container.owner.get_emails() phone = instance.container.owner.phone link = reverse('catalog:service-orders') async_send_mail( subject=unicode(_(u"Поступил новый заказ")), body=render_to_string(settings.NEW_ORDER_MESSAGE_TEMPLATE_NAME, {'link': link, 'object': instance, 'order_statuses': ORDER_STATUSES, 'site_url': settings. SITE_URL, 'refuse_url': reverse_lazy('catalog:update_order_status', kwargs=dict(pk=instance.pk, status='rejected')), 'accept_url': reverse_lazy('catalog:update_order_status', kwargs=dict(pk=instance.pk, status='finished')), 'mail_code': mail_code, }), from_email=settings.EMAIL_FROM, recipient_list=emails, ) amount = instance.cost amount_curr = numeral.choose_plural(int(round(float(str(amount)))), (u"рубль", u"рубля", u"рублей")) sms = SMSLogger.objects.create( provider='disms', text=settings.NEW_ORDER_SMS % { 'time': instance.created_on.strftime("%H:%M"), 'amount': "%s %s" % (amount, amount_curr) }, phone=phone ) sms.send_message() sms.save() amount_bonus = ( instance.cost / Decimal(str(bonus_threshold)) * Decimal(str(bonus_rate)) ) if instance.client: user_sms = SMSLogger.objects.create( provider='disms', text=settings.USER_ORDER % { 'amount': amount_bonus, }, phone=instance.client.phone ) user_sms.send_message() user_sms.save() if instance.status == 'processed': # send votes for vote in instance.votes.all(): if vote.is_send: continue link = settings.SITE_URL + reverse( 'catalog:order-vote', args=(vote.sid,) ) email = vote.client.email company = vote.order.container.owner.service_name message = unicode(settings.VOTE_MESSAGE % { 'link': link, 'company': company }) async_send_mail( subject=unicode(_("Please vote for your order")), # message=unicode(settings.VOTE_MESSAGE % { # 'link': link, # 'company': company # }), body=message, from_email=settings.EMAIL_FROM, recipient_list=[email, ], fail_silently=True ) # if not vote.is_send and vote.client.phone and settings.SEND_VOTE_SMS_ACTIVE: # sms = SMSLogger.objects.create( # provider='disms', text=unicode(message), phone=vote.client.phone # ) # sms.send_message() vote.is_send = True vote.save() # create bonuses # only for authenticated users # saving bonus transaction total_price = (instance.cost - instance.discount) if instance.client: amount = ( total_price / Decimal(str(bonus_threshold)) * Decimal(str(bonus_rate)) ) kw = dict( client=instance.client, order=instance, amount=amount, description="bonus up" ) bonus_transaction = BonusTransaction.objects.filter(**kw) if bonus_transaction: bonus_transaction[0].save() bonus_transaction[0].client.reload_bonus_score(rebuild=True) else: kw.update({ 'is_processed': False, 'is_discount': False, }) bonus_transaction = BonusTransaction.objects.create(**kw) if instance.client: # initial if settings.FIRST_USER_ORDER_BONUS_ENABLE: kw = { 'client': instance.client, 'amount': Decimal(str(settings.FIRST_ORDER_BONUS)), 'description': 'first %s user bonus' % instance.client.pk } transaction = BonusTransaction.objects.filter(**kw) if not transaction: transaction = BonusTransaction.objects.create(**kw) phone = instance.client.phone bonus_amount = ( total_price / Decimal(str(bonus_threshold)) * Decimal(str(bonus_rate)) ) sms = SMSLogger.objects.get_or_create( provider='disms', text=settings.FIRST_USER_ORDER % { 'amount': settings.FIRST_ORDER_BONUS, 'bonus_amount': bonus_amount }, phone=phone ) sms[0].send_message() sms[0].save() else: transaction = transaction[0] transaction.client.save() transaction.client.reload_bonus_score(rebuild=True) if invites: count = instance.client.orders.count() if count == 1: sender = invites[0].sender # use only first sender # invited transaction = BonusTransaction.objects.filter( client=sender, amount=Decimal(str(settings.BONUS_PER_INVITE_ORDER)), description='invited %s user' % instance.client.pk ) if not transaction: transaction = BonusTransaction.objects.create( client=sender, amount=Decimal(str(settings.BONUS_PER_INVITE_ORDER)), description='invited %s user' % instance.client.pk ) else: transaction = transaction[0] transaction.client.save() transaction.client.reload_bonus_score(rebuild=True) # return instance
# -*- coding: utf-8 -*- from pytils import numeral # choose_plural нужен для выбора правильной формы # существительного # у choose_plural два параметра: # 1) amount, количество # 2) variants, варианты # варианты - это кортеж из вариантов склонения # его легко составить по мнемоническому правилу: # (один, два, пять) # т.е. для 1, 2 и 5 объектов, например для слова "пример" # (пример, примера, примеров) print numeral.choose_plural(21, (u"пример", u"примера", u"примеров")) #-> пример print numeral.choose_plural(12, (u"пример", u"примера", u"примеров")) #-> примеров print numeral.choose_plural(32, (u"пример", u"примера", u"примеров")) #-> примера # также можно задавать варианты в одну строку, разделенные запятой print numeral.choose_plural(32, u"пример,примера, примеров") #-> примера # если в варианте используется запятая, она экранируется слешем print numeral.choose_plural(35, u"гвоздь, гвоздя, гвоздей\, шпунтов") #-> гвоздей, шпунтов # зачастую требуется не просто вариант, а вместе с числительным
def rubles(self, sum): "Transform sum number in rubles to text" text_rubles = numeral.rubles(int(sum)) copeck = round((sum - int(sum))*100) text_copeck = numeral.choose_plural(int(copeck), (u"копейка", u"копейки", u"копеек")) return ("%s %02d %s")%(text_rubles, copeck, text_copeck)
def label_buy(self): currency = plugshop_currency(self.price) label = numeral.choose_plural(self.price, ('ruble', 'ruble', 'rubles')) return 'Buy for %s %s' % (currency, label)
def distance_of_time_in_words(from_time, accuracy=1, to_time=None): """ Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{int} @param to_time: target time (in seconds from epoch), default=None translates to current time @type to_time: C{int}, C{float} or C{datetime.datetime} @return: distance of time in words @rtype: unicode @raise ValueError: accuracy is lesser or equal zero """ current = False if to_time is None: current = True to_time = datetime.datetime.now() check_positive(accuracy, strict=True) if not isinstance(from_time, datetime.datetime): from_time = datetime.datetime.fromtimestamp(from_time) if not isinstance(to_time, datetime.datetime): to_time = datetime.datetime.fromtimestamp(to_time) if from_time.tzinfo and not to_time.tzinfo: to_time = to_time.replace(tzinfo=from_time.tzinfo) dt_delta = to_time - from_time difference = dt_delta.days*86400 + dt_delta.seconds minutes_orig = int(abs(difference)/60.0) hours_orig = int(abs(difference)/3600.0) days_orig = int(abs(difference)/86400.0) in_future = from_time > to_time words = [] values = [] alternatives = [] days = days_orig hours = hours_orig - days_orig*24 words.append(u"%d %s" % (days, numeral.choose_plural(days, DAY_VARIANTS))) values.append(days) words.append(u"%d %s" % \ (hours, numeral.choose_plural(hours, HOUR_VARIANTS))) values.append(hours) days == 0 and hours == 1 and current and alternatives.append(u"час") minutes = minutes_orig - hours_orig*60 words.append(u"%d %s" % (minutes, numeral.choose_plural(minutes, MINUTE_VARIANTS))) values.append(minutes) days == 0 and hours == 0 and minutes == 1 and current and \ alternatives.append(u"минуту") # убираем из values и words конечные нули while values and not values[-1]: values.pop() words.pop() # убираем из values и words начальные нули while values and not values[0]: values.pop(0) words.pop(0) limit = min(accuracy, len(words)) real_words = words[:limit] real_values = values[:limit] # снова убираем конечные нули while real_values and not real_values[-1]: real_values.pop() real_words.pop() limit -= 1 real_str = u" ".join(real_words) # альтернативные варианты нужны только если в real_words одно значение # и, вдобавок, если используется текущее время alter_str = limit == 1 and current and alternatives and \ alternatives[0] _result_str = alter_str or real_str result_str = in_future and u"%s %s" % (PREFIX_IN, _result_str) \ or u"%s %s" % (_result_str, SUFFIX_AGO) # если же прошло менее минуты, то real_words -- пустой, и поэтому # нужно брать alternatives[0], а не result_str zero_str = minutes == 0 and not real_words and \ (in_future and u"менее чем через минуту" \ or u"менее минуты назад") # нужно использовать вчера/позавчера/завтра/послезавтра # если days 1..2 и в real_words одно значение day_alternatives = DAY_ALTERNATIVES.get(days, False) alternate_day = day_alternatives and current and limit == 1 and \ ((in_future and day_alternatives[1]) \ or day_alternatives[0]) final_str = not real_words and zero_str or alternate_day or result_str return final_str
session = vk.Session(access_token=vvod_token) api = vk.API(session) info = api.users.get(user_ids=0) main_id = info[0]['uid'] print ('*Успешная авторизация*') print(info[0]['first_name']+' '+info[0]['last_name']+' (https://vk.com/id'+ str(info[0]['uid'])+')') except: print('Токен умер, увы з:') sys.exit() friends = api.friends.get(user_id=main_id,order='hints') print('*Права доступа токена*\n'+access_messages(api)+'\n'+access_status(api)+'\n'+access_friends(api)) print(line) menu = input('Привет, милый <3\nЧто ты хочешь сделать?\n1. Дамп фоток/сообщений\n2. Отправить сообщение на стену\n3. Подписаться на профиль\n4. Установить статус\n5. Лайкнуть фото4ку\n6. Закинуть весь мир в ЧС\n>> ') if menu == '1': count_photos = 0 FreeEnd = str(len(friends))+ ' ' + print_(numeral.choose_plural(len(friends), (u'друг', u'друга', u'друзей'))) print('Всего '+FreeEnd) print('* * * * * * *\nДампим переписки..') SMS = api.messages.get(out='0',count='200') #Тут магия жуткая # РРРРРРРРРРРРРРРР print('Дамп переписок завершен.') print('Дамп фоток..') z = 0 ############################################# for element in friends: i = 1 print(line+'\nФотки от id'+str(friends[z])) photos = api.messages.getHistoryAttachments(peer_id=friends[z],media_type='photo',count='200') for meow in photos: try: