Esempio n. 1
0
 def _write_test_status(self,
                        test_repr: str,
                        location: tp.Tuple[str, int, str],
                        with_progress: bool = False,
                        rewrite: bool = False,
                        newline: bool = False,
                        **markup):
     w = self._tw.fullwidth
     loc = location[2].replace('.', '::')
     if len(loc) > w // 2 - 8:
         loc = textwrap.shorten(loc, w // 2 - 8)
     right = loc + ' [100%]'
     l_left = len(test_repr)
     l_right = len(right) + 1
     if l_left + l_right >= w:
         test_repr = textwrap.shorten(test_repr, w - l_right - 1)
         l_left = len(test_repr)
     if rewrite:
         self.write('\r')
     self.write(test_repr, **markup)
     self.write(' ' * (w - l_left - l_right) + loc, light=True)
     if with_progress:
         self.write(self._get_progress_information_message(), cyan=True)
     else:
         self.write(' [ ~ %]', cyan=True)
     if newline:
         self.write_line('')
Esempio n. 2
0
File: cli.py Progetto: kondziu/6p
    def _display(self, correct, answer, answers=None):
        self._message_window.refresh()
        self._message_window.border()

        text_width = self._width - 2
        text_height = self._height - 2

        self._message_window.refresh()

        if correct:
            self._message_window.addstr(1, int((text_width - 8)/2), "CORRECT!")
        else:
            self._message_window.addstr(1, int((text_width - 6)/2), "WRONG!")


            if self._show_answers_on_fail:
                self._answers_window.clear()
                self._answers_window.border()
                self._answers_window.addstr(0, 1, "[Accepted answers]")

                max_answers = self._answers_height - 2
                display_all_answers = len(answers) <= max_answers
                displayed_answers = answers if display_all_answers else answers[0:max_answers]

                if not display_all_answers:
                    self._answers_window.addstr(self._answers_height - 1, self._width - 7, "[...]")

                for index, answer in enumerate(displayed_answers):
                    self._answers_window.addstr(index + 1, 1, textwrap.shorten(answer, text_width, placeholder = "..."))

                self._answers_window.refresh()
Esempio n. 3
0
def sendChatPushNotification(user, message):
	device = FCMDevice.objects.filter(user = user, active = True).first()

	if not device is None:
		serializer = ChatSerializer(message)

		json_r = json.dumps(serializer.data)
		json_r = json.loads(json_r)
		
		info = {}

		info["data"] = {}
		info["data"]["messages"] = []
		info["data"]["message_sent"] = json_r

		info["message"] = ""
		info["type"] = ""
		info["title"] = ""
		info["success"] = True
		info["number"] = 1
		info['extra'] = 0

		response = json.dumps(info)

		title = str(message.user).join(_(" sent a message"))

		simple_notify = textwrap.shorten(strip_tags(message.text), width = 30, placeholder = "...")

		if message.image:
			simple_notify += " ".join(_("[Photo]"))

		device.send_message(title = str(message.user), body = simple_notify, data = {"response": response, "title": title, "body": simple_notify, "user_from": message.user.email, "user_name": str(message.user), "user_img": message.user.image_url, "type": 'chat', "click_action": 'FLUTTER_NOTIFICATION_CLICK'})
Esempio n. 4
0
 def pack_table(info):
     return '<table>\n' + "\n".join(
         '<tr><td align="right" width="90">{}:</td>\n'
         '<td width="40">{}</td></tr>\n'.format(
             d,
             textwrap.shorten(str(v), width=30, placeholder="..."))
         for d, v in info
     ) + "</table>\n"
Esempio n. 5
0
def main():
    url = 'http://feed.exileed.com/vk/feed/pynsk'

    _section_title = 'Колонка автора'
    _res_title = 'Александр Сапронов (PyNSK)'

    resource = Resource.objects.filter(title=_res_title)
    assert resource.count() == 1, "Not found resoure: %s" % _res_title
    resource = resource[0]

    section = Section.objects.filter(title=_section_title)
    assert section.count() == 1, "Not found section: %s" % _section_title
    section = section[0]

    r = re.compile(r"(htt(p|ps)://[^ ]+)")

    today = datetime.date.today()
    week_before = today - datetime.timedelta(weeks=1)
    rssnews = feedparser.parse(url)
    for n in reversed(rssnews.entries):
        if len(Item.objects.filter(link=n.link)[0:1]):
            continue

        # print("Parse: %s" % n.link)
        title = None
        content = None

        time_struct = getattr(n, 'published_parsed', None)
        if time_struct:
            _timestamp = mktime(time_struct)
            dt = datetime.datetime.fromtimestamp(_timestamp)
            if dt.date() < week_before:
                continue

        text = n.summary
        for x in l:
            if x in text and '<br><br>' in text.split(x)[1]:
                _ = text.split(x)[1].split('<br>')
                title = x + _[0]
                content = ' </br>\n'.join(filter(lambda x: x, _[1:]))

                content = r.sub(r'<a href="\1">\1</a>', content)
                break

        if title is not None and content is not None:
            content_link = "<a href='%s' target='_blank'>[Продолжение]</a>" % n.link
            content = textwrap.shorten(content, width=300, placeholder="...%s" % content_link)\
                .replace('<a...', '...')
            _ = {
                'link': n.link,
                'description': content,
                'title': title,
                'resource': resource,
                'language': 'ru',
                'section': section,
                'status': 'active',
            }
            save_item(_)
def print_content_entry(entry, index = 1):
    assert(isinstance(entry, dict))
    name = entry.pop('name')
    xtype = entry.pop('type')
    print("Name: {} {}".format(name, xtype))
    for k in sorted(entry.keys()):
        value = entry[k]
        if isinstance(value, str):
            value = textwrap.shorten(value, 60)
        print("    {}: {}".format(k, value))
Esempio n. 7
0
def list_commands():
    """ List all commands """
    text = ""
    for n in sorted(Env.COMMANDS):
        c = Env.COMMANDS[n]
        d = c.doc
        a = c.arg_parser
        doc = textwrap.shorten(d,60)
        doc = "%- 20s %s %s\n" % (n, doc, a)
        text += doc
    Env.show(text)
Esempio n. 8
0
 def __enter__(self):
     if self._use_timer:
         self._enter_time = time()
     self._curr_ticks = 0
     self._next_threshold = 0
     # reserving space for percentage
     space = self._lineman.use_width - 4
     line = shorten(self._description, width = space, placeholder = '...')
     line += wrap_color(2, '.' * (space - len(line)))
     self._prefix = line
     self._push_label(wrap_color(3, '  0%'))
     return self
Esempio n. 9
0
    def string(self):
        properties = self._current['properties']

        headline = ' '.join(properties['parameters']['NWSheadline'])
        start = dateutil.parser.parse(properties['effective'])
        end = dateutil.parser.parse(properties['expires'])
        return '{} [ {}({}): FROM {} TO {} -- {} ]'.format(
                self.location.name,
                properties['event'],
                properties['severity'],
                start.strftime('%b %d %X'),
                end.strftime('%b %d %X'),
                textwrap.shorten(headline, width=200))
Esempio n. 10
0
def style_tweet(tweet, porcelain=False):
    if porcelain:
        return "{nick}\t{url}\t{tweet}".format(
            nick=tweet.source.nick,
            url=tweet.source.url,
            tweet=str(tweet))
    else:
        styled_text = format_mentions(tweet.text)
        len_styling = len(styled_text) - len(click.unstyle(styled_text))
        return "➤ {nick} ({time}):\n{tweet}".format(
            nick=click.style(tweet.source.nick, bold=True),
            tweet=textwrap.shorten(styled_text, 140 + len_styling),
            time=click.style(tweet.relative_datetime, dim=True))
Esempio n. 11
0
    def __repr__(self):
        import textwrap

        repr = '{cls}(id={id}, "{text}")'
        args = {
                'cls': self.__class__.__name__,
                'id': hex(id(self))[-4:],
        }
        try:
            args['text'] = textwrap.shorten(self.text, width=10, placeholder='...')
        except:
            repr = '{cls}(id={id})'

        return repr.format(**args)
Esempio n. 12
0
 def __enter__(self):
     '''Printing the subtask description and starts timer if needed'''
     # reverse space for okay/fail label on the right
     space = self._lineman.use_width - 4
     line = shorten(self._description, width = space, placeholder = '...')
     # filling the space between the line end and the label with dots
     line += wrap_color(2, '.' * (space - len(line)))
     self._lineman.append(line, space)
     # whether we need to print label on the right
     # will be disabled when subtasks pushed
     self._need_status_label = True
     if self._use_timer:
         self._enter_time = time()
     return self
Esempio n. 13
0
def notify_user_about_clarification(request, clarification):
    messages.add_message(
        request,
        msg_lvl.INFO_PERSISTENT,
        'На Ваш вопрос был <a href="{}" data-clarification="{}">дан ответ</a>: "{}"'.format(
            clarification.get_absolute_url(),
            clarification.id,
            html.escape(
                textwrap.shorten(html.strip_tags(clarification.answer_html), 70, placeholder='...')
            ),
        ),
        extra_tags='safe',
        user=clarification.user,
    )
Esempio n. 14
0
    def truncate(self, length: int = 75, suffix: str = None) -> 'String':
        """
        Returns the string truncated to fit the given length.

        Args:
            length: The position to truncate the string
            suffix: The string to add after the truncated string

        Returns:
            The truncated string
        """
        return String(textwrap.shorten(self,
                                       width=length,
                                       placeholder=suffix or '...'))
Esempio n. 15
0
def style_tweet(tweet, porcelain=False):
    conf = click.get_current_context().obj["conf"]
    limit = conf.character_limit

    if porcelain:
        return "{nick}\t{url}\t{tweet}".format(nick=tweet.source.nick, url=tweet.source.url, tweet=str(tweet))
    else:
        if sys.stdout.isatty() and not tweet.text.isprintable():
            return None
        styled_text = format_mentions(tweet.text)
        len_styling = len(styled_text) - len(click.unstyle(styled_text))
        final_text = textwrap.shorten(styled_text, limit + len_styling) if limit else styled_text
        timestamp = tweet.absolute_datetime if conf.use_abs_time else tweet.relative_datetime
        return "➤ {nick} ({time}):\n{tweet}".format(
            nick=click.style(tweet.source.nick, bold=True), tweet=final_text, time=click.style(timestamp, dim=True)
        )
Esempio n. 16
0
def style_tweet(tweet, porcelain=False):
    conf = click.get_current_context().obj["conf"]
    limit = conf.character_limit

    if porcelain:
        return "{nick}\t{url}\t{tweet}".format(
            nick=tweet.source.nick,
            url=tweet.source.url,
            tweet=str(tweet))
    else:
        styled_text = format_mentions(tweet.text)
        len_styling = len(styled_text) - len(click.unstyle(styled_text))
        final_text = textwrap.shorten(styled_text, limit + len_styling) if limit else styled_text
        return "➤ {nick} ({time}):\n{tweet}".format(
            nick=click.style(tweet.source.nick, bold=True),
            tweet=final_text,
            time=click.style(tweet.relative_datetime, dim=True))
Esempio n. 17
0
def do_tweet(text, weather_location, tweet_location, variable_location, hashtag=None):
    """
    Post a tweet.
    If set in the config, a hashtag will be applied to the end of the tweet.
    If variable_location is True, prepend the tweet with the location name.
    If tweet_location is True, the coordinates of the the location will be embedded in the tweet.
    If successful, the status id is returned, otherwise None.
    :type text: str
    :param text: text for the tweet
    :type weather_location: models.WeatherLocation
    :param weather_location: location information used for the tweet location and inline location name
    :type tweet_location: bool
    :param tweet_location: determines whether or not to include Twitter location
    :type variable_location: bool
    :param variable_location: determines whether or not to prefix the tweet with the location
    :type hashtag: str
    :param hashtag:
    :return: a tweepy status object
    """
    api = get_tweepy_api()
    body = text
    # account for space before hashtag
    max_length = 279 - len(hashtag) if hashtag else 280

    if variable_location:
        body = weather_location.name + ': ' + body

    logging.debug('Trying to tweet: %s', body)
    if len(body) > max_length:
        # horizontal ellipsis
        body = textwrap.shorten(body, width=max_length, placeholder='\u2026')
        logging.warning('Status text is too long, tweeting the following instead: %s', body)

    if hashtag:
        body += ' ' + hashtag
    try:
        if tweet_location:
            status = api.update_status(status=body, lat=weather_location.lat, long=weather_location.lng)
        else:
            status = api.update_status(status=body)
        logging.info('Tweet success: %s', body)
        return status
    except tweepy.TweepError as err:
        logging.error('Tweet failed: %s', err.reason)
        logging.warning('Tweet skipped due to error: %s', body)
        return None
Esempio n. 18
0
def set_pastes():
    pastes = list(db.get_pastes())

    for index, element in enumerate(paste_elements):
        # To few pastes available
        if index >= len(pastes):
            element["text"].config(text="")
            element["date"].config(text="")
            element["button"].config(text="")
            element["button"].bind("<Button-1>", lambda x: None)
            element["button"].lower()
            continue

        element["text"].config(text=textwrap.shorten(pastes[index].text, width=50, placeholder="..."))
        element["date"].config(text=pastes[index].date.strftime("%d. %B %Y %H:%M:%S"))
        element["button"].config(text="Copy")
        element["button"].bind("<Button-1>", lambda x: copy_from_history(pastes[index].text))
Esempio n. 19
0
    def handle(self, sender, target, tokens, bot):
        if len(tokens) < 2:
            for line in self.help_text:
                bot.send_privmsg(sender, line)
            return

        search_title = ' '.join(tokens[1:])
        try:
            page = wikipedia.page(search_title)
        except wikipedia.exceptions.DisambiguationError as err:
            m = 'Your query returned a disambiguation page.'
            bot.send_privmsg(sender, m)
            if len(err.options) < 6:
                m = 'Options: {}'.format(u'; '.join(err.options))
                bot.send_privmsg(sender, m)
            else:
                opts_list = u'; '.join(err.options[:6])
                m = 'Some options: {} ...'.format(opts_list)
                bot.send_privmsg(sender, m)
            return
        except wikipedia.exceptions.PageError as err:
            bot.send_privmsg(sender, str(err))
            return

        summ = textwrap.shorten(page.summary, width=300, placeholder=' ...')
        m = '{} // {} [ {} ]'.format(page.title, summ, page.url)

        if not bot.is_irc_channel(target):
            bot.send_privmsg(sender, m)
            return

        now = int(time.time())
        last = int(bot.c.get('wiki:last', 0))
        wait = int(bot.c.get('wiki:wait', 0))
        if last < now - wait:
            bot.send_privmsg(target, m)
            bot.c.set('wiki:last', now)
        else:
            bot.send_privmsg(sender, m)
            remaining = last + wait - now
            m = 'I am cooling down. You cannot use {}'.format(tokens[0])
            m = '{} in {} for another'.format(m, target)
            m = '{} {} seconds.'.format(m, remaining)
            bot.send_privmsg(sender, m)
Esempio n. 20
0
    def form_valid(self, form):
        message = form.cleaned_data.get('comment')
        image = form.cleaned_data.get("image",'')
        users = (self.request.POST.get('users[]','')).split(",")
        user = self.request.user
        subject = self.questionary.topic.subject

        if (users[0] is not ''):
            for u in users:
                to_user = User.objects.get(email=u)
                talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user)
                created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image)

                simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...")

                if image is not '':
                    simple_notify += " ".join(_("[Photo]"))
                
                notification = {
                    "type": "chat",
                    "subtype": "subject",
                    "space": subject.slug,
                    "user_icon": created.user.image_url,
                    "notify_title": str(created.user),
                    "simple_notify": simple_notify,
                    "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}),
                    "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request),
                    "container": "chat-" + str(created.user.id),
                    "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT"))
                }

                notification = json.dumps(notification)

                Group("user-%s" % to_user.id).send({'text': notification})

                ChatVisualizations.objects.create(viewed = False, message = created, user = to_user)
            
            success = str(_('The message was successfull sent!'))
            return JsonResponse({"message":success})

        erro = HttpResponse(str(_("No user selected!")))
        erro.status_code = 404
        return erro
