示例#1
0
def get_post_comments(db, post_id, user):
    """
    Returns list of all comments for specific post id, including user avatars and
    comment votes for the related comment.
    A vote count is also returned which determines if the logged in user has voted on
    a specific comment (1 being upvote, -1 being downvote, 0 for unvoted)
    """
    cursor = db.cursor()
    query = """
    SELECT c.*, u.avatar,
      (SELECT COALESCE(SUM(up) - SUM(down), 0)
        FROM comment_votes
        WHERE comment_id = c.id) v,
      (SELECT SUM(up + -down)
        FROM comment_votes
        WHERE comment_id = c.id
        AND username = ?)
    FROM users u
    LEFT OUTER JOIN comments c
    ON u.username = c.username
    WHERE c.post_id = ?
    AND c.id is not NULL
    ORDER BY v DESC
    """
    cursor.execute(query, (user, post_id))
    result = []
    for row in cursor:
        row = list(row)
        # Format date and time
        row[5] = format_date(row[5])
        # If vote count is None, set it to 0
        if row[7] is None:
            row[7] = 0
        result.append(row)
    return result
示例#2
0
def get_post(db, post_id, user):
    """
    Returns specific post by id if it exists, otherwise None
    """
    cursor = db.cursor()
    query = """
    SELECT p.*, u.avatar,
      (SELECT COALESCE(SUM(up) - SUM(down), 0)
        FROM post_votes
        WHERE post_id = p.id),
      (SELECT SUM(up + -down)
        FROM post_votes
        WHERE post_id = p.id
        AND username = ?),
      GROUP_CONCAT(k.keyword)
    FROM users u
    LEFT OUTER JOIN posts p ON u.username = p.username
    LEFT OUTER JOIN  post_keywords pk ON p.id = pk.post_id
    LEFT OUTER JOIN keywords k ON pk.keyword_id = k.id
    WHERE p.id = ?
    GROUP BY p.id
    """
    cursor.execute(query, (user, post_id))
    post = cursor.fetchone()
    if post:
        post = list(post)
        # Format date and time
        post[6] = format_date(post[6])
        # Split keywords into a list to be returned
        if post[10] is not None:
            post[10] = [x.strip() for x in post[10].split(',')]
        return post
    return None
示例#3
0
  def set_cookie(self, key, value, expires=1, domain=None, path='/', secure=False, http_only=False):
    '''
    Send a cookie to the client.
    
    :param key: Key to use for cookie
    :param value: Data to pass to cookie
    :param expires: How long (in hours) until the cookie expires
    :param domain: Domain that the cookie should apply to
    :param path: Path that the cookie should apply to
    :param secure: Whether or not "Secure" flag should be passed to cookie
    :param http_only: Whether or not "HttpOnly" flag should be passed to cookie
    '''
    
    cookie = ["%s=%s" % (key, value)]

    if expires:
      now = get_gmt_now()
      then = now + datetime.timedelta(hours=expires)
      cookie.append("Expires=%s" % format_date(then))
    if domain:
      cookie.append("Domain=%s" % domain)
    if path:
      cookie.append("Path=%s" % path)
    if secure:
      cookie.append("Secure")
    if http_only:
      cookie.append("HttpOnly")

    self.headers['Set-Cookie'] = '; '.join(cookie)
    def initWithFrame_oldTransfer_(self, frame, transferInfo):
        self = NSView.initWithFrame_(self, frame)
        if self:
            self.oldTransferInfo = transferInfo

            NSBundle.loadNibNamed_owner_("FileTransferItemView", self)

            filename = transferInfo.file_path
            if filename.endswith(".download"):
                filename = filename[:-len(".download")]

            self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(filename))

            self.nameText.setStringValue_(os.path.basename(filename))
            self.fromText.setStringValue_('To %s from account %s' % (transferInfo.remote_uri, transferInfo.local_uri) if transferInfo.direction=='outgoing' else 'From %s to account %s' % (transferInfo.remote_uri, transferInfo.local_uri))

            time_print = format_date(transferInfo.time)
            if transferInfo.status == "completed":
                t = NSLocalizedString("Completed transfer of ", "Label")
                status = t + "%s %s" % (format_size(transferInfo.file_size, 1024), time_print)
            else:
                if transferInfo.direction == "outgoing":
                    status = '%s %s' % (transferInfo.status.title(), time_print)
                    self.retryButton.setHidden_(False)
                else:
                    #status = "%s of %s"%(format_size(transferInfo.bytes_transfered, 1024), format_size(transferInfo.file_size, 1024))
                    status = "%s %s" % (transferInfo.status.title(), time_print)

            self.sizeText.setStringValue_(status)
            frame.size = self.view.frame().size
            self.setFrame_(frame)
            self.addSubview_(self.view)
            self.relayoutForDone()
            self.done = True
        return self
