Skip to content

Commit

Permalink
added disqus comments
Browse files Browse the repository at this point in the history
  • Loading branch information
aliev committed Jun 24, 2015
1 parent c8daa74 commit c71f645
Show file tree
Hide file tree
Showing 146 changed files with 307 additions and 46 deletions.
59 changes: 15 additions & 44 deletions modules/luther/sphinx/disqus/disqus.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,46 +20,20 @@
from docutils.parsers.rst import Directive


DISQUS_BOX = """\
DISQUS_LINK = """\
<div id="disqus_thread"></div>
<script type="text/javascript">
function %(identifier)s_disqus(source) {
if (window.DISQUS) {
$('#disqus_thread').insertAfter(source); //put the DIV for the Disqus box after the link
//if Disqus exists, call it's reset method with new parameters
DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = '%(identifier)s_' + eBookConfig.course;
this.page.url = 'http://%(identifier)s_'+eBookConfig.course+'.interactivepython.com/#!';
}
});
} else {
//insert a wrapper in HTML after the relevant "show comments" link
$('<div id="disqus_thread"></div>').insertAfter(source);
// set Disqus required vars
disqus_shortname = '%(shortname)s';
disqus_identifier = '%(identifier)s_' + eBookConfig.course;
disqus_url = 'http://%(identifier)s_'+eBookConfig.course+'.interactivepython.com/#!';
//append the Disqus embed script to HTML
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
$('head').append(dsq);
}
}
</script>
"""

DISQUS_LINK = """
<a href="#disqus_thread" class='disqus_thread_link' data-disqus-identifier="%(identifier)s" onclick="%(identifier)s_disqus(this);">Show Comments</a>
<script type='text/javascript'>
$("a[data-disqus-identifier='%(identifier)s']").attr('data-disqus-identifier', '%(identifier)s_' + eBookConfig.course);
/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'alialiev';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
"""


Expand All @@ -77,10 +51,9 @@ def __init__(self,content):


def visit_disqus_node(self, node):
res = DISQUS_BOX
res += DISQUS_LINK
res = DISQUS_LINK

res = res % node.disqus_components
res = res

self.body.append(res)

Expand All @@ -99,9 +72,7 @@ class DisqusDirective(Directive):
optional_arguments = 0
final_argument_whitespace = True
has_content = False
option_spec = {'shortname':directives.unchanged_required,
'identifier':directives.unchanged_required
}
option_spec = {}


def run(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,6 @@
while i > 0:
k = 2 + 2
i = i // 2
.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/AlgorithmAnalysis/BigONotation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,5 @@ Python, показанный в :ref:`листинге 2 <lst_dummycode>`. Не

http://media.interactivepython.org/pythondsVideos/findmin.mov
http://media.interactivepython.org/pythondsVideos/findmin.webm

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/AlgorithmAnalysis/Dictionaries.rst
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,5 @@

http://media.interactivepython.org/pythondsVideos/pythonops.mov
http://media.interactivepython.org/pythondsVideos/pythonops.webm

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/AlgorithmAnalysis/DiscussionQuestions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,5 @@
k = 2 + 2
for k in range(n):
k = 2 + 2

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/AlgorithmAnalysis/Lists.rst
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,5 @@ Python сочли разумными.
.. figure:: Figures/poptime.png

Рисунок 3: Сравнение производительности ``pop`` и ``pop(0)``

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/AlgorithmAnalysis/Objectives.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@

- Понять, как находить критерии оценки для простых программ на Python.


.. disqus::
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@
протяжении оставшихся глав этой книги. В этом разделе мы не планируем
объяснять, почему производительность такова, какова она есть. Позднее вы
сами увидите возможные реализации списков и словарей, и как от этого зависит производительность.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/AlgorithmAnalysis/ProgrammingExercises.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@

#. Можете ли вы улучшить алгоритм из предыдущего задания, чтобы он был
:math:`O(n\log(n))`?

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/AlgorithmAnalysis/Summary.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@

- Нотация "большое О" позволяет классифицировать алгоритмы по их доминирующим
вычислениям относительно размера задачи.

.. disqus::
3 changes: 3 additions & 0 deletions pythonds/source/AlgorithmAnalysis/WhatIsAlgorithmAnalysis.rst
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,6 @@
от программы или компьютера. Такое измерение было бы полезно для оценки алгоритма
самого по себе, и его стало бы возможно использовать для сравнения алгоритмов в различных
реализациях.


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/BalancedSymbols(AGeneralCase).rst
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,5 @@
Мы продолжим их исследовать в следующем разделе.



.. disqus::
Original file line number Diff line number Diff line change
Expand Up @@ -182,3 +182,5 @@

http://media.interactivepython.org/pythondsVideos/Stack2.mov
http://media.interactivepython.org/pythondsVideos/Stack2.webm

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/DiscussionQuestions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,5 @@
#. Объясните, как работает метод ``remove`` для связанного списка, когда значение
находится в *единственном* узле.


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/ImplementingaDequeinPython.rst
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,5 @@ CodeLens 1 демонстрирует класс ``Deque`` в последова
методы использовались для этой цели. Опять же, главное, в чём мы должны
быть уверены, так это в том, что в нашей реализации назначено хвостом,
а что головой дека.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/ImplementingaQueueinPython.rst
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,5 @@ CodeLens 1 демонстрирует класс ``Queue`` в действии

Какие элементы находятся в очереди слева?


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/ImplementingaStackinPython.rst
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,5 @@ n, являются O(n). Очевидно, что даже если в реал
http://media.interactivepython.org/pythondsVideos/Stack1.mov
http://media.interactivepython.org/pythondsVideos/Stack1.webm


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/ImplementinganOrderedList.rst
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,5 @@
списки основываются не на связанной модели, а на чём-то ещё. Действительно,
в основе существующей реализация списков в Python лежит понятие массива.
Мы обсудим это более детально в другой главе.

.. disqus::
Original file line number Diff line number Diff line change
Expand Up @@ -755,3 +755,5 @@ Python. Чтобы создать узел, вы должны предостав

mylist = UnorderedList()


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/InfixPrefixandPostfixExpressions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -497,3 +497,5 @@ B C \*, то произойдёт конвертирование подвыра

http://media.interactivepython.org/pythondsVideos/Stack3.mov
http://media.interactivepython.org/pythondsVideos/Stack3.webm

.. disqus::
4 changes: 3 additions & 1 deletion pythonds/source/BasicDS/KeyTerms.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@
Полная расстановка скобок Список Симуляция
Голова (например, списка) Узел Стек
Инфикс Палиндром
====================================== ======================================= =======================
====================================== ======================================= =======================

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/Lists.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@
мы должны записывать их как разделённые запятыми значения - общепринятым
способом изображения структуры списка. Python, естественно, покажет список так: :math:`[54,26,93,17,77,31]`.


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/Objectives.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,5 @@
- Уметь реализовывать АТД списка как связанный список с использованием модели узлов и ссылок.

- Уметь сравнивать производительность нашей реализации связанного списка со списком Python.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/PalindromeChecker.rst
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,5 @@

print(palchecker("lsdkjfskf"))
print(palchecker("radar"))

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/ProgrammingExercises.rst
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,5 @@

#. Создайте реализацию очереди, которая имела бы среднюю производительность
:math:`O(1)` для операций постановки в очередь и извлечения из неё.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/SimpleBalancedParentheses.rst
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,5 @@
сбалансировано и стек абсолютно пуст, делается вывод, что входной параметр
представляет из себя правильно сбалансированную последовательность скобок.


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/SimulationHotPotato.rst
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,5 @@ FIFO. Для начала давайте рассмотрим детскую и
было в её начале. В данном случае первым элементом в списке будет ``Bill``, поэтому
он помещается в начало очереди. Варианты этой реализации, описанные в упражнениях,
позволяют выбирать счётчик случайным образом.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/SimulationPrintingTasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -501,3 +501,5 @@
for i in range(10):
simulation(3600,5)


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/Summary.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,5 @@

- Изменение головы списка - специальный случай.


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/TheDequeAbstractDataType.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,5 @@
============================ ============================ ===============================



.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/TheOrderedListAbstractDataType.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,5 @@
Требует индекс в качестве аргумента, возвращает элемент.
Предполагается наличие элемента в списке.


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/TheQueueAbstractDataType.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,5 @@
============================ ======================== ===============================



.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/TheStackAbstractDataType.rst
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,5 @@
============================ ======================== ============================



.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/TheUnorderedListAbstractDataType.rst
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,5 @@
Требует позицию в качестве аргумента и возвращает элемент.
Предполагает, что такой элемент присутствует в списке.


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/WhatAreLinearStructures.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@
Эти различия порождают некоторые из наиполезнейших структур данных в информатике,
которые фигурируют во многих алгоритмах и могут использоваться для решения целого
ряда важных задач.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/WhatIsaDeque.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@
:align: center

Рисунок 1: Дек из объектов данных Python

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/WhatIsaQueue.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,5 @@
Нажатия клавиш помещаются в очередеподобный буфер, чтобы в конце концов отобразиться на
экране в правильном порядке.


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/BasicDS/WhatisaStack.rst
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,5 @@
их URL'ы). Текущая страница, которую вы просматриваете, находится на вершине,
а самая первая из просмотренных - в основании. Если вы нажмёте кнопку "Назад",
то начнёте двигаться по страницам в обратном порядке.

.. disqus::
4 changes: 3 additions & 1 deletion pythonds/source/BasicDS/basic_ex.rst
Original file line number Diff line number Diff line change
Expand Up @@ -258,4 +258,6 @@ Programming Exercises
last. Code this implementation in Python.

#. Create an implementation of a queue that would have an average
performance of O(1) for enqueue and dequeue operations.
performance of O(1) for enqueue and dequeue operations.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/Graphs/AnAdjacencyList.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@
Рисунок 4: Представление графа в виде списка смежности.

Преимуществом такой реализации является то, что она позволяет нам компактно представлять разреженные графы. Также в списке смежности легко найти все ссылки, непосредственно связанные с конкретной вершиной.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/Graphs/AnAdjacencyMatrix.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@
Преимущество использования матрицы смежности в её простоте. Так же для небольших графов легко увидеть, какие узлы соединены между собой. Однако, обратите внимание, что большинство ячеек в матрице пусты. Про такую матрицу мы говорим, что она "разреженная". Матрица - не самый эффективный способ хранить разреженные данные. Фактически, в Python вы должны приложить немало усилий, чтобы создать матричную структуру даже наподобие показанной на :ref:`рисунке 3 <fig_adjmat>`.

Матрица смежности - хорошее представление графа, который имеет большое количество рёбер. Но что значит "большое"? Сколько рёбер нужно, чтобы заполнить матрицу? Поскольку для каждой вершины графа нужно по одному столбцу и строке, то для заполнения матрицы требуется :math:`|V|^2` рёбер. Матрица заполнена, когда каждая вершина соединяется с каждой. В реальном мире существует несколько проблем с таким типом связи между компонентами. Однако, в этой главе все рассматриваемые задачи включают разреженные графы.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/Graphs/AnalysisofDijkstrasAlgorithm.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@
~~~~~~~~~~~~~~~~~~~~~~~~~

Наконец, давайте посмотрим на время выполнения алгоритма Дейкстры. Для начал отметим, что создание очереди с приоритетом занимает :math:`O(V)` времени, поскольку первоначально мы добавляем в неё каждую вершину из графа. После того, как очередь сформирована, запускается цикл ``while``. Он вычисляется один раз для каждого узла, так как все они добавлены с самого начала, а после только удаляются. Внутри цикла каждый вызов ``delMin`` занимает :math:`O(\log V)` времени. Вместе цикл и вызов ``delMin`` дают :math:`O(V \log(V))`. Цикл ``for`` вычисляется единожды для каждого ребра графа, а внутри него происходит вызов ``decreaseKey``. Вместе на это уходит :math:`O(E\log(V))` времени. Таким образом, общее время выполнения получается равным :math:`O((V+E) \log(V)).`

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/Graphs/BreadthFirstSearch.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@
Поиск в ширину
--------------


.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/Graphs/BreadthFirstSearchAnalysis.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@
Конечно, поиск в ширину - всего лишь часть задания. Проследовать по ссылкам от стартового узла до целевого является его второй частью. Наихудшим случаем станет граф в виде обычной длинной цепочки. Тогда проход по всем вершинам даст :math:`O(V)`. Обычно же берётся некая часть :math:`|V|`, но мы по-прежнему будем писать :math:`O(V)`.

Наконец, для данной задачи потребуется время на постороение начального графа. Мы оставляем анализ функции ``buildGraph`` в качестве упражнения для вас.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/Graphs/BuildingtheKnightsTourGraph.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,5 @@
:align: center

Рисунок 2: Все возможные ходы коня на доске :math:`8 \times 8`

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/Graphs/BuildingtheWordLadderGraph.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,5 @@
return g

Поскольку это наша первая задача на графы из реального мира, вам может быть любопытно, насколько разрежен результат. Имеющийся список четырёхбуквенных слов для неё содержит 5 110 элементов. Если бы мы использовали матрицу смежности, то в ней было бы 5 110 \* 5 110 = 26 112 100 ячеек. Граф, построенный функцией ``buildGraph`` имеет ровно 53 286 рёбер, так что матрица была бы заполнена только на 0.2%! Вот уж действительно *очень* разреженная матрица.

.. disqus::
2 changes: 2 additions & 0 deletions pythonds/source/Graphs/DepthFirstSearchAnalysis.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@
В общем случае время выполнения поиска в глубину следующее. Оба цикла в ``dfs`` выполняются за :math:`O(V)` (без учёта происходящего в ``dfsvisit``), поскольку они вычисляются по одному разу для каждой вершины графа. Цикл в ``dfsvisit`` вычисляется один раз для каждого ребра из списка смежности текущей вершины. Поскольку ``dfsvisit`` вызывается рекурсивно только в том случае, если вершина окрашена в белый, то цикл для каждого ребра графа выполнится максимум единожды (:math:`O(E)`). Таким образом, общее время выполнения поиска в глубину равно :math:`O(V + E)`.



.. disqus::
Loading

0 comments on commit c71f645

Please sign in to comment.