Esempio n. 21
0
def format_quote(quote, short=False):
    """Returns a human-readable string representation of a Quote object.

    :param quote: helga.plugins.quotes.Quote
    :param short: bool
    :return: str
    """
    if short:
            return "#{quote_id}: „<{author}> {text}“".format(
                    quote_id=quote.quote_id,
                    author=quote.author.first_name,
                    text=textwrap.shorten(quote.text, 50))
    else:
            return "Quote #{quote_id}: „<{author}> {text}“ (added by {added_by} at {date})".format(
                    quote_id=quote.quote_id,
                    author=quote.author.first_name,
                    text=quote.text.replace('\n', ' '),
                    added_by=quote.added_by.first_name,
                    date=format_timestamp(quote.date))
Esempio n. 22
0
    async def twitter_search(self, query, limit=5):
        """Searches for a Twitter user.

        To use a multi-word query, enclose it in quotes.
        """
        try:
            results = await self.bot.loop.run_in_executor(None, self.api.search_users, query, limit)
        except tweepy.TweepError as e:
            log.error(str(e))
            raise TwitterError('Unknown error from the Twitter API, this has been logged.') from e
        if not results:
            raise TwitterError('No result.')

        embed = discord.Embed(colour=0x738bd7)
        for user in results:
            name = '{} - @{}'.format(user.name, user.screen_name)
            description = textwrap.shorten(user.description, 1024) if user.description else 'No description.'
            embed.add_field(name=name, value=description, inline=False)
        await self.bot.say(embed=embed)