示例#5
0
def get_post(db, post_id, user):
    """
    Returns specific post by id if it exists, otherwise None
    """
    cursor = db.cursor()
    query = """
    SELECT p.*, u.avatar,
      (SELECT COALESCE(SUM(up) - SUM(down), 0)
        FROM post_votes
        WHERE post_id = p.id),
      (SELECT SUM(up + -down)
        FROM post_votes
        WHERE post_id = p.id
        AND username = ?),
      GROUP_CONCAT(k.keyword)
    FROM users u
    LEFT OUTER JOIN posts p ON u.username = p.username
    LEFT OUTER JOIN  post_keywords pk ON p.id = pk.post_id
    LEFT OUTER JOIN keywords k ON pk.keyword_id = k.id
    WHERE p.id = ?
    GROUP BY p.id
    """
    cursor.execute(query, (user, post_id))
    post = cursor.fetchone()
    if post:
        post = list(post)
        # Format date and time
        post[6] = format_date(post[6])
        # Split keywords into a list to be returned
        if post[10] is not None:
            post[10] = [x.strip() for x in post[10].split(',')]
        return post
    return None
示例#6
0
  def set_cookie(self, key, value, expires=1, domain=None, path='/', secure=False, http_only=False):
    '''
    Send a cookie to the client.
    
    :param key: Key to use for cookie
    :param value: Data to pass to cookie
    :param expires: How long (in hours) until the cookie expires
    :param domain: Domain that the cookie should apply to
    :param path: Path that the cookie should apply to
    :param secure: Whether or not "Secure" flag should be passed to cookie
    :param http_only: Whether or not "HttpOnly" flag should be passed to cookie
    '''
    
    cookie = ["%s=%s" % (key, value)]

    if expires:
      now = get_gmt_now()
      then = now + datetime.timedelta(hours=expires)
      cookie.append("Expires=%s" % format_date(then))
    if domain:
      cookie.append("Domain=%s" % domain)
    if path:
      cookie.append("Path=%s" % path)
    if secure:
      cookie.append("Secure")
    if http_only:
      cookie.append("HttpOnly")

    self.headers['Set-Cookie'] = '; '.join(cookie)
示例#7
0
def get_post_comments(db, post_id, user):
    """
    Returns list of all comments for specific post id, including user avatars and
    comment votes for the related comment.
    A vote count is also returned which determines if the logged in user has voted on
    a specific comment (1 being upvote, -1 being downvote, 0 for unvoted)
    """
    cursor = db.cursor()
    query = """
    SELECT c.*, u.avatar,
      (SELECT COALESCE(SUM(up) - SUM(down), 0)
        FROM comment_votes
        WHERE comment_id = c.id) v,
      (SELECT SUM(up + -down)
        FROM comment_votes
        WHERE comment_id = c.id
        AND username = ?)
    FROM users u
    LEFT OUTER JOIN comments c
    ON u.username = c.username
    WHERE c.post_id = ?
    AND c.id is not NULL
    ORDER BY v DESC
    """
    cursor.execute(query, (user, post_id))
    result = []
    for row in cursor:
        row = list(row)
        # Format date and time
        row[5] = format_date(row[5])
        # If vote count is None, set it to 0
        if row[7] is None:
            row[7] = 0
        result.append(row)
    return result
示例#8
0
    def _gen_cmd(self, job, params):
        script = 'shell_%s.%s' % (job.name, thread_id())
        templ = """cmd="%s"
eval $cmd
"""
        f = open(script, 'w')
        f.write(templ % params[COMMAND])
        f.close()
        log = '%s.log.%s' % (job.name, format_date(now()))
        # we can not remove it in the cmd
        # as it will return success to replace the actual cmd output
        cmd = 'chmod +x %(script)s; ./%(script)s > %(log)s 2>&1' % {
            'script': script,
            'log': log
        }
        return cmd