Esempio n. 23
0
    async def rip(self, ctx, member_or_text: str):
        """RIP\nCreates a tombstone for either a member or some text. Mention a member to get the avatar + name"""
        if ctx.message.mentions:
            user_name = ctx.message.mentions[0].name.replace(" ", "%20")
            rip_member = ctx.message.mentions[0]
            ava_url = rip_member.avatar_url
            url = "https://ripme.xyz/{}"
            msg = url.format(user_name)

            tomb = Image.open(os.path.join(asset_pos, "tombstone.png"))
            base_img = Image.new("RGBA", (tomb.width, tomb.height), color="White")
            with aiohttp.ClientSession() as session:
                async with session.get(ava_url) as resp:
                    ava = await resp.content.read()

            ava_img = Image.open(io.BytesIO(ava))
            ava_img_greyscale = ImageOps.autocontrast(ava_img.convert("L").filter(ImageFilter.CONTOUR)).filter(
                ImageFilter.SMOOTH).resize((200, 200))
            base_img.paste(ava_img_greyscale, (140, 380, 340, 580))
            final = ImageChops.multiply(base_img, tomb)
            f = ImageFont.truetype(os.path.join(asset_pos, "Symbola.ttf"), size=35)
            d = ImageDraw.Draw(final)
            w, h = d.textsize(rip_member.name, font=f)
            d.multiline_text(((60 + ((350 - w) / 2)), 315), rip_member.name, fill="Black", font=f, align="center")
            final.save(os.path.join(asset_pos, "rip.png"))
            await self.bot.send_file(ctx.message.channel, os.path.join(asset_pos, "rip.png"), content=msg)
        else:
            content = ctx.message.content.partition(" ")
            user_name = content[2].replace(" ", "_")
            url = "https://ripme.xyz/{}"
            msg = url.format(user_name)
            base_img = Image.new("RGB", (520, 640), color="White")
            tomb = Image.open(os.path.join(asset_pos, "tombstone.png"))
            base_img.paste(tomb)
            f = ImageFont.truetype(os.path.join(asset_pos, "Symbola.ttf"), size=35)
            d = ImageDraw.Draw(base_img)
            text = textwrap.shorten(content[2], width=25, placeholder="")
            w, h = d.textsize(text, font=f)
            d.text(((60 + ((350 - w) / 2)), 315), text, fill="Black", font=f, align="center")
            d.text((160, 450), "2016 - 2016", fill="Black", font=f)
            base_img.save(os.path.join(asset_pos, "rip.jpeg"))
            await self.bot.send_file(ctx.message.channel, os.path.join(asset_pos, "rip.jpeg"), content=msg)
Esempio n. 24
0
    async def wiki(self, ctx: cmds.Context, *, search_terms: str):
        """Look up information on Wikipedia."""

        try:
            page = wikipedia.page(search_terms)
        except wikipedia.exceptions.DisambiguationError as err:
            await ctx.author.send('Your query returned a disambiguation page.')
            if len(err.options) < 6:
                opts_list = '; '.join(err.options)
                await ctx.author.send(f'Options: {opts_list}')
            else:
                opts_list = '; '.join(err.options[:6])
                await ctx.author.send(f'Some options: {opts_list} ...')
            return
        except wikipedia.exceptions.PageError as err:
            await ctx.author.send(str(err))
            return

        summary = textwrap.shorten(page.summary, width=300, placeholder=' ...')
        await ctx.send(f'{page.title} // {summary} [ {page.url} ]')
Esempio n. 25
0
def api_request(url, data):

    response = requests.post(
        url,
        headers={'Content-Type': 'application/json'},
        auth=(settings.API_USERNAME, settings.API_PASSWORD),
        data=json.dumps(data)
    )

    try:
        return response.json()
    except json.JSONDecodeError:
        raise APIResponseInvalidJson(
            "The response from the Adyen API was invalid JSON:\n"
            "  Status code: {}\n"
            "  Body: {}".format(
                response.status_code,
                textwrap.shorten(response.text, width=75)
            )
        )
Esempio n. 26
0
    def send_sms(self, message, ignore_last_sms_timestamp=False):
        if not ignore_last_sms_timestamp and (
                datetime.utcnow() - self.last_sms_timestamp).total_seconds() < self.backoff_timeout_in_sec:
            log.warning('Not sending SMS, recently already sent an SMS')
            return

        log.info('Trying to send SMS with text: {}'.format(str(message)))

        try:
            trimmed_message = textwrap.shorten(str(message), 100)
            headers = {'Authorization': 'AccessKey ' + self.sms_api_key, 'accept': 'application/json'}
            payload = {'type': 'sms',
                       'originator': self.sms_from_number,
                       'body': 'Alarm notification! Unexpected event: {}'.format(trimmed_message),
                       'recipients': [self.sms_to_number]}
            resp = requests.post(MSG_BIRD_BASE_URI + MSG_BIRD_API_MESSAGE, headers=headers, data=payload)
            log.info('SMS response: ' + str(resp.json()))

            if not ignore_last_sms_timestamp:
                self.last_sms_timestamp = datetime.utcnow()
        except requests.exceptions.RequestException:
            log.exception('Failed to send SMS!')
Esempio n. 27
0
def RecordPatch(*args, **kwargs):
    # raise_attr_exception=False
    mrm = MyRedmine()

    issueChoices = [(0, "None")] + [(i.id, "#{}: {}".format(i.id, i.subject)) for i in
                                    mrm.my_issues]

    releaseChoices = [(0, "None")] + [
        (int(r['Nr']), "{}: {}".format(r['Nr'], shorten(r['Beschreibung'], 80))) for r in
        get_releasetest_issues(assignee=Config.GSPREAD_ASSIGNEE)]

    class RecordPatch(CancelDataset):
        prefix = di.ChoiceItem('Prefix', [(p, p.name) for p in Prefixes])
        tracker = di.ChoiceItem("Tracker", issueChoices, default=0)
        rtest = di.ChoiceItem("Releasetest", releaseChoices, default=0)

        name = di.StringItem("Name", notempty=True)
        author = di.StringItem("Author", notempty=True, default=Config.AUTHOR)

        @property
        def Prefix(self):
            return self.prefix.Name(self.tracker, self.rtest)

        @property
        def FormattedName(self):
            return '{}: {}'.format(self.Prefix, self.name)

        def check_prefix(self):
            if not self.prefix.hasParameter:
                return False
            return self.tracker > 0 or self.rtest


        def read(self, p: Patch):
            prefix, name = p.title.split(': ', 1)
            self.name = name
            self.prefix, self.tracker, self.rtest = Prefixes.read(prefix)

    return RecordPatch(*args, **kwargs)
Esempio n. 28
0
def brodcast_dificulties(request, message, subject):
	msg = TalkMessages()
	msg.text = message
	msg.user = request.user
	msg.subject = subject

	simple_notify = textwrap.shorten(strip_tags(msg.text), width = 30, placeholder = "...")
	
	for p in subject.professor.all():
		talks = Conversation.objects.filter((Q(user_one = request.user) & Q(user_two__email = p.email)) | (Q(user_two = request.user) & Q(user_one__email = p.email)))
		
		if talks.count() > 0:
			msg.talk = talks[0]
		else:
			msg.talk = Conversation.objects.create(user_one = request.user, user_two = p)

		msg.save()

		notification = {
			"type": "chat",
			"subtype": subject.slug,
			"space": "subject",
			"user_icon": request.user.image_url,
			"notify_title": str(request.user),
			"simple_notify": simple_notify,
			"view_url": reverse("chat:view_message", args = (msg.id, ), kwargs = {}),
			"complete": render_to_string("chat/_message.html", {"talk_msg": msg}, request),
			"container": "chat-" + str(request.user.id),
			"last_date": _("Last message in %s")%(formats.date_format(msg.create_date, "SHORT_DATETIME_FORMAT"))
		}

		notification = json.dumps(notification)

		Group("user-%s" % p.id).send({'text': notification})

		sendChatPushNotification(p, msg)

		ChatVisualizations.objects.create(viewed = False, message = msg, user = p)
Esempio n. 29
0
def QuickEditIssue(*args, **kwargs):
    # raise_attr_exception=False
    mrm = MyRedmine()

    issueChoices = [(i, "#{} ({}: {}%)".format(i, i.status, i.done_ratio)) for i in
                    mrm.my_issues_filtered(**kwargs)]
    statusChoices = [(0, "Dont Change")] + [(s, s.name) for s in mrm.issue_statuses]
    releaseChoices = [(int(r['Nr']), "{}: {}".format(r['Nr'], shorten(r['Beschreibung'], 50))) for
                      r in
                      get_releasetest_issues()]

    if not issueChoices:
        message("Nope", "There are no new Issues for you.")
        return

    class QuickIssue(CancelDataset):
        issue = di.ChoiceItem("Issue", issueChoices)
        rtest = di.ChoiceItem("Releasetest", releaseChoices)
        status = di.ChoiceItem("Status", statusChoices, default=0)
        progress = di.IntItem("Progress", min=0, max=100, slider=True, default=0)
        comment = di.TextItem("Comment")

    return QuickIssue(*args)