示例#9
0
    def _terminate(self, failure_reason=None, failure_status=None):
        notification_center = NotificationCenter()

        if failure_reason is None:
            self.log_info("File Transfer ended (%i of %i bytes transferred)" %
                          (self.bytes, self.total_bytes))
            self.end_time = datetime.datetime.now()
            t = NSLocalizedString("Completed transfer of ", "Label")
            self.status = t + format_size(self.file_size) + NSLocalizedString(
                " in ", "Label") + format_duration(
                    self.end_time - self.start_time) + " " + format_date(
                        self.end_time)
            self.ft_info.status = "completed"
            self.ft_info.bytes_transfered = self.file_selector.size
        else:
            if failure_status is None:
                if self.total_bytes:
                    self.log_info("File Transfer was interrupted")
                    self.status = NSLocalizedString(
                        "Transferred %s of ", "Label") % format_size(
                            self.bytes, 1024) + format_size(
                                self.total_bytes) + " - " + failure_reason
                else:
                    self.log_info("File Transfer was cancelled")
                    self.status = failure_reason
            else:
                self.log_info("File Transfer failed: %s" % failure_reason)
                self.status = failure_status
            self.ft_info.status = "failed"
            self.ft_info.bytes_transfered = self.file_pos

        if self.session is not None and self.stream is not None and self.handler is not None:
            notification_center.remove_observer(self, sender=self.stream)
            notification_center.remove_observer(self, sender=self.handler)

        self.session = None
        self.stream = None
        self.handler = None
        self.transfer_rate = None

        notification_center.post_notification(
            "BlinkFileTransferDidEnd",
            sender=self,
            data=NotificationData(file_path=self.ft_info.file_path,
                                  error=failure_reason is not None))
        self.add_to_history()
示例#10
0
def get_all_posts(db, user, keyword=''):
    """
    Return a list of posts, including user avatars, comment count,
    post votes and keywords, ordered by votes.
    Can return list of posts that can contain keyword
    """
    cursor = db.cursor()
    query = """
    SELECT p.*, u.avatar,
        (SELECT COUNT(*)
          FROM comments
          WHERE post_id = p.id),
        (SELECT COALESCE(SUM(up) - SUM(down), 0)
          FROM post_votes
          WHERE post_id = p.id) v,
        (SELECT SUM(up + -down)
          FROM post_votes
          WHERE post_id = p.id
          AND username = ?),
        GROUP_CONCAT(k.keyword)
    FROM users u
    LEFT OUTER JOIN posts p ON u.username = p.username
    LEFT OUTER JOIN  post_keywords pk ON p.id = pk.post_id
    LEFT OUTER JOIN keywords k ON pk.keyword_id = k.id
    WHERE p.id is not NULL
    GROUP BY p.id
    HAVING (p.title LIKE ? OR p.username LIKE ? OR GROUP_CONCAT(k.keyword) LIKE ?)
    ORDER BY v DESC
    """
    keyword = '%' + str(keyword) + '%'
    cursor.execute(query, (user, keyword, keyword, keyword))
    result = []
    for row in cursor:
        row = list(row)
        # Form date and time
        row[6] = format_date(row[6])
        # If vote count is None, set it as 0
        if row[9] is None:
            row[9] = 0
        # Split keywords into a list to be returned
        if row[11] is not None:
            row[11] = [x.strip() for x in row[11].split(',')]
        result.append(row)
    return result
示例#11
0
def get_all_posts(db, user, keyword=''):
    """
    Return a list of posts, including user avatars, comment count,
    post votes and keywords, ordered by votes.
    Can return list of posts that can contain keyword
    """
    cursor = db.cursor()
    query = """
    SELECT p.*, u.avatar,
        (SELECT COUNT(*)
          FROM comments
          WHERE post_id = p.id),
        (SELECT COALESCE(SUM(up) - SUM(down), 0)
          FROM post_votes
          WHERE post_id = p.id) v,
        (SELECT SUM(up + -down)
          FROM post_votes
          WHERE post_id = p.id
          AND username = ?),
        GROUP_CONCAT(k.keyword)
    FROM users u
    LEFT OUTER JOIN posts p ON u.username = p.username
    LEFT OUTER JOIN  post_keywords pk ON p.id = pk.post_id
    LEFT OUTER JOIN keywords k ON pk.keyword_id = k.id
    WHERE p.id is not NULL
    GROUP BY p.id
    HAVING (p.title LIKE ? OR p.username LIKE ? OR GROUP_CONCAT(k.keyword) LIKE ?)
    ORDER BY v DESC
    """
    keyword = '%' + str(keyword) + '%'
    cursor.execute(query, (user, keyword, keyword, keyword))
    result = []
    for row in cursor:
        row = list(row)
        # Form date and time
        row[6] = format_date(row[6])
        # If vote count is None, set it as 0
        if row[9] is None:
            row[9] = 0
        # Split keywords into a list to be returned
        if row[11] is not None:
            row[11] = [x.strip() for x in row[11].split(',')]
        result.append(row)
    return result
    def initWithFrame_oldTransfer_(self, frame, transferInfo):
        self = NSView.initWithFrame_(self, frame)
        if self:
            self.oldTransferInfo = transferInfo
            self.file_path = transferInfo.file_path
            self.remote_uri = transferInfo.remote_uri
            self.local_uri = transferInfo.local_uri

            NSBundle.loadNibNamed_owner_("FileTransferItemView", self)

            self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(
                self.file_path))

            self.nameText.setStringValue_(os.path.basename(self.file_path))
            self.fromText.setStringValue_(
                'To %s from account %s' %
                (transferInfo.remote_uri,
                 transferInfo.local_uri) if transferInfo.direction ==
                'outgoing' else 'From %s to account %s' %
                (transferInfo.remote_uri, transferInfo.local_uri))

            self.revealButton.setHidden_(not os.path.exists(self.file_path))

            time_print = format_date(transferInfo.time)
            if transferInfo.status == "completed":
                self.sizeText.setTextColor_(NSColor.blueColor())
                t = NSLocalizedString("Completed transfer of ", "Label")
                status = t + "%s %s" % (format_size(transferInfo.file_size,
                                                    1024), time_print)
            else:
                self.sizeText.setTextColor_(NSColor.redColor())
                status = "%s %s" % (transferInfo.status.title(), time_print)

            self.sizeText.setStringValue_(status)
            frame.size = self.view.frame().size
            self.setFrame_(frame)
            self.addSubview_(self.view)
            self.relayoutForDone()
            if transferInfo.direction == "outgoing" and transferInfo.status != "completed" and os.path.exists(
                    self.file_path):
                self.retryButton.setHidden_(False)
            self.done = True
        return self
示例#13
0
    def update_row(self, jira_issue):
        for row in self.soup.findAll('tr')[1:]:
            key = row.findAll('td')[2].text
            if key == jira_issue.key:
                ConfluencePage.__update_cell(row, 3, None, jira_issue.summary)
                ConfluencePage.__update_cell(row, 4, ConfluencePage.__get_colour(jira_issue.status), jira_issue.status)
                ConfluencePage.__update_cell(row, 5, None, jira_issue.get_custom_field('is_dc'))
                ConfluencePage.__update_cell(row, 7, None, jira_issue.reporter)
                ConfluencePage.__update_cell(row, 8, None, jira_issue.get_custom_field('onshore_ba'))

                if jira_issue.get_custom_field('is_dc') != 'Yes':
                    ConfluencePage.__update_cell(row, 6, None, ' ')
                else:
                    if jira_issue.status == 'completed' and row.findAll('td')[6].text not in DC_STATUSES:
                        ConfluencePage.__update_cell(row, 6, ConfluencePage.__get_colour(jira_issue.status), 'Ready')
                    if jira_issue.status == 'accepted' and row.findAll('td')[6].text != 'Pass':
                        ConfluencePage.__update_cell(row, 6, ConfluencePage.__get_colour(jira_issue.status), 'Pass')

                est_date = jira_issue.get_custom_field('est_date')
                if est_date != '':
                    est_date = format_date(est_date)
                ConfluencePage.__update_cell(row, 9, None, est_date)

        self.set_content(self.soup.find('table'))
示例#14
0
def add_last_modified(request, response):
	'''
	Ensures that all responses have a Last-Modified header.
	'''
	if 'Last-Modified' not in response.headers:
		response.headers['Last-Modified'] = format_date(get_gmt_now())
示例#15
0
def add_date(request, response):
    '''
	Adds the current timestamp to all requests.
	'''
    response.headers['Date'] = format_date(get_gmt_now())
示例#16
0
def add_last_modified(request, response):
    '''
	Ensures that all responses have a Last-Modified header.
	'''
    if 'Last-Modified' not in response.headers:
        response.headers['Last-Modified'] = format_date(get_gmt_now())