Esempio n. 30
0
    def __get_book(self, now):
        # Faz duas tentativas para obter o livro do dia, por questões de possível cache antigo.
        for _ in range(2):
            book = self.resources.get_packt_free_book()
            if book is None:
                continue

            delta = datetime.datetime.fromtimestamp(book.expires, tz=AJU_TZ) - now
            delta = delta.total_seconds()
            if delta < 0:
                continue

            summary = textwrap.shorten(book.summary, 150, placeholder=r' \[...]')
            response = (
                "Confira o livro gratuito de hoje da Packt Publishing 🎁\n\n"
                "📖 [%s](%s)\n"
                "🔎 %s\n"
            ) % (book.name, Resources.BOOK_URL, summary)

            for left in TIME_LEFT:
                if delta <= left:
                    return book, response, left
            else:
                left = None

            break

        # As tentativas falharam...
        else:
            Resources.cache.invalidate(Resources.get_packt_free_book, "get_packt_free_book")
            book = None
            response = "Parece que não tem um livro grátis hoje 😡\n\n" \
                       "Se acha que é um erro meu, veja com seus próprios olhos em " + Resources.BOOK_URL
            left = None

        return book, response, left
Esempio n. 31
0
 def test_width_too_small_for_placeholder(self):
     shorten("x" * 20, width=8, placeholder="(......)")
     with self.assertRaises(ValueError):
         shorten("x" * 20, width=8, placeholder="(.......)")
Esempio n. 32
0
    async def send_email(self, *, user: Dict[str, Any],
                         user_ctx: Dict[str, Any], subject: str, title: str,
                         body: str, template: str, e_from: str,
                         reply_to: Optional[str], global_ctx: Dict[str, Any],
                         attachment: Optional[Attachment],
                         tags: Dict[str, str], company_id: int):
        base_url = global_ctx['base_url']

        full_name = '{first_name} {last_name}'.format(
            first_name=user['first_name'] or '',
            last_name=user['last_name'] or '',
        ).strip(' ')
        user_email = user['email']
        extra_ctx = dict(
            first_name=user['first_name'] or user['last_name'] or '',
            full_name=full_name or 'user',
            unsubscribe_link=
            f'/api/unsubscribe/{user["id"]}/?sig={unsubscribe_sig(user["id"], self.settings)}',
        )
        ctx = clean_ctx({**global_ctx, **extra_ctx, **user_ctx}, base_url)
        markup_data = ctx.pop('markup_data', None)

        e_msg = EmailMessage(policy=SMTP)
        subject = chevron.render(subject, data=ctx)
        e_msg['Subject'] = subject
        e_msg['From'] = e_from
        if reply_to:
            e_msg['Reply-To'] = reply_to
        e_msg[
            'To'] = f'{full_name} <{user_email}>' if full_name else user_email
        e_msg['List-Unsubscribe'] = '<{unsubscribe_link}>'.format(**ctx)
        e_msg['X-SES-CONFIGURATION-SET'] = 'nosht'
        e_msg['X-SES-MESSAGE-TAGS'] = ', '.join(f'{k}={v}'
                                                for k, v in tags.items())

        if DEBUG_PRINT_REGEX.search(body):
            ctx['__debug_context__'] = f'```{json.dumps(ctx, indent=2)}```'

        body = apply_macros(body)
        body = chevron.render(body, data=ctx)
        raw_body = re.sub(r'\n{3,}', '\n\n', body).strip('\n')
        e_msg.set_content(raw_body, cte='quoted-printable')

        ctx.update(
            styles=STYLES,
            main_message=safe_markdown(raw_body),
            message_preview=shorten(strip_markdown(raw_body),
                                    60,
                                    placeholder='…'),
        )
        if markup_data:
            ctx['markup_data'] = json.dumps(markup_data, separators=(',', ':'))
        html_body = chevron.render(template,
                                   data=ctx,
                                   partials_dict={'title': title})
        e_msg.add_alternative(html_body,
                              subtype='html',
                              cte='quoted-printable')
        if attachment:
            maintype, subtype = attachment.mime_type.split('/')
            e_msg.add_attachment(
                attachment.content.encode(),
                maintype=maintype,
                subtype=subtype,
                filename=attachment.filename,
            )

        if self.send_via_aws and user_email.endswith('example.com'):
            logger.info(
                'email not sent "%s" to "%s" because it ends "example.com"',
                subject, user_email)
            return

        send_method = self.aws_send if self.send_via_aws else self.print_email
        msg_id = await send_method(e_from=e_from,
                                   to=[user_email],
                                   email_msg=e_msg)

        await self.pg.execute(
            """
            insert into emails (company, user_id, ext_id, trigger, subject, address)
            values ($1, $2, $3, $4, $5, $6)
            """, company_id, user['id'], msg_id, tags['trigger'], subject,
            user_email)
Esempio n. 33
0
    async def apply_ban(self,
                        ctx: Context,
                        user: UserSnowflake,
                        reason: t.Optional[str],
                        purge_days: t.Optional[int] = 0,
                        **kwargs) -> None:
        """
        Apply a ban infraction with kwargs passed to `post_infraction`.

        Will also remove the banned user from the Big Brother watch list if applicable.
        """
        # In the case of a permanent ban, we don't need get_active_infractions to tell us if one is active
        is_temporary = kwargs.get("expires_at") is not None
        active_infraction = await _utils.get_active_infraction(
            ctx, user, "ban", is_temporary)

        if active_infraction:
            if is_temporary:
                log.trace(
                    "Tempban ignored as it cannot overwrite an active ban.")
                return

            if active_infraction.get('expires_at') is None:
                log.trace("Permaban already exists, notify.")
                await ctx.send(
                    f":x: User is already permanently banned (#{active_infraction['id']})."
                )
                return

            log.trace("Old tempban is being replaced by new permaban.")
            await self.pardon_infraction(ctx, "ban", user, is_temporary)

        infraction = await _utils.post_infraction(ctx,
                                                  user,
                                                  "ban",
                                                  reason,
                                                  active=True,
                                                  **kwargs)
        if infraction is None:
            return

        self.mod_log.ignore(Event.member_remove, user.id)

        if reason:
            reason = textwrap.shorten(reason, width=512, placeholder="...")

        action = ctx.guild.ban(user,
                               reason=reason,
                               delete_message_days=purge_days)
        await self.apply_infraction(ctx, infraction, user, action)

        if infraction.get('expires_at') is not None:
            log.trace(
                f"Ban isn't permanent; user {user} won't be unwatched by Big Brother."
            )
            return

        bb_cog = self.bot.get_cog("Big Brother")
        if not bb_cog:
            log.error(
                f"Big Brother cog not loaded; perma-banned user {user} won't be unwatched."
            )
            return

        log.trace(
            f"Big Brother cog loaded; attempting to unwatch perma-banned user {user}."
        )

        bb_reason = "User has been permanently banned from the server. Automatically removed."
        await bb_cog.apply_unwatch(ctx, user, bb_reason, send_message=False)
Esempio n. 34
0
 def build_status(self, text):
     return textwrap.shorten(text, width=280, placeholder="...")
Esempio n. 35
0
 def __str__(self):
     return textwrap.shorten("{0.name}".format(self), 40)
Esempio n. 36
0
# 	print(textwrap.fill(dedented_text, width=width))
# 	print()

# indenting blog
# dedented_text = textwrap.dedent(sample_text)
# wrapped = textwrap.fill(dedented_text, width=50)
# wrapped += '\n\nSecond paragraph after a blank line.'
# final = textwrap.indent(wrapped, '> ')
# print('Quoted block:\n')
# print(final)

# hanging indent

# dedented_text = textwrap.dedent(sample_text).strip()
# print(textwrap.fill(dedented_text,
# initial_indent='',
# subsequent_indent=' ' * 4,
# width=50,
# ))

# Truncating long text
dedented_text = textwrap.dedent(sample_text)
original = textwrap.fill(dedented_text, width=50)
print('Original:\n')
print(original)

shortened = textwrap.shorten(original, 100)
shortened_wrapped = textwrap.fill(shortened, width=50)
print('\nShortened:\n')
print(shortened_wrapped)
Esempio n. 37
0
def cquery_render(s):
    terms = s
    mquery = '''
    query {
        Page(page:1, perPage:5) {
            characters(search: %s) {
                name { full }
                media(perPage: 2) {
                    nodes {
                        id
                        title {
                            romaji
                            native
                            english
                        }
                        type
                        format
                        status
                        description
                        season
                        startDate { year }
                        episodes
                        duration
                        coverImage {
                            medium
                            large
                        }
                        genres
                        isAdult
                        tags { name }
                        airingSchedule {
                            nodes {
                                timeUntilAiring
                                episode
                            }
                        }
                    }
                }
            }
        }
    }
    ''' % json.dumps(s)
    print('query is', mquery)
    media = simple_query(litquery=mquery)
    print('Got result', media)
    characters = media['data']['Page']['characters']
    media = [(textwrap.shorten(x['name']['full'], width=15,
                               placeholder='...'), y) for x in characters
             for y in x['media']['nodes']]
    responses = [
        InlineQueryResultArticle(
            id=uuid4(),
            title=
            f"{'R' if len(media) else 'There were no r'}esults for query '{terms}'",
            input_message_content=InputTextMessageContent(
                'Y u clickin\' this?'))
    ]

    def timefmt(t):
        if not t:
            return '???'
        if t < 3600:
            return 'about an hour or so'
        if t < 24 * 3600:
            return f'about {t/3600} hours or so'
        return f'{int(t/(3600*24))} days'

    def nextEpisode(episodes: list):
        eps, time = None, None
        for ex in episodes:
            if ex['timeUntilAiring'] > 0:
                eps = ex['episode']
                time = ex['timeUntilAiring']
                break

        return f"episode {eps or '???'} in {timefmt(time)}"

    for n, m in media:
        responses.append(
            InlineQueryResultArticle(
                id=uuid4(),
                title=
                (lambda t:
                 f"[{n}] {'[🌶] ' if m['isAdult'] else ''}[{m['format']}] {t['english'] or t['romaji']}"
                 )(m['title']),
                thumb_url=m['coverImage']['medium'],
                input_message_content=InputTextMessageContent((
                    f"<b>{m['title']['english'] or m['title']['romaji']} ({m['startDate']['year']})</b>\n"
                    + f"Original name: {m['title']['native']}\n" +
                    f"Romaji name: {m['title']['romaji']}\n" +
                    f"Status: {m['status']}\n" +
                    f"Genres: {', '.join(m.get('genres', None) or ['Nothing'])}\n"
                    +
                    f"Tags: {', '.join(i['name'] for i in (m.get('tags', []))) or 'Nothing'}\n"
                    + f"Total episode count: {m['episodes']}\n" +
                    (f"Next episode: {nextEpisode(m['airingSchedule']['nodes'])}\n"
                     if m['status'] == 'RELEASING' else '') +
                    '\nHere be dragons\n' +
                    f"Description: {strip_tags(m['description'])}\n" +
                    f"<a href=\"{m['coverImage']['large']}\"> Cover Image </a>"
                ),
                                                              parse_mode='HTML'
                                                              )))
    return responses
Esempio n. 38
0
# Text Wrap Module
import textwrap

websiteText = """   Learning can happen anywhere with our apps on your computer,
mobile device, and TV, featuring enhanced navigation and faster streaming
for anytime learning. Limitless learning, limitless possibilities."""

print("No Dedent:")
print(textwrap.fill(websiteText))

print("Dedent")
dedent_text = textwrap.dedent(websiteText).strip()
print(dedent_text)

print("Fill")
print()
print(textwrap.fill(dedent_text, width=50))
print(textwrap.fill(dedent_text, width=100))

print("Controlling Indent")
print(
    textwrap.fill(dedent_text,
                  initial_indent="   ",
                  subsequent_indent="          "))

print("Shortening Text")
short = textwrap.shorten("LinkedIn.com is great!", width=15, placeholder="...")
print(short)
Esempio n. 39
0
    async def on_command_error(self, ctx, error):
        if ctx.command and ctx.command.has_error_handler():
            return

        if ctx.cog and ctx.cog.has_error_handler():
            return

        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.MissingRequiredArgument):
            argument = error.param.name
            await ctx.send(f"You are missing a required argument: `{argument}`"
                           )

        elif isinstance(error, commands.BadArgument):
            await ctx.send(error or "You are using a bad argument.")

        elif isinstance(error, commands.MissingPermissions):
            await ctx.send("You don't have enough permissions.")

        elif isinstance(error, checks.MemberOnCooldown):
            seconds = round(error.retry_after, 2)
            await ctx.send(
                f"You are on cooldown. Wait `{seconds}s` before running another command."
            )

        elif isinstance(error, commands.CommandOnCooldown):
            command = ctx.command.qualified_name
            seconds = round(error.retry_after, 2)
            await ctx.send(
                f"You can't use `{command}` command for `{seconds}s`.")

        elif isinstance(error, commands.NoPrivateMessage):
            await ctx.author.send(
                "This command can't be used in direct messages.")

        elif isinstance(error, commands.NotOwner):
            await ctx.send("It seems you do not own this bot.")

        elif isinstance(error, commands.CheckFailure):
            if type(error) == checks.ProfileNotLinked:
                await ctx.send(
                    f'You haven\'t linked a profile yet. Use "{ctx.prefix}profile link" to start.'
                )

            elif type(error) == checks.ProfileLimitReached:
                if error.limit == 5:
                    premium = self.bot.config.premium
                    embed = discord.Embed(color=discord.Color.red())
                    embed.description = (
                        "Maximum limit of profiles reached.\n"
                        f"[Upgrade to Premium]({premium}) to be able to link up to 25 profiles."
                    )
                    await ctx.send(embed=embed)
                else:
                    await ctx.send("Maximum limit of profiles reached.")

            elif type(error) == checks.MemberNotPremium:
                premium = self.bot.config.premium
                embed = discord.Embed(color=discord.Color.red())
                embed.description = (
                    "This command requires a Premium membership.\n"
                    f"[Click here]({premium}) to have a look at the Premium plans."
                )
                await ctx.send(embed=embed)

        elif isinstance(error, commands.CommandInvokeError):
            original = error.original
            group = (RequestError, ProfileException, NoChoice, PaginationError)
            if isinstance(original, discord.HTTPException):
                return
            elif isinstance(original, DataError):
                await ctx.send("The argument you entered cannot be handled.")
            elif isinstance(original, group):
                await ctx.send(original)
            else:
                embed = discord.Embed(color=discord.Color.red())
                embed.set_author(name=str(ctx.author),
                                 icon_url=ctx.author.display_avatar)
                embed.add_field(name="Command",
                                value=ctx.command.qualified_name)
                content = textwrap.shorten(ctx.message.content, width=512)
                embed.add_field(name="Content", value=content)
                if ctx.guild:
                    guild = f"{str(ctx.guild)} ({ctx.guild.id})"
                    embed.add_field(name="Guild", value=guild, inline=False)
                try:
                    exc = "".join(
                        traceback.format_exception(
                            type(original),
                            original,
                            original.__traceback__,
                            chain=False,
                        ))
                except AttributeError:
                    exc = f"{type(original)}\n{original}"
                embed.description = f"```py\n{exc}\n```"
                embed.timestamp = ctx.message.created_at
                if not self.bot.debug:
                    await self.bot.webhook.send(embed=embed)
                else:
                    print(original, type(original))
                await ctx.send(
                    "This command ran into an error. The incident has been reported and will be fixed as soon as possible!"
                )
Esempio n. 40
0
 def snippet(self):
     body_snippet = textwrap.shorten(self.body, width=35, placeholder='...')
     # Define here rather than in __str__ so we can use it in the admin list_display
     return '{author} - {snippet}...'.format(author=self.author_text,
                                             snippet=body_snippet)
Esempio n. 41
0
def news_scrapper():
 import textwrap
 import requests
 from bs4 import BeautifulSoup
 import pandas as pd

 #API CALL TO Greek google news
 news_url=' https://news.google.com/rss?hl=el&gl=GR&ceid=GR:el.'
 # downloads the page
 rss_text = requests.get(news_url).text
 # create an instance in xml form 
 soup_page=BeautifulSoup(rss_text,"xml")
 def get_items(soup):
 # function that gets all the headlines and contents of the news 
 # INPUT: all the instance of beautiful soup
 # OUTPUT: the title and content of the news item
 # the process before the yield is performed one time 
    for news in soup.findAll("item"):
#       
#        s = BeautifulSoup(news.description.text, 'lxml')
#        a = s.select('a')[-1]
#        a.extract()         # extract lat 'See more on Google News..' link

        html = requests.get(news.link.text)
        soup_content = BeautifulSoup(html.text,"lxml")

#        # perform basic sanitization:
#        for t in soup_content.select('script, noscript, style, iframe, nav, footer, header'):
#            t.extract()
       # give the headline title and the content of the news
       # every time that the function is called give away one item 
        yield news.title.text.strip(), str(soup_content.select_one('body').text)
        # increase the increment of the for loop at the end of the loop so to be ready 
        # for the next iteration 

 # Defining a dictionary for words relevant to coronavirus
 thisdict = {"κορωναϊό","κοροναϊό","COVID-19","κορονοϊό","κορωνοϊό","coronavirus"}

 titles=[]
 contents=[]

 # Initializing the first lines of the csv
 # titles.append("TITLE")
 # contents.append("CONTENT")
 
 # maximum width of the line 
 width = 80
 # Extracting only title and content of the articles that contain any of the words that we specify in the dictionary
 for (title,content) in get_items(soup_page):
    # wrap the headline in lines, per line maximim width of 80 characters
    title = '\n'.join(textwrap.wrap(title, width))
    # wrap each line so that it has width of 80 characters, 
    # and shorten the text so that it show 1024 characters 
    content = '\n'.join(textwrap.wrap(textwrap.shorten(content, 1024), width))

    # Filtering out the articles in which the titles does not contain any word relevant to coronavirus
    for value in thisdict:
        if title.find(value):
            titles.append(title)
        if content.find(value):
            contents.append(content)
# zip means pair first element of one list with first element from the other 
 df = pd.DataFrame(list(zip(titles, contents)))
 print(df.iloc[8])
 df.columns = ['title', 'content']
 return df