示例#17
0
	def match(self, environ):
		'''
		Checks the WSGI environment provided to see if the requested path exists within the
		static mappings. If it does, returns the file; else, throws ``404 Not Found``.
		
		:param environ: WSGI environment (uses `PATH_INFO`)
		:param return: Returns a :class:`frame.response.Response` with the appropriate
			content-type, body, etc.
		'''
		
		for key, value in self.static_map.items():
			# Fix trouble caused by multiple preceeding '/'
			uri = '/%s' % environ['PATH_INFO'].lstrip('/')
			
			if uri.startswith(key):
				uri = uri[len(key):]
				uri = uri.lstrip('/')
				status = '200 OK'

				file_path = os.path.join(value, uri).rstrip('/')
				trash, extension = os.path.splitext(file_path)
				
				headers = dict(config.response.default_headers)

				if os.path.exists(file_path) and file_path.startswith(value):
					headers['Date'] = format_date(get_gmt_now())

					try:
						headers['Content-Type'] = mimetypes.types_map[extension]
					except KeyError:
						headers['Content-Type'] = 'application/octet-stream'

					try:
						headers['Accept-Ranges'] = 'bytes'

						if 'range' in self.app.request.headers:
							range_match = self.ranges_pattern.match(self.app.request.headers.range)
							if range_match:
								ranges = range_match.group(1).split(',')
								if False: #ranges[0] == '0-':
									response_body = self.read_file(open(file_path, 'r'))
								else:
									status = '206 Partial Content'
									boundary_string = self.get_boundary_string()
									file_obj = open(file_path, 'r')

									file_obj.seek(0, 2)

									if len(ranges) == 1:
										temp_range = self.get_range(file_obj, ranges[0])
										headers['Content-Range'] = 'bytes %s-%s/%s' % temp_range
									else:
										headers['Content-Type'] = 'multipart/byteranges; boundary=%s' % boundary_string

									response_body = self.read_file(file_obj, ranges, boundary_string)
							else:
								raise Error416
						else:
							response_body = self.read_file(open(file_path, 'r'))

					except EnvironmentError:
						raise Error401

				else:
					continue
				
				try:
					st = os.stat(file_path)
				except EnvironmentError, e:
					pass
				else:
					last_modified = datetime.datetime.fromtimestamp(
						time.mktime(time.gmtime(st.st_mtime)))
					headers['Last-Modified'] = format_date(last_modified)

				response = Response.from_data(status, headers, response_body)
				return response
示例#18
0
def get_reminder_set_message(request_info):
    return ("You are looking for carpool on " + 
        util.format_date(request_info.date) + " from " + 
        request_info.from_location + " to " +
        request_info.to_location + "\n" +
        "Type cancel reminder to cancel it any time.")
def test_accuracy(n_train, n_test):
    #n_train = load_list(c.NODES_FILENAME)
    #n_test = load_list(c.TEST_NODES_FILENAME)

    td = []
    succeeds = 0

    for n in n_test:

        # exclude rarer nodes to fix overrepresentation
        if n.reach_percentage() < 0.1 or len(n.passages) < 100:
            continue

        for i in pick_random_passage(n, 10):
            passage = n.passages[i]
            route = n.get_route(i)

            # pick random spot from passage.route
            # use 2 data points for calculation
            spot = random.randint(0, len(route) - 2)
            real_arrival = passage.enters_meas_area(route[spot + 1][2])

            print(n_train[spot + 1])

            predict_p, pred_parts = predict_path(n_train, route[spot],
                                                 route[spot + 1], 3)

            if predict_p == 0:
                continue
            predict_t = calculate_arrival(predict_p, route[spot], pred_parts)

            t = (predict_t - real_arrival) / 3600
            if abs(t) > 13:
                n.add_passage(passage, n.passage_i[i])
                #print("Already visited area")
                c = random_color()
                passage.plot(c)
                n.draw(c)
                Map.draw_circle(route[spot + 1][0], route[spot + 1][1], 2000,
                                "red")
                #print(n.label[i])
                print(predict_t / 3600, real_arrival / 3600, "(",
                      format_date(route[spot + 1][2]),
                      format_date(passage.enters_meas_area()), ")")

            if abs(t) < 0.5:
                succeeds += 1

            #print(t)
            td.append(t)

    print("Average time delta", np.mean(td))
    text = "Predictions in 1 hour margin {0}%\n".format(
        int(succeeds / len(td) * 100))
    text += "n=" + str(len(td))

    def draw_chart(values):
        plt.hist(values, np.arange(-5, 5, step=0.5), density=False)
        plt.xlabel("hours")
        plt.ylabel("propability")
        plt.xticks(np.arange(-5, 6, step=1))
        #plt.yticks(np.arange(0, 1, step=0.2))
        plt.ticklabel_format(axis='x')
        plt.gca().set_aspect('auto', adjustable='datalim')
        #plt.text(0, .025, r'$\mu=100,\ \sigma=15$')
        # xy scale is dependant on data, bad practice
        plt.text(-5, 400, text)
        plt.show()

    draw_chart(td)
示例#20
0
def add_date(request, response):
	'''
	Adds the current timestamp to all requests.
	'''
	response.headers['Date'] = format_date(get_gmt_now())