def parsePage(items, browser, occuranceCount):
	soup = browser.get_current_page()
	foldername = soup.select(".pp-subfolder-self")[0].get_text()


	for div in soup.find_all(class_="pp-pub-item"):
		initialdata = re.sub(r"<[^>]+>", "", div.find(ppdata=True)['ppdata'])

		jsondata = json.loads(initialdata)

		
		catpage = re.sub(r"(https://paperpile.com/shared/\w+)/[0-9]+$", r"\1", browser.get_url())
		#print(catpage, browser.get_url())
		jsondata['category_page'] = [catpage]



		if "keywords" in jsondata:
			jsondata['keywords'] = [ x.title().strip() for x in re.split(r'[;,] *', jsondata['keywords']) if x.title().strip() ]
		else:
			jsondata['keywords'] = ['No Keywords']
		# pprint(jsondata)
		if "url" in jsondata:
			jsondata['docurls'] = jsondata['url']
			del jsondata['url']

		jsondata['jsonauthors'] = jsondata['author']
		authors = []
		citationauthor = []
		for j, author in enumerate(jsondata['author']):			
			
			if "last" in author and "first" in author:
				authors.append("{}, {}".format(author['last'], author['first']))
				initials = ""
				for i, initial in enumerate(author['initials']):
					if initial != " ":
						initials += "{}.".format(initial)
						if i < len(author['initials'])-1:
							initials += " "
				citationauthor.append("{}, {}".format(author['last'], initials))
			elif "last" in author:
				authors.append("{}".format(author['last']))
				citationauthor.append("{}".format(author['last']))
			elif "collective" in author:
				authors.append(re.sub(r' +', '_', "{}".format(author['collective'])))
				citationauthor.append(author['collective'])
			else:
				raise ValueError(author)
		authorout = authors
		if len(authorout) > 2:
			authorout = authors[:2]+['etal']
		if authors == []:
			authorout.append(jsondata['title'])

		citationauthorstring = ""
		for i, a in enumerate(citationauthor):
			if i < len(citationauthor) -2:
				citationauthorstring += "{}, ".format(a)
			elif i == len(citationauthor)-2:
				citationauthorstring += "{}, & ".format(a)
			else:
				citationauthorstring += "{}".format(a)

		jsondata['citationauthor'] = citationauthorstring
		# authorstring= '-'.join([ "{}".format(author['last']) for author in jsondata['author']] )
		authorstring = textwrap.shorten(re.sub(r'[^A-Za-z0-9-,;+]+', '-', '+'.join(authorout)), width=50, placeholder="+etal")
		jsondata['author'] = '; '.join(authors)

		if "published" in jsondata:
			year = jsondata['published']['year']
		else:
			jsondata['published'] = {}
			jsondata['published']['year'] = "n.d."
			year = "n.d."

		occuranceKey = "{}-{}".format('-'.join(authorout).upper(), jsondata['title'].upper())
		if occuranceKey in occuranceCount:
			occuranceCount[occuranceKey] += 1
		else:
			occuranceCount[occuranceKey] = 1
		jsondata['occuranceKey'] = occuranceKey
		key = "{}-{}-{}".format(year, '-'.join(authorout), textwrap.shorten(jsondata['title'], width=50, placeholder=""))
		jsondata['sortorder'] = "{}-{}-{}".format(' '.join(authors), year, jsondata['title'])

		if key in items:
			jsondata['category_page'] = jsondata['category_page'] + items[key]['category_page']			
		items[key] = jsondata
Esempio n. 43
0
 def __str__(self):
     return "[{0}] {1} {2}".format(self.category, self.question,
                                   shorten(self.answer, 140))
Esempio n. 44
0
    def form_valid(self, form):
        message = form.cleaned_data.get("comment")
        image = form.cleaned_data.get("image")
        users = (self.request.POST.get("users[]", "")).split(",")
        user = self.request.user
        subject = self.webpage.topic.subject

        if users[0] != "":
            for u in users:
                to_user = User.objects.get(email=u)
                talk, create = Conversation.objects.get_or_create(
                    user_one=user, user_two=to_user)
                created = TalkMessages.objects.create(text=message,
                                                      talk=talk,
                                                      user=user,
                                                      subject=subject,
                                                      image=image)

                simple_notify = textwrap.shorten(strip_tags(message),
                                                 width=30,
                                                 placeholder="...")

                if image != "":
                    simple_notify += " ".join(_("[Photo]"))

                notification = {
                    "type":
                    "chat",
                    "subtype":
                    "subject",
                    "space":
                    subject.slug,
                    "user_icon":
                    created.user.image_url,
                    "notify_title":
                    str(created.user),
                    "simple_notify":
                    simple_notify,
                    "view_url":
                    reverse("chat:view_message",
                            args=(created.id, ),
                            kwargs={}),
                    "complete":
                    render_to_string("chat/_message.html",
                                     {"talk_msg": created}, self.request),
                    "container":
                    "chat-" + str(created.user.id),
                    "last_date":
                    _("Last message in %s") % (formats.date_format(
                        created.create_date, "SHORT_DATETIME_FORMAT")),
                }

                notification = json.dumps(notification)

                Group("user-%s" % to_user.id).send({"text": notification})

                ChatVisualizations.objects.create(viewed=False,
                                                  message=created,
                                                  user=to_user)

            success = str(_("The message was successfull sent!"))
            return JsonResponse({"message": success})
        erro = HttpResponse(str(_("No user selected!")))
        erro.status_code = 404
        return erro
 def snippet(self):
     body_snippet = textwrap.shorten(self.body, width=35, placeholder="...")
     return "{author} - {snippet}...".format(
         author=self.creation_user.username, snippet=body_snippet)
Esempio n. 46
0
 def __str__(self):
     return textwrap.shorten(self.text, width=300)
Esempio n. 47
0
    def run(self, **kwargs):
        """
        Run the celery task.

        """
        # Set the arguments.
        for key, value in kwargs.items():
            setattr(self, key, value)

        # If a time limit is set for using labs,
        # check how much time learner has already spent
        settings = get_xblock_settings()
        lab_usage_limit = settings.get("lab_usage_limit", None)

        policy_warn_message = None
        if lab_usage_limit:
            # don't look further than 365 days for lab launch
            cutoff = timezone.now() - timezone.timedelta(days=365)

            # get all learner stacks across the platform
            stacks = Stack.objects.filter(learner__id=self.learner_id).filter(
                launch_timestamp__gt=cutoff)

            # add up total time spent on labs in seconds
            total_time_spent = 0
            for stack in stacks:
                # A stacklog is saved each time the stack status changes,
                # we only need to look at log entires with SUSPEND_COMPLETE
                # status to get all records of active lab sessions with
                # launch and suspend timestamps.
                stacklog = StackLog.objects.filter(stack_id=stack.id).filter(
                    status="SUSPEND_COMPLETE")

                # add up time spent on labs for one stack in seconds
                time_spent = 0
                for logentry in stacklog:
                    time = (logentry.suspend_timestamp -
                            logentry.launch_timestamp)
                    time_spent += time.total_seconds()
                total_time_spent += time_spent

            if total_time_spent > lab_usage_limit:
                policy = settings.get("lab_usage_limit_breach_policy",
                                      "").lower()

                if policy:
                    logger.error(
                        f'Learner {stacks[0].learner.email} has gone over '
                        'the lab usage limit!')

                if policy == 'block':
                    raise LabAccessRestricted(
                        "You've reached the time limit allocated to you "
                        "for using labs.")

                elif policy == 'warn':
                    policy_warn_message = (
                        "You've reached the time limit allocated to you "
                        "for using labs.")

        # Get the stack
        stack = Stack.objects.get(id=self.stack_id)

        # Initialize parameters
        self.protocol = stack.protocol
        self.port = stack.port
        self.stack_run = stack.run
        self.stack_name = stack.name
        self.stack_user_name = stack.user
        self.course_id = stack.course_id
        self.student_id = stack.student_id
        self.hook_events = stack.hook_events

        # Initialize hook script
        self.hook_script = None
        if stack.hook_script:
            self.hook_script = read_from_contentstore(stack.course_id,
                                                      stack.hook_script)

        # Initialize providers
        self.providers = []
        for provider in stack.providers:
            p = Provider.init(provider["name"])
            if p:
                p.set_logger(logger)
                p.set_capacity(provider["capacity"])

                template = read_from_contentstore(stack.course_id,
                                                  provider["template"])
                p.set_template(template)

                environment_path = provider.get("environment")
                if environment_path:
                    environment = read_from_contentstore(
                        stack.course_id, environment_path)
                    p.set_environment(environment)

                self.providers.append(p)
            else:
                logger.warning(
                    f'Failed to initialize provider: {provider["name"]}, '
                    'make sure the necessary settings are in place, or remove '
                    'the provider from the list to silence this warning.')
        if not self.providers:
            logger.error("No providers were successfully initialized, "
                         "make sure you have the necessary settings in place.")
            raise ProviderException()

        try:
            # Launch the stack and wait for it to complete.
            stack_data = self.launch_stack(stack.provider)
        except LaunchStackFailed as e:
            logger.error(e.error_msg)

            # In case of failure, only return the provider if this was a failed
            # resume attempt.
            provider_name = ""
            if e.suspend:
                provider_name = e.provider.name

            stack_data = {
                'status': e.status,
                'error_msg': textwrap.shorten(e.error_msg, width=256),
                'ip': None,
                'user': "",
                'key': "",
                'password': "",
                'provider': provider_name
            }

            # Roll back in case of failure
            self.cleanup_stack(e)

        # Don't wait for the user to check results.  Update the database
        # immediately.
        if policy_warn_message:
            stack_data["error_msg"] = policy_warn_message
        self.update_stack(stack_data)
Esempio n. 48
0
 def __str__(self):
     latest_revision = self.get_latest_revision()
     if not latest_revision:
         return str(self.pk)
     return textwrap.shorten(latest_revision.text, 70, placeholder='...')
Esempio n. 49
0
 def truncate(width, obj, right=False):
     stringified = str(obj or "")
     truncated = shorten(stringified, width=width, placeholder="...")
     return truncated.rjust(width) if right else truncated.ljust(width)
Esempio n. 50
0
 def get_shorten_text(self):
     return textwrap.shorten(self.explanation_text, 70, placeholder='...')
Esempio n. 51
0
def audits(name, uuid):

    if name and uuid:
        data = db_query(
            "SELECT assets.fqdn, compliance.check_name, compliance.status FROM compliance LEFT OUTER JOIN assets ON "
            "assets.uuid = compliance.asset_uuid "
            "where compliance.audit_file='{}' and compliance.asset_uuid='{}';".
            format(name, uuid))

        click.echo("{:65} {:65} {}".format("\nFQDN", " Check Name", " Status"))
        click.echo("-" * 150)
        click.echo()
        for finding in data:
            click.echo("{:65} {:65} {}".format(
                textwrap.shorten(str(finding[0]), width=65),
                textwrap.shorten(str(finding[1]), width=65), finding[2]))
        click.echo()

    elif name:
        data = db_query(
            "SELECT assets.fqdn, compliance.check_name, compliance.status FROM compliance LEFT OUTER JOIN assets ON "
            "assets.uuid = compliance.asset_uuid "
            "where audit_file='{}';".format(name))

        click.echo("{:65} {:65} {}".format("\nFQDN", " Check Name", " Status"))
        click.echo("-" * 150)
        click.echo()

        for finding in data:
            click.echo("{:65} {:65} {}".format(
                textwrap.shorten(str(finding[0]), width=65),
                textwrap.shorten(str(finding[1]), width=65), finding[2]))
        click.echo()

    elif uuid:
        data = db_query(
            "SELECT assets.fqdn, compliance.check_name, compliance.status FROM compliance LEFT OUTER JOIN assets ON "
            "assets.uuid = compliance.asset_uuid "
            "where asset_uuid='{}';".format(uuid))

        click.echo("{:65} {:65} {}".format("\nFQDN", " Check Name", " Status"))
        click.echo("-" * 150)
        click.echo()
        for finding in data:
            click.echo("{:65} {:65} {}".format(
                textwrap.shorten(str(finding[0]), width=65),
                textwrap.shorten(str(finding[1]), width=65), finding[2]))
        click.echo()

    else:
        compliance_data = db_query("SELECT audit_file from compliance;")
        compliance_list = []

        for audit in compliance_data:
            if audit not in compliance_list:
                compliance_list.append(audit)

        click.echo("\nCompleted Audits")
        click.echo("-" * 80)
        click.echo()

        for name in compliance_list:
            click.echo(name[0])

        click.echo()
Esempio n. 52
0
 def set_default(self, ctx: commands.Context, limit: int=30):
     """Sets embed author"""
     who = shorten(ctx.author.display_name, limit)
     self.set_author(name=f'Requested by {who}', icon_url=str(ctx.author.avatar_url))
     return self
Esempio n. 53
0
def shorten_str(full_string):
    """
    Shorten string to 50 chars max, including an ending ellipsis
    Words are not truncated
    """
    return textwrap.shorten(full_string, width=50, placeholder="...")
Esempio n. 54
0
def get_grid_table_context(lessons, homeworks, current_day, week, context):
    """ Returns class schedule and homework for this week """
    if len(
            lessons
    ) == 0:  # If class shedule for the user is empty the program exits the function
        return context

    context['count_of_lessons'] = get_max_number_of_lessons(
        lessons)  # getting the most lessons per week
    context['number_of_days'] = lessons.order_by(
        '-day').first().day  # Getting all non empty days

    for day in context['days']:
        for _ in range(1, context['count_of_lessons'] + 1):
            lesson = lessons.filter(day=current_day.isoweekday(),
                                    number=_).first()
            if lesson != None:
                homework = homeworks.filter(lesson=lesson).first()
                if homework != None:
                    day['lessons'].append({
                        'none':
                        False,
                        'name':
                        lesson.name,
                        'number':
                        lesson.number,
                        'classroom':
                        lesson.classroom,
                        'homework':
                        textwrap.shorten(text=homework.homework,
                                         width=25,
                                         placeholder='...'),
                        'homework_is_done':
                        homework.is_done,
                        'details':
                        homework.id,
                        'delete_id':
                        lesson.id,
                        'edit_homework': {
                            'week': week,
                            'id': lesson.id
                        },
                    })
                else:
                    day['lessons'].append({
                        'none': False,
                        'number': lesson.number,
                        'name': lesson.name,
                        'classroom': lesson.classroom,
                        'delete_id': lesson.id,
                        'details': 0,
                        'edit_homework': {
                            'week': week,
                            'id': lesson.id
                        },
                    })
            elif lessons.filter(day=current_day.isoweekday()).exists():
                day['lessons'].append({'none': True})

        current_day += datetime.timedelta(
            days=1)  # Taking the next day for processing in the next iteration

    context['number_of_lessons'] = context['count_of_lessons'] + 1
    context['count_of_lessons'] = range(1, context['count_of_lessons'] + 1)

    return context
Esempio n. 55
0
                    s(None, "Google Calculator:",
                      f"**{tmp}** {h2t(str(answer))}"))
                return

    # sidepage card
    if card := soup.find("div", class_="liYKde g VjDLd"):
        if thumbnail := card.find("g-img", attrs={"data-lpage": True}):
            kwargs["thumbnail"] = thumbnail["data-lpage"]
        if title := soup.find("div", class_="SPZz6b"):
            if desc := card.find("div", class_="kno-rdesc"):
                if remove := desc.find(class_="Uo8X3b"):
                    remove.decompose()

                desc = (
                    textwrap.shorten(h2t(str(desc)),
                                     1024,
                                     placeholder="\N{HORIZONTAL ELLIPSIS}") +
                    "\n")

                if more_info := card.findAll("div", class_="Z1hOCe"):
                    for thing in more_info:
                        tmp = thing.findAll("span")
                        if len(tmp) == 2:
                            desc2 = f"\n **{tmp[0].text}**`{tmp[1].text.lstrip(':')}`"
                            # More jack advises :D
                            MAX = 1024
                            MAX_LEN = MAX - len(desc2)
                            if len(desc) > MAX_LEN:
                                desc = (next(
                                    pagify(
                                        desc,
Esempio n. 56
0
def feedback_review_3(feedback, size):
    return textwrap.shorten(feedback, size)
Esempio n. 57
0
    def render_snapin(self, snapin: UserSidebarSnapin) -> str:
        snapin_class = snapin.snapin_type
        name = snapin_class.type_name()
        snapin_instance = snapin_class()

        more_id = "sidebar_snapin_%s" % name

        show_more = user.get_show_more_setting(more_id)
        html.open_div(id_="snapin_container_%s" % name,
                      class_=["snapin", ("more" if show_more else "less")])

        self._render_snapin_styles(snapin_instance)
        # When not permitted to open/close snapins, the snapins are always opened
        if snapin.visible == SnapinVisibility.OPEN or not user.may(
                "general.configure_sidebar"):
            style = None
        else:
            style = "display:none"

        toggle_url = "sidebar_openclose.py?name=%s&state=" % name

        # If the user may modify the sidebar then add code for dragging the snapin
        head_actions: Dict[str, str] = {}
        if user.may("general.configure_sidebar"):
            head_actions = {
                "onmouseover": "document.body.style.cursor='move';",
                "onmouseout ": "document.body.style.cursor='';",
                "onmousedown": "cmk.sidebar.snapin_start_drag(event)",
                "onmouseup": "cmk.sidebar.snapin_stop_drag(event)",
            }

        html.open_div(class_=["head", snapin.visible.value], **head_actions)

        show_more = snapin_instance.has_show_more_items()
        may_configure = user.may("general.configure_sidebar")

        if show_more or may_configure:

            html.open_div(class_="snapin_buttons")

            if show_more:
                html.open_span(class_="moresnapin")
                html.more_button(more_id, dom_levels_up=4)
                html.close_span()

            if may_configure:
                # Button for closing (removing) a snapin
                html.open_span(class_="closesnapin")
                close_url = "sidebar_openclose.py?name=%s&state=off" % name
                html.icon_button(
                    url=None,
                    title=_("Remove this element"),
                    icon="close",
                    onclick="cmk.sidebar.remove_sidebar_snapin(this, '%s')" %
                    close_url,
                )
                html.close_span()

            html.close_div()

        # The heading. A click on the heading mini/maximizes the snapin
        toggle_actions: Dict[str, str] = {}
        if user.may("general.configure_sidebar"):
            toggle_actions = {
                "onclick":
                "cmk.sidebar.toggle_sidebar_snapin(this,'%s')" % toggle_url,
                "onmouseover": "this.style.cursor='pointer'",
                "onmouseout": "this.style.cursor='auto'",
            }
        html.b(
            textwrap.shorten(snapin_class.title(), width=27,
                             placeholder="..."),
            class_=["heading"],
            **toggle_actions,
        )

        if may_configure:
            # Icon for mini/maximizing
            html.span(
                "",
                class_="minisnapin",
                title=_("Open/close this element"),
                onclick="cmk.sidebar.toggle_sidebar_snapin(this, '%s')" %
                toggle_url,
            )

        # End of header
        html.close_div()

        # Now comes the content
        html.open_div(class_="content", id_="snapin_%s" % name, style=style)
        refresh_url = ""
        try:
            # TODO: Refactor this confusing special case. Add deddicated method or something
            # to let the snapins make the sidebar know that there is a URL to fetch.
            url = snapin_instance.show()
            if url is not None:
                # Fetch the contents from an external URL. Don't render it on our own.
                refresh_url = url
                html.javascript(
                    'cmk.ajax.get_url("%s", cmk.utils.update_contents, "snapin_%s")'
                    % (refresh_url, name))
        except Exception as e:
            logger.exception("error rendering snapin %s", name)
            write_snapin_exception(e)
        html.close_div()
        html.close_div()
        return refresh_url
Esempio n. 58
0
async def error_handler(ctx, error):
    error = getattr(error, "original", error)

    if isinstance(
            error,
        (commands.MissingPermissions, RuntimeError, discord.Forbidden)):
        ctx.bot.logger.info(
            "command raised no bot permissions: %s, author: %s, error: %s",
            ctx.invoked_with, ctx.author.id, error)
        return await ctx.send(
            str(error) if error else
            "Please double-check the bot's permissions and try again.")

    if isinstance(error, (checks.NoConfigFailure, paginator.CannotPaginate,
                          commands.CheckFailure)):
        ctx.bot.logger.info("command raised checks failure: %s, author: %s",
                            ctx.invoked_with, ctx.author.id)
        return await ctx.send(str(error))

    if isinstance(error, (commands.BadArgument, commands.BadUnionArgument)):
        if str(error):
            return await ctx.send(str(error))
        else:
            return
    if isinstance(error, commands.MissingRequiredArgument):
        ctx.bot.logger.info(
            "command missing required argument: %s, author: %s",
            ctx.invoked_with, ctx.author.id)
        return await ctx.send(
            f"Oops! That didn't look right... "
            f"please see how to use the command with `++help {ctx.command.qualified_name}`"
        )
    if isinstance(error, commands.CommandOnCooldown):
        if await ctx.bot.is_owner(ctx.author):
            return await ctx.reinvoke()
        time = formats.readable_time(error.retry_after)
        ctx.bot.logger.info("command raised cooldown error: %s",
                            ctx.invoked_with)
        return await ctx.send(
            f"You're on cooldown. Please try again in: {time}")
    if isinstance(error, coc.HTTPException):
        ctx.bot.logger.info("coc api raised %s for command %s", error,
                            ctx.invoked_with)
        return await ctx.send(f"The COC API returned {error.message}. "
                              f"If this persists, please tag TubaKid!")

    ctx.command.reset_cooldown(ctx)

    if isinstance(
            error,
        (discord.Forbidden, discord.NotFound, paginator.CannotPaginate)):
        return

    e = discord.Embed(title="Command Error", colour=0xcc3366)
    e.add_field(name="Name", value=ctx.command.qualified_name)
    e.add_field(name="Author", value=f"{ctx.author} (ID: {ctx.author.id})")

    fmt = f"Channel: {ctx.channel} (ID: {ctx.channel.id})"
    if ctx.guild:
        fmt = f"{fmt}\nGuild: {ctx.guild} (ID: {ctx.guild.id})"

    e.add_field(name="Location", value=fmt, inline=False)
    e.add_field(name="Content",
                value=textwrap.shorten(ctx.message.content, width=512))

    exc = "".join(
        traceback.format_exception(type(error),
                                   error,
                                   error.__traceback__,
                                   chain=False))

    ctx.bot.logger.error(
        f"Unhandled error occurred:\ncommand: {ctx.invoked_with}\nauthor: {ctx.author.id}"
    )

    if len(exc) > 2000:
        fp = io.BytesIO(exc.encode("utf-8"))
        e.description = "Traceback was too long."
        return await ctx.send(embed=e, file=discord.File(fp, "traceback.txt"))

    e.description = f"```py\n{exc}\n```"
    e.timestamp = datetime.datetime.utcnow()

    if not ctx.bot.live:
        return await ctx.send(embed=e)

    await ctx.bot.error_webhook.send(embed=e)
    try:
        await ctx.send(
            "Uh oh! Something broke. You might want to tag TubaKid and tell him to get his crap together!"
        )
    except discord.Forbidden:
        pass
Esempio n. 59
0
    def send_message(self, request):
        self.log_action = "send"
        self.log_resource = "message"
        self.log_context = {}

        if "file" in request.data:
            file = request.FILES["file"]

            data = json.loads(request.data["data"])

            username = data["email"]
            user_two = data["user_two"]
            subject = data["subject"]
            msg_text = data["text"]
            create_date = data["create_date"]
        else:
            file = None
            data = (request.data if request.data else json.loads(
                request.body.decode("utf-8")))
            username = data["email"]
            user_two = data["user_two"]
            subject = data["subject"]
            msg_text = data["text"]
            create_date = data["create_date"]

        info = {}

        if not user_two == "" and not username == "":
            user = User.objects.get(email=username)
            user_to = User.objects.get(email=user_two)

            talks = Conversation.objects.filter(
                (Q(user_one__email=username) & Q(user_two__email=user_two))
                | (Q(user_two__email=username) & Q(user_one__email=user_two)))

            if talks.count() > 0:
                talk = talks[0]
            else:
                talk = Conversation()
                talk.user_one = user
                talk.user_two = user_to

                talk.save()

            if subject != "":
                subject = Subject.objects.get(slug=subject)
                space = subject.slug
                space_type = "subject"

                self.log_context["subject_id"] = subject.id
                self.log_context["subject_slug"] = space
                self.log_context["subject_name"] = subject.name
            else:
                subject = None
                space = 0
                space_type = "general"

            message = TalkMessages()
            message.text = "<p>" + msg_text + "</p>"
            message.user = user
            message.talk = talk
            message.subject = subject

            if not file is None:
                message.image = file

            message.save()

            self.log_context["talk_id"] = talk.id
            self.log_context["user_id"] = user_to.id
            self.log_context["user_name"] = str(user_to)
            self.log_context["user_email"] = user_two

            if not message.pk is None:
                simple_notify = textwrap.shorten(strip_tags(message.text),
                                                 width=30,
                                                 placeholder="...")

                notification = {
                    "type":
                    "chat",
                    "subtype":
                    space_type,
                    "space":
                    space,
                    "user_icon":
                    message.user.image_url,
                    "notify_title":
                    str(message.user),
                    "simple_notify":
                    simple_notify,
                    "view_url":
                    reverse("chat:view_message",
                            args=(message.id, ),
                            kwargs={}),
                    "complete":
                    render_to_string("chat/_message.html",
                                     {"talk_msg": message}, request),
                    "container":
                    "chat-" + str(message.user.id),
                    "last_date":
                    _("Last message in %s") % (formats.date_format(
                        message.create_date, "SHORT_DATETIME_FORMAT")),
                }

                notification = json.dumps(notification)

                Group("user-%s" % user_to.id).send({"text": notification})

                ChatVisualizations.objects.create(viewed=False,
                                                  message=message,
                                                  user=user_to)

                serializer = ChatSerializer(message)

                json_r = json.dumps(serializer.data)
                json_r = json.loads(json_r)

                info["data"] = {}
                info["data"]["message_sent"] = json_r

                info["message"] = _("Message sent successfully!")
                info["success"] = True
                info["number"] = 1

                sendChatPushNotification(user_to, message)

                super(ChatViewset, self).createLog(
                    user,
                    self.log_component,
                    self.log_action,
                    self.log_resource,
                    self.log_context,
                )
            else:
                info["message"] = _("Error while sending message!")
                info["success"] = False
                info["number"] = 0
        else:
            info["data"] = {}
            info["data"]["message_sent"] = {}

            info["message"] = _("No information received!")
            info["success"] = False
            info["number"] = 0

        info["data"]["messages"] = []
        info["type"] = ""
        info["title"] = _("Amadeus")
        info["extra"] = 0

        response = json.dumps(info)

        return HttpResponse(response)
Esempio n. 60
0
 def pack_table(info):
     return '<table>\n' + "\n".join(
         '<tr><td align="right" width="90">%s:</td>\n'
         '<td width="40">%s</td></tr>\n' %
         (d, textwrap.shorten(str(v), width=30, placeholder="..."))
         for d, v in info) + "</table>\n"