text:
#!/usr/bin/env julia
# coding: utf-8

# In[1]:

#aho corasick is a string search algorithm for multiple patterns
#its ability to match patterns in parallel is incredible
#kmp is merely a special case of ac
#ac is the most complicated string search algorithm in this repository
#check the link below for a more detailed tutorial
# https://blogs.asarkar.com/assets/docs/algorithms-curated/Aho-Corasick%20Automata%20-%20Stanford.pdf

# In[2]:

#naïve search iterates the letter one by one
function naive_search(pattern,rawtext)

    len_pattern=length(pattern)
    len_rawtext=length(rawtext)
    output=[]

    #this part is stupid
    #as julia allows us to do
    #rawtext[i:i+len_pattern-1]==pattern
    for i in 1:(len_rawtext-len_pattern+1)
        ignore=false
        j=1
        while !ignore
            if rawtext[i+j-1]!=pattern[j]
                ignore=true
            end
            j+=1
            if j>len_pattern
                if !ignore
                    push!(output,i)
                end
                ignore=true
            end
        end
    end
    return output
end

# In[3]:

#brute force search through each pattern
function naive_multi_search(patterns,rawtext)
    arr=[naive_search(pattern,rawtext) for pattern in patterns]
    result=Dict(zip(patterns,arr))
    return result
end

# In[4]:

#build a trie structure where edge represents each letter
#check the link below for explanation on suffix tree
# https://www.cs.jhu.edu/~langmea/resources/lecture_notes/tries_and_suffix_tries.pdf
function build_trie(patterns)

    #initialize
    trie=Dict(0=>Dict())
    vertex_counter=0
    ending_vertices=Dict()
    for pattern in patterns
        current_vertex=0
        for letter in pattern

            #no need to create a new branch
            #if the next letter exists in children nodes
            #move the current_vertex
            if letter in values(trie[current_vertex])
                edges=collect(values(trie[current_vertex]))
                ind=findfirst(x->x==letter,edges)
                current_vertex=collect(keys(trie[current_vertex]))[ind]

            #increment the vertex_counter to create a new branch
            #if the next letter does not exist in children nodes
            #move the current_vertex to vertex_counter
            else
                vertex_counter+=1
                trie[current_vertex][vertex_counter]=letter
                trie[vertex_counter]=Dict()
                current_vertex=vertex_counter
            end
        end

        #the last current_vertex marks the end of a pattern
        ending_vertices[current_vertex]=pattern
    end
    return trie,ending_vertices
end

# In[5]:

#bfs style traversal to build suffix links and output links
#details of bfs can be found in the link below
# https://github.com/je-suis-tm/graph-theory/blob/master/BFS%20DFS%20on%20DCG.ipynb
function build_links(trie,ending_vertices)

    #initialize
    #suffix link of root goes back to itself
    #suffix links of first layer nodes go to root
    suffix_links=Dict(0=>0)
    for i in keys(trie[0])
        suffix_links[i]=0
    end

    #initialize
    #all output links go nowhere
    output_links=Dict(zip(keys(trie),[NaN for _ in 1:length(trie)]))

    #bfs style to create suffix links and output links
    #queue1 and visited1 correspond to node w in stanford material
    queue1=collect(keys(trie[0]))
    visited1=[]
    while length(queue1)>0

        #node w in stanford material
        parent=popfirst!(queue1)
        push!(visited1,parent)

        #node wa in stanford material
        for child in keys(trie[parent])

            #queue2 and visited2 correspond to node xyz in stanford material
            queue2=[suffix_links[parent]]
            visited2=[]
            stop=false
            while !stop

                #node xyz
                aunt=popfirst!(queue2)
                push!(visited2,aunt)

                #if xa exists,the suffix link of node wa goes to xa
                if trie[parent][child] in values(trie[aunt])
                    ind=findfirst(x->x==trie[parent][child],collect(values(trie[aunt])))
                    suffix_links[child]=collect(keys(trie[aunt]))[ind]

                    #node u which is equivalent to node wa
                    #node v which is equivalent to node xa
                    #if node u is a pattern,output link of node v goes to node u
                    if collect(keys(trie[aunt]))[ind] in keys(ending_vertices)
                        output_links[child]=collect(keys(trie[aunt]))[ind]

                    #if node u is not a pattern
                    #output link of node v goes to output link of node u
                    #it can either be initial value null
                    #or existing pattern via output link
                    else
                        output_links[child]=output_links[collect(keys(trie[aunt]))[ind]]
                    end

                    #stop the loop
                    stop=true

                #if xa doesnt exist,follow suffix link of node x to find node yz
                else
                    if aunt in keys(suffix_links)
                        if !(suffix_links[aunt] in queue2) && !(suffix_links[aunt] in visited2)
                            push!(queue2,suffix_links[aunt])
                        end
                    end
                end

                #stop the loop
                if length(queue2)==0
                    stop=true
                end
            end

            #if no suffix link has been found
            #suffix link goes back to the root
            if !(child in keys(suffix_links))
                suffix_links[child]=0
            end

            #bfs
            if !(child in visited1)
                push!(queue1,child)
            end
        end
    end
    return suffix_links,output_links
end

# In[6]:

#matching process of aho corasick
function aho_corasick(patterns,rawtext)

    #reprocess
    trie,ending_vertices=build_trie(patterns)
    suffix_links,output_links=build_links(trie,ending_vertices)

    #initialize result
    result=Dict()
    for i in patterns
        result[i]=[]
    end

    #start from root
    start=0

    #iterate character by character
    for i in 1:length(rawtext)
        character=rawtext[i]

        #while current letter cannot support the traversal
        if !(character in values(trie[start]))
            stop=false
            while !stop
                start=suffix_links[start]

                #if start is at the root,break the loop
                #the next letter will start at the root as well
                if start==0
                    stop=true
                end

                #if we can find the current letter via suffix link
                #indicating the prefix of a pattern has been validated
                #we will move start pointer to that pattern accordingly
                if character in values(trie[start])
                    stop=true
                    ind=findfirst(x->x==character,collect(values(trie[start])))
                    start=collect(keys(trie[start]))[ind]
                end
            end

        #if current letter supports the traversal
        #move start pointer further down the trie
        else
            ind=findfirst(x->x==character,collect(values(trie[start])))
            start=collect(keys(trie[start]))[ind]
        end

        #if there exists an output link at the start pointer
        #the existing pattern is at the start pointer
        #minus the pattern length plus one
        if !isnan(output_links[start])
            push!(result[ending_vertices[output_links[start]]],
                                    i-length(ending_vertices[output_links[start]])+1)

            #trace every output along the chain of output links
            stop=false
            exhausted=output_links[start]
            while !stop
                if !isnan(output_links[exhausted])
                    push!(result[ending_vertices[output_links[exhausted]]],
                            i-length(ending_vertices[output_links[exhausted]])+1)
                    exhausted=output_links[exhausted]
                else
                    stop=true
                end
            end
        end

        #if there exists a pattern at the start pointer
        #the existing pattern is at the start pointer
        #minus the pattern length plus one
        if start in keys(ending_vertices)
            push!(result[ending_vertices[start]],i-length(ending_vertices[start])+1)
        end
    end
    return result
end

# In[7]:

patterns=["universality",
 "universal",
 "epicurus",
 "epicurean",
 "philosopher",
 "philosophy",
 "content",
 "contentment",
 "discontent",
 "athens","at","athenian"]

#sort patterns by their length in ascending order
#easier to find suffix link
patterns=sort(patterns,rev=false,by=length);

# In[8]:

#philosophy by hegel
rawtext=lowercase("""The Epicurean philosophy which forms the counterpart to Stoicism was just as much elaborated as the Stoic if indeed it were not more so While the latter posited as truth existence for thought the universal Notion and held firmly to this principle Epicurus the founder of the other system held a directly opposite view regarding as the true essence not Being in general but Being as sensation that is consciousness in the form of immediate particularity As the Stoics did not seek the principle of the Cynics that man must confine himself to the simplicity of nature in man s requirements but placed it in universal reason so Epicurus elevated the principle that happiness should be our chief end into the region of thought by seeking pleasure in a universal which is determined through thought And though in so doing he may have given a higher scientific form to the doctrines of the Cyrenaics it is yet self evident that if existence for sensation is to be regarded as the truth the necessity for the Notion is altogether abrogated and in the absence of speculative interest things cease to form a united whole all things being in point of fact lowered to the point of view of the ordinary human understanding Notwithstanding this proviso before we take this philosophy into consideration we must carefully divest ourselves of all the ideas commonly prevalent regarding Epicureanism As regards the life of Epicurus be was born in the Athenian village of Gargettus in Ol 109 3 B C 342 and therefore before the death of Aristotle which took place in Ol 114 3 His opponents especially the Stoles have raked up against him more accusations than I can tell of and have invented the most trivial anecdotes respecting his doings He had poor parents his father Neocles was village schoolmaster and Chaerestrata his mother was a sorceress that is she earned money like the women of Thrace and Thessaly by furnishing spells and incantations as was quite common in those days The father taking Epicurus with him migrated with an Athenian colony to Samos but here also he was obliged to give instruction to children because his plot of land was not sufficient for the maintenance of his family At the age of about eighteen years just about the time when Aristotle was living in Chalcis Epicurus returned to Athens He had already in Samos made the philosophy of Democritus a special subject of study and now in Athens he devoted himself to it more than ever in addition to this he was on intimate terms with several of the philosophers then flourishing such as Xenocrates the Platonist and Theophrastus a follower of Aristotle When Epicurus was twelve years old he read with his teacher Hesiod s account of Chaos the source of all things and this was perhaps not without influence on his philosophic views Otherwise he professed to be self taught in the sense that he produced his philosophy entirely from himself but we are not to suppose from this that he did not attend the lectures or study the writings of other philosophers Neither is it to be understood that he was altogether original in his philosophy as far as content was concerned for as will be noted later his physical philosophy especially is that of Leucippus and Democritus It was at Mitylene in Lesbos that he first came forward as teacher of an original philosophic system and then again at Lampsacus in Asia Minor he did not however find very many hearers After having for some years led an unsettled life he returned in about the six and thirtieth year of his age to Athens to the very centre of all Philosophy and there some time after he bought for himself a garden where he lived and taught in the midst of his friends Though so frail in body that for many years he was unable to rise from his chair in his manner of living lie was most regular and frugal and he devoted himself entirely to science to the exclusion of all other interests Even Cicero though in other respects he has little to say in his favour bears testimony to the warmth of his friendships and adds that no one can deny he was a good a humane and a kindly man Diogenes Laertius gives special commendation to his reverence towards his parents his generosity to his brothers and his benevolence to all He died of stone in the seventy first year of his age Just before his death he had himself placed in a warm bath drank a cup of wine and charged his friends to remember what he had taught them No other teacher has ever been loved and reverenced by his scholars as much as Epicurus they lived on such intimate terms of friendship that they determined to make common stock of their possessions with him and so continue in a permanent association like a kind of Pythagorean brotherhood This they were however forbidden to do by Epicurus himself because it would have betrayed a distrust in their readiness to share what they had with one another but where distrust is possible there neither friendship nor unity nor constancy of attachment can find a place After his death he was held in honoured remembrance by his disciples they carried about with them everywhere his likeness engraved on rings or drinking cups and remained so faithful to his teaching that they considered it almost a crime to make any alteration in it while in the Stoic philosophy development was continually going on and his school in respect of his doctrines resembled a closely barricaded state to which all entrance was denied The reason for this lies as we shall presently see in his system itself and the further result from a scientific point of view ensued that we can name no celebrated disciples of his who carried on and completed his teaching on their own account For his disciples could only have gained distinction for themselves by going further than Epicurus did But to go further would have been to reach the Notion which would only have confused the system of Epicurus for what is devoid of thought is thrown into confusion by the introduction of the Notion and it is this very lack of thought which has been made a principle Not that it is in itself without thought but the use made of thought is to hold back thought and thought thus takes up a negative position in regard to itself and the philosophic activity of Epicurus is thus directed towards the restoration and maintaining of what is sensuous through the very Notion which renders it confused Therefore his philosophy has not advanced nor developed but it must also be said that it has not retrograded a certain Metrodorus alone is said to have carried it on further in some directions It is also told to the credit of the Epicurean philosophy that this Metrodorus was the only disciple of Epicurus who went over to Carneades for the rest it surpassed all others in its unbroken continuity of doctrine and its long duration for all of them became degenerate or suffered interruption When some one called the attention of Arcesilaus to this attachment to Epicurus by the remark that while so many had gone over from other philosophers to Epicurus scarcely a single example was known of any one passing over from the Epicurean system to another Arcesilaus made the witty rejoinder Men may become eunuchs but eunuchs can never again become men Epicurus himself produced in his lifetime an immense number of works being a much more prolific author than Chrysippus who vied with him in the number of his writings if we deduct from the latter his compilations from the works of others or from his own The number of his writings is said to have amounted to three hundred it is scarcely to be regretted that they are lost to us We may rather thank Heaven that they no longer exist philologists at any rate would have had great trouble with them The main source of our knowledge of Epicurus is the whole of the tenth book of Diogenes Laertius which after all gives its but scanty information though it deals with the subject at great length We should of course have been better off had we possessed the philosopher s own writings but we know enough of him to make us honour the whole For besides this we know a good deal about the philosophy of Epicurus through Cicero Sextus Empiricus and Seneca and so accurate are the accounts they give of him that the fragment of one of Epicurus s own writings found some years ago in Herculaneum and reprinted by Orelli from the Neapolitan edition Epicuri Fragmenta libri II et XI De natura illustr Orellius Lipsiae 1818 has neither extended nor enriched our knowledge so that we must in all earnestness deprecate the finding of the remaining writings With regard to the Epicurean philosophy it is by no means to be looked on as setting forth a system of Notions but on the contrary as a system of ordinary conceptions or even of sensuous existence which looked at from the ordinary point of view as perceived by the senses Epicurus has made the very foundation and standard of truth p 277 A detailed explanation of how sensation can be such he has given in his so called Canonic As in the case of the Stoics we have first to speak of the manner which Epicurus adopted of Determining the criterion of truth secondly of his philosophy of nature and thirdly and lastly of his moral teaching 1 Canonical Philosophy Epicurus gave the name of Canonic to what is really a system of logic in which he defines the criteria of truth in regard to the theoretic as in fact sensuous perceptions and further as conceptions or anticipations prolhqeis in regard to the practical as the passions impulses and affections a On the theoretic side the criterion closely considered has according to Epicurus three moments which are the three stages of knowledge first sensuous perception as the side of the external secondly ordinary conception as the side of the internal thirdly opinion doxa as the union of the two a Sensuous perception is devoid of reason being what is given absolutely For it is not moved by itself nor can it if it is moved by something else take away from or add to that which it is but it is exactly what it is It is beyond criticism or refutation For neither can one sensation judge another both being alike since both have equal authority when the presentations of sight are of the same kind every one of them must admit the truth of all the rest Nor can one of them pass judgment on another when they are unlike for they each have their value as differing red and blue for example are each something individual Nor can one sensation pass judgment on another when they are heterogeneous for we give heed to all Thought in the same way cannot criticise the senses for all thought itself depends on the sensation which forms its content But sensuous perception may go far wrong The truth of what our senses perceive is first evinced by this that the power of perception remains with us sight and hearing are permanent powers of this kind as much as the capacity of feeling pain In this way even the unknown the unperceived may be indicated by means of that which appears perception Of this conception of objects of perception which are not immediate we shall have to speak more particularly hereafter p 292 in dealing with physical science Thus all unknown imperceptible thoughts originated in the senses either directly in respect of their chance origin or in respect of relationship analogy and combination to these operations thought also contributes something namely as the formal connection of the sensuous conceptions The fancies of the insane or of our dreams are also true for they act upon us but that which is not real does not act Thus every sensuous perception is explicitly true in so far as it shows itself to be abiding and that which is not apparent to our senses must be apprehended after the same manner as the perception known to us We hear Epicurus say just as we hear it said in everyday life What I see and hear or speaking generally what I perceive by my senses comprises the existent every such object of sense exists on its own account one of them does not contradict the other but all are on the same level of validity and reciprocally indifferent These objects of perception are themselves the material and content of thought inasmuch as thought is continually making use of the images of these things b Ordinary conception is now a sort of comprehension katalhqis or correct opinion or thought or the universal indwelling power of thinking that is to say it is the recollection of that which has often appeared to us the picture For instance when I say this is a man I with the help of previous perceptions at once by my power of representation recognise his form By dint of this repetition the sensuous perception becomes a permanent conception in me which asserts itself that is the real foundation of all that we hold true These representations are universal but certainly the Epicureans have not placed universality in the form of thinking but only said it is caused by frequency of appearance This is further confirmed by the name which is given to the image which has thus arisen within us Everything has its evidence enarges esti in the name first conferred on it The name is the ratification of the perception The evidence which Epicurus terms enargeia is just the recognition of the sensuous through subsumption under the conceptions already possessed and to which the name gives permanence the evidence of a conception is therefore this that we affirm an object perceptible by the senses to correspond with the image That is the acquiescence which we have found taking place with the Stoics when thought gives its assent to a content thought however which recognises the thing as its own and receives it into itself with the Stoics remained formal only With Epicurus the unity of the conception of the object with itself exists also as a remembrance in consciousness which however proceeds from the senses the image the conception is what harmonises with a sense perception The recognition of the object is here an apprehension not as an object of thought but as an object of imagination for apprehension belongs to recollection to memory The name it is true is some thing universal belongs to thinking makes the manifold simple yea is in a high degree ideal but in such a way that its meaning and its content are the sensuous and are not thus to be counted as simple but as sensuous In this way opinion is established instead of knowledge c In the last place opinion is nothing but the reference of that general conception which we have within us to an object a perception or to the testimony of the senses and that is the passing of a judgment For in a conception we have anticipated that which comes directly before our eyes and by this standard we pronounce whether something is a man a tree or not Opinion depends on something already evident to us to which we refer when we ask how we know that this is a man or not This opinion is also itself termed conception and it may be either true or false true when what we see before our eyes is corroborated or not contradicted by the testimony of the conception false in the opposite case That is to say in opinion we apply a conception which we already possess or the type to an object which is before us and which we then examine to see if it corresponds with our mental representation of it Opinion is true if it corresponds with the type and it has its criterion in perceiving whether it repeats itself as it was before or not This is the whole of the ordinary process in consciousness when it begins to reflect When we have the conception it requires the testimony that we have seen or still see the object in question From the sensuous perceptions blue sour sweet and so on the general conceptions which we possess are formed and when an object again comes before us we recognise that this image corresponds with this object This is the whole criterion and a very trivial process it is for it goes no further than the first beginnings of the sensuous consciousness the immediate perception of an object The next stage is without doubt this that the first perception forms itself into a general image and then the object which is present is subsumed under the general image That kind of truth which anything has of which it can only be said that the evidence of the senses does not contradict it is possessed by the conceptions of the unseen for instance the apprehension of heavenly phenomena here we cannot approach nearer we can see something indeed but we cannot have the sensuous perception of it in its completeness we therefore apply to it what we already know by other perceptions if there is but some circumstance therein which is also present in that other perception or conception supra p 282 b From these external perceptions of objects presently existing with which we here began the affections the internal perceptions which give the criteria for practical life are however distinguished they are of two kinds either pleasant or unpleasant That is to say they have as their content pleasure or satisfaction and pain the first as that which peculiarly belongs to the perceiver is the positive but pain as something alien to him is the negative It is these sensuous perceptions which determine action they are the material from which general conceptions regarding what causes me pain or pleasure are formed as being permanent they are therefore again conceptions and opinion is again this reference of conception to perception according to which I pass judgment on objects affections desires and so on It is by this opinion therefore that the decision to do or to avoid anything is arrived at This constitutes the whole Canon of Epicurus the universal standard of truth it is so simple that nothing can well be simpler and yet it is very abstract It consists of ordinary psychological conceptions which are correct on the whole but quite superficial it is the mechanical view of conception having respect to the first beginnings of observation But beyond this there lies another and quite different sphere a field that contains determinations in themselves and these are the criteria by which the statements of Epicurus must be judged Nowadays even Sceptics are fond of speaking of facts of consciousness this sort of talk goes no further than the Epicurean Canon 2 Metaphysics In the second place Epicurus enters on a metaphysical explanation of how we are related to the object for sensuous perception and outside impressions he unhesitatingly regards as our relation to external things so that he places the conceptions in me the objects outside of me In raising the question of how we come by our conceptions there lies a double question on the one hand since sense perceptions are not like conceptions but require an external object what is the objective manner in which the images of external things enter into us On the other hand it may be asked how conceptions of such things as are not matter of perception arise in us this seems to be an activity of thought which derives conceptions such as these from other conceptions we shall however see presently pp 287 288 and more in detail how the soul which is here related to the object in independent activity arrives at such a point From the surfaces of things says Epicurus in the first place there passes elf a constant stream which cannot be detected by our senses for things would in any other case decrease in size and which is very fine and this because by reason of the counteracting replenishment the thing itself in its solidity long preserves the same arrangement and disposition of the atoms and the motion through the air of these surfaces which detach themselves is of the utmost rapidity because it is not necessary that what is detached should have any thickness it is only a surface Epicurus says Such a conception does not contradict our senses when we take into consideration how pictures produce their effects in a very similar way I mean by bringing us into sympathy with external things Therefore emanations like pictures pass out from them into us so that we see and know the forms and colours of things This is a very trivial way of representing sense perception Epicurus took for himself the easiest criterion of the truth that is not seen a criterion still in use namely that it is not contradicted by what we see or hear For in truth such matters of thought as atoms the detachment of surfaces and so forth are beyond our powers of sight Certainly we manage to see and to hear something different but there is abundance of room for what is seen and what is conceived or imagined to exist alongside of one another If the two are allowed to fall apart they do not contradict each other for it is not until we relate them that the contradiction becomes apparent Error as Epicurus goes on to say on the second point comes to pass when through the movement that takes place within us on the conception therein wrought such a change is effected that the conception can no longer obtain for itself the testimony of perception There would be no truth no likeness of our perceptions which we receive as in pictures or in dreams or in any other way if there were nothing on which we as it were put out our faculty of observation There would be no untruth if we did not receive into ourselves another movement which to be sure is conformable to the entering in of the conception but which has at the same time an interruption Error is therefore according to Epicurus only a displacement of the pictures in us which does not proceed from the movement of perception but rather from this that we cheek their influence by a movement originating in ourselves how this interruption is brought about will be shown more fully later on pp 290 300 The Epicurean theory of knowledge reduces itself to these few passages some of which are also obscurely expressed or else not very happily selected or quoted by Diogenes Laertius it is impossible to have a theory less explicitly stated Knowledge on the side of thought is determined merely as a particular movement which makes an interruption and as Epicurus as we have already seen looks on things as made up of a multitude of atoms thought is the moment which is different from the atoms the vacuum the pores whereby resistance to this stream of atoms is rendered possible If this negative is also again as soul affirmative Epicurus in the notional determination of thinking has only reached this negativity that we look away from something i e we interrupt that inflowing stream The answer to the question of what this interrupting movement exactly is when taken for itself is connected with the more advanced conceptions of Epicurus and in order to discuss them more in detail we must go back to the implicit basis of his system This constitutes on the whole the metaphysic of Epicurus in it he has expounded his doctrine of the atom but not with greater definiteness than did Leucippus and Democritus The essence and the truth of things were to him as they were to them atoms and vacuum Atoms have no properties except figure weight and magnitude Atoms as atoms must remain undetermined but the Atomists have been forced to take the inconsistent course of ascribing properties to them the quantitative properties of magnitude and figure the qualitative property of weight But that which is in itself altogether indivisible can have neither figure nor magnitude and even weight direction upon something else is opposed to the abstract repulsion of the atom Epicurus even says Every property is liable to change but the atoms change not In all dissolutions of the composite something must remain a constant and indissoluble which no change can transform into that which is not or brine from non being into Being This unchangeable element therefore is constituted by some bodies and figures The properties are a certain relation of atoms to each other In like manner we have already seen with Aristotle p 178 that the tangible is the foundation of properties a distinction which under various forms is still always made and is in common use We mean by this that an opposition is established between fundamental properties such as we here have in weight figure and magnitude and sensuous properties which are only in relation to us and are derived from the former original differences This has frequently been understood as if weight were in things while the other properties were only in our senses but in general the former is the moment of the implicit or the abstract essence of the thing while the latter is its concrete existence which expresses its relation to other things The important matter now would be to indicate the relation of atoms to sensuous appearance to allow essence to pass over into the negative but here Epicurus rambles amidst the indeterminate which expresses nothing for we perceive in him as in the other physicists nothing but an unconscious medley of abstract ideas and realities All particular forms all objects light colour c the soul itself even are nothing but a certain arrangement of these atoms This is what Locke also said and even now Physical Science declares that the basis of things is found in molecules which are arranged in a certain manner in space But these are empty words and a crystal for instance is not a certain arrangement of parts which gives this figure It is thus not worth while to deal with this relation of atoms for it is an altogether formal way of speaking as when Epicurus again concedes that figure and magnitude in so far as pertaining to atoms are something different from what they are as they appear in things The two are not altogether unlike the one implicit magnitude has something in common with apparent magnitude The latter is transitory variable the former has no interrupted parts that is nothing negative But the determination of the atoms as originally formed in this or that fashion and having original magnitude of such and such a kind is a purely arbitrary invention That interruption which we regarded above p 288 as the other side to atoms or as vacuum is the principle of movement for the movement of thought is also like this and has interruptions Thought in man is the very same as atoms and vacuum are in things namely their inward essence that is to say atoms and vacuum belong to the movement of thought or exist for this in the same way as things are in their essential nature The movement of thinking is thus the province of the atoms of the soul so that there takes place simultaneously therein an interruption of the inward flow of atoms from without There is therefore nothing further to be seen in this than the general principle of the positive and negative so that even thought is affected by a negative principle the moment of interruption This principle of the Epicurean system further applied to the difference in things is the most arbitrary and therefore the most wearisome that can be imagined Besides their different figures atoms have also as the fundamental mode in which they are affected a difference of movement caused by their weight but this movement to some extent deviates from the straight line in its direction That is to say Epicurus ascribes to atoms a curvilinear movement in order that they may impinge on one another and so on In this way there arise particular accumulations and configurations and these are things Other physical properties such as taste and smell have their basis again in another arrangement of the molecules But there is no bridge from this to that or what results is simply empty tautology according to which the parts are arranged and combined as is requisite in order that their appearance may be what it is The transition to bodies of concrete appearance Epicurus has either not made at all or what has been cited from him as far as this matter is concerned taken by itself is extremely meagre The opinion that one hears expressed respecting the Epicurean philosophy is in other respects not unfavourable and for this reason some further details must be given regarding it For since absolute Being is constituted by atoms scattered and disintegrated and by vacuum it directly follows that Epicurus denies to these atoms any relationship to one another which implies purpose All that we call forms and organisms or generally speaking the unity of Nature s end in his way of thinking belongs to qualities to an external connection of the configurations of the atoms which in this way is merely an accident brought about by their chance directed motion the atoms accordingly form a merely superficial unity and one which is not essential to them Or else Epicurus altogether denies that Notion and the Universal are the essential and because all originations are to him chance combinations for him their resolution is just as much a matter of chance The divided is the first and the truly existent but at the same time chance or external necessity is the law which dominates all cohesion That Epicurus should in this fashion declare himself against a universal end in the world against every relation of purpose as for instance the inherent conformity to purpose of the organism and further against the teleological representations of the wisdom of a Creator in the world his government c is a matter of course for he abrogates unity whatever be the manner in which we represent it whether as Nature s end in itself or as end which is in another but is carried out in Nature In contrast to this the teleological view enters largely into the philosophy of the Stoics and is there very fully developed To show that conformity to an end is lacking Epicurus brings forward the most trivial examples for instance that worms and so on are produced by chance from mud through the warmth of the sun Taken in their entirety they may very well be the work of chance in relation to others but what is implicit in them their Notion and essence is something organic and the comprehension of this is what we have now to consider But Epicurus banishes thought as implicit without its occurring to him that his atoms themselves have this very nature of thought that is their existence in time is not immediate but essentially mediate and thus negative or universal the first and only inconsistency that we find in Epicurus and one which all empiricists are guilty of The Stoics take the opposite course of finding essential Being in the object of thought or the universal and they fail equally in reaching the content temporal existence which however they most inconsistently assume We have here the metaphysics of Epicurus nothing that he says further on this head is of interest 3 Physics The natural philosophy of Epicurus is based on the above foundation but an aspect of interest is given it by the fact that it is still peculiarly the method of our times his thoughts on particular aspects of Nature are however in themselves feeble and of little weight containing nothing but an ill considered medley of all manner of loose conceptions Going further the principle of the manner in which Epicurus looks on nature lies in the conceptions he forms which we have already had before us pp 282 285 That is to say the general representations which we receive through the repetition of several perceptions and to which we relate such perceptions in forming an opinion must be then applied to that which is not exactly matter of perception but yet has something in common with what we can perceive In this way it comes about that by such images we can apprehend the unknown which does not lend itself immediately to perception for from what is known we must argue to what is unknown This is nothing else but saying that Epicurus judged by analogy or that he makes so called evidence the principle of his view of Nature and this is the principle which to this day has authority in ordinary physical science We go through experiences and make observations these arising from the sensuous perceptions which are apt to be overlooked Thus we reach general concepts laws forces and so on electricity and magnetism for instance and these are then applied by us to such objects and activities as we cannot ourselves directly perceive As an example we know about the nerves and their connection with the brain in order that there may be feeling and so on it is said that a transmission from the finger tips to the brain takes place But how can we represent this to ourselves We cannot make it a matter of observation BY anatomy we can lay bare the nerves it is true but not the manner of their working We represent these to ourselves on the analogy of other phenomena of transmission for instance as the vibration of a tense string that passes through the nerve to the brain As in the well known phenomenon of a number of billiard balls set close together in a row the last of which rolls away when the first is struck while those in the middle through each of which the effect of the stroke has been communicated to the next scarcely seem to move so we represent to ourselves the nerves as consisting of tiny balls which are invisible even through the strongest magnifying glass and fancy that at every touch c the last springs off and strikes the soul In the same way light is represented as filaments rays or as vibrations of the ether or as globules of ether each of which strikes on the other This is an analogy quite in the manner of Epicurus In giving such explanations as those above Epicurus professed to be most liberal fair and tolerant saying that all the different conceptions which occur to us in relation to sensuous objects at our pleasure we may say can be referred to that which we cannot ourselves directly observe we should not assert any one way to be the right one for many ways may be so In so saying Epicurus is talking idly his words fall on the ear and the fancy but looked on more narrowly they disappear So for instance we see the moon shine without being able to have any nearer experience of it On this subject Epicurus says The moon may have its own light or a light borrowed from the sun for even on earth we see things which shine of themselves and many which are illuminated by others Nothing hinders us from observing heavenly things in the light of various previous experiences and from adopting hypotheses and explanations in accordance with these The waxing and waning of the moon may also be caused by the revolution of this body or through changes in the air according as vapour is modified in one way or another or also by means of adding and taking away somewhat in short in all the ways whereby that which has a certain appearance to us is caused to show such appearance Thus there are to be found in Epicurus all these trivialities of friction concussion c as when he gives his opinion of lightning on the analogy of how we see fire of other kinds kindled Lightning is explained by quite a large number of possible conceptions for instance that through the friction and collision of clouds the figuration of fire is emitted and lightning is produced In precisely the same way modern physicists transfer the production of an electric spark when glass and silk are rubbed against each other to the clouds For as we see a spark both in lightning and electricity we conclude from this circumstance common to both that the two are analogical therefore we come to the conclusion that lightning also is an electric phenomenon But clouds are not hard bodies and by moisture electricity is more likely to be dispersed therefore such talk has just as little truth in it as the fancy of Epicurus He goes on to say Or lightning may also be produced by being expelled from the clouds by means of the airy bodies which form lightning by being struck out when the clouds are pressed together either by each other or by the wind c With the Stoics things are not much better Application of sensuous conceptions according to analogy is often termed comprehension or explanation but in reality there is in such a process not the faintest approach to thought or comprehension One man adds Epicurus may select one of these modes and reject the others not considering what is possible for man to know and what is impossible and therefore striving to attain to a knowledge of the unknowable This application of sensuous images to what has a certain similarity to them is pronounced to be the basis and the knowledge of the cause because in his opinion a transference such as this cannot be corroborated by the testimony of mere immediate sensation thus the Stoic method of seeking a basis in thought is excluded and in this respect the mode of explanation adopted by Epicurus is directly opposed to that of the Stoics One circumstance which strikes xis at once in Epicurus is the lack of observation and experience with regard to the mutual relations of bodies but the kernel of the matter the principle is nothing else than the principle of modern physics This method of Epicurus has been attacked and derided but on this score no one need be ashamed of or fight shy of it if he is a physicist for what Epicurus says is not a whit worse than what the moderns assert Indeed in the case of Epicurus the satisfactory Assurance is likewise always present of his emphasising the fact most strongly that just because the evidence of the senses is found to be lacking we must not take our stand on any one analogy Elsewhere he in the same way makes light of analogy and when one person accepts this possibility and another that other possibility he admires the cleverness of the second and troubles himself little about the explanation given by the first it may be so or it may not be so This is a method devoid of reason which reaches no further than to general conceptions Nevertheless if Physical Science is considered to rebate to immediate experience on the one hand and on the other hand in respect of that which cannot be immediately experienced to relate to the application of the above according to a resemblance existing between it and that which is not matter of experience in that case Epicurus may well be looked on as the chief promoter if not the originator of this method and also as having asserted that it is identical with knowledge Of the Epicurean method in philosophy we may say this that it likewise has a side on which it possesses value and we may in some measure assent when we hear as we frequently do the Epicurean physics favourably spoken of Aristotle and the earlier philosophers took their start in natural philosophy from universal thought a priori and from this developed the Notion this is the one side The other side which is just as necessary demands that experience should be worked up into universality that laws should be found out that is to say that the result which follows from the abstract Idea should coincide with the general conception to which experience and observation have led up The a priori is with Aristotle for instance most excellent but not sufficient because to it there is lacking connection with and relation to experience and observation This leading up of the particular to the universal is the finding out of laws natural forces and so on It may thus be said that Epicurus is the inventor of empiric Natural Science of empiric Psychology In contrast to the Stoic ends conceptions of the understanding experience is the present as it appears to the senses there we have abstract limited understanding without truth in itself and therefore without the present in time and the reality of Nature here we have this sense of Nature which is more true than these other hypotheses The same effect which followed the rise of a knowledge of natural laws c in the modern world was produced by the Epicurean philosophy in its own sphere that is to say in so far as it is directed against the arbitrary invention of causes The more in later times men made acquaintance with the laws of Nature the more superstition miracles astrology c disappeared all this fades away owing to the contradiction offered to it by the knowledge of natural laws The method of Epicurus was directed more especially against the senseless superstition of astrology c in whose methods there is neither reason nor thought for it is quite a thing of the imagination downright fabrication being resorted to or what we may even term lying In contrast with this the way in which Epicurus works when the conceptions and not thought are concerned accords with truth For it does not go beyond what is perceived by the sight and hearing and the other senses but keeps to what is present and not alien to the mind not speaking of certain things as if they could be seen and heard when that is quite impossible seeing that the things are pure inventions The effect of the Epicurean philosophy in its own time was therefore this that it set itself against the superstition of the Greeks and Romans and elevated men above it All the nonsense about birds flying to right or to left or a hare running across the path or men deciding hew they are to act according to the entrails of animals or according as chickens are lively or dull all that kind of superstition the Epicurean philosophy made short work of by permitting that only to be accepted as truth which is counted as true by sense perception through the instrumentality of anticipations and from it more than anything those conceptions which have altogether denied the supersensuous have proceeded The physics of Epicurus were therefore famous for the reason that they introduced more enlightened dews in regard to what is physical and banished the fear of the gods Superstition passes straightway from immediate appearances to God angels demons or it expects from finite things other effects than the conditions admit of phenomena of a higher kind To this the Epicurean natural philosophy is utterly opposed because in the sphere of the finite it refuses to go beyond the finite and admits finite causes alone for the so called enlightenment is the fact of remaining in the sphere of the finite There connection is sought for in other finite things in conditions which are themselves conditioned superstition on the contrary rightly or wrongly passes at once to what is above us However correct the Epicurean method may be in the sphere of the conditioned it is not so in other spheres Thus if I say that electricity comes from God I am right and yet wrong For if I ask for a cause in this same sphere of the conditioned and give God as answer I say too much though this answer fits all questions since God is the cause of everything what I would know here is the particular connection of the phenomenon On the other hand in this sphere even the Notion is already something higher but this loftier way of looking at things which we met with in the earlier philosophers was quite put an end to by Epicurus since with superstition there also passed away self dependent connection and the world of the Ideal To the natural philosophy of Epicurus there also belongs his conception of the soul which he looks on as having the nature of a thing just as the theories of our own day regard it as nerve filaments cords in tension or rows of minute balls p 294 His description of the soul has therefore but little meaning since here also he draws his conclusion by analogy and connects therewith the metaphysical theory of atoms The soul consists of the finest and roundest atoms which are something quite different from fire being a fine spirit which is distributed through the whole aggregate of the body and partakes of its warmth Epicurus has consequently established a quantitative difference only since these finest atoms are surrounded by a mass of coarser atoms and dispersed through this larger aggregate The part which is devoid of reason is dispersed in the body as the principle of life but the self conscious part to logikon is in the breast as may be perceived from joy and sadness The soul is capable of much change in itself owing to the fineness of its parts which can move very rapidly it sympathises with the rest of the aggregate as we see by the thoughts emotions and so on but when it is taken away from us we die But the soul on its part has also the greatest sympathy with sensuous perception yet it would have nothing in common with it were it not in a certain measure covered by the rest of the aggregate the body an utterly illogical conception The rest of this aggregate which this principle provides for the soul is thereby also partaker on its part of a like condition sensuous perception yet not of all that the former possesses therefore when the soul escapes sensuous perception exists no more for it The aggregate spoken of above has not this power in itself but derives it from the other which is brought into union with it and the sentient movement comes to pass through the flow of sympathy which they have in common Of such conceptions it is impossible to make anything The above mentioned p 287 interruption of the streaming together of images of external things with our organs as the ground of error is now explained by the theory that the soul consists of peculiar atoms and the atoms are separated from one another by vacuum With such empty words and meaningless conceptions we shall no longer detain ourselves we can have no respect for the philosophic thoughts of Epicurus or rather he has no thoughts for us to respect 4 Ethics Besides this description of the soul the philosophy of mind contains the ethics of Epicurus which of all his doctrines are the most decried and therefore the most interesting they may however also be said to constitute the best part of that philosophy The practical philosophy of Epicurus depends on the individuality of self consciousness just as much as does that of the Stoics and the end of his ethics is in a measure the same the unshaken tranquillity of the soul and more particularly an undisturbed pure enjoyment of itself Of course if we regard the abstract principle involved in the ethics of Epicurus our verdict cannot be other than exceedingly unfavourable For if sensation the feeling of pain and pleasure is the criterion for the right good true for that which man should make his aim in life morality is really abrogated or the moral principle is in fact not moral at least we hold that the way is thereby opened up to all manner of arbitrariness in action If it is now alleged that feeling is the ground of action and that because I find a certain impulse in myself it is for that reason right this is Epicurean reasoning Everyone may have different feelings and the same person may feel differently at different times in the same way with Epicurus it may be left to the subjectivity of the individual to determine the course of action But it is of importance to notice this that when Epicurus sets up pleasure as the end he concedes this only so far as its enjoyment is the result of philosophy We have before now remarked vol i p 470 that even with the Cyrenaics while on the one hand sensation was certainly made the principle on the other hand it was essential that thought should be in intimate connection with it Similarly it is the case with Epicurus that while he designated pleasure as the criterion of the good he demanded a highly cultured consciousness a power of reflection which weighs pleasure to see if it is not combined with a greater degree of pain and in this way forms a correct estimate of what it is Diogenes Laertius X 144 quotes from him with regard to this point of view The wise man owes but little to chance Reason attains what is of the greatest consequence and both directs it and will direct it his whole life long The particular pleasure is therefore regarded only with reference to the whole and sensuous perception is not the one and only principle of the Epicureans but while they made pleasure the principle they made a principle at the same time of that happiness which is attained and only attainable by reason so that this happiness is to be sought in such a way that it may be free and independent of external contingencies the contingencies of sensation The true Epicureans were therefore just as much as the Stoics raised above all particular ties for Epicurus too made his aim the undisturbed tranquillity of the wise man In order to be free from superstition Epicurus specially requires physical science as it sets men free from all the opinions which most disturb their rest opinions regarding the gods and their punishments and more particularly from the thought of death Freed from till this fear and from the imaginings of the men who make any particular object their end and aim the wise man seeks pleasure only as something universal and holds this alone to be positive Here the universal and the particular meet or the particular regarded only in its bearings to the whole is raised into the form of universality Thus it happens that while materially or as to content Epicurus makes individuality a principle on the other hand he requires the universality of thinking and his philosophy is thus in accordance with that of the Stoics Seneca who is known as a thorough going and uncompromising Stoic when in his treatise De Vita Beata c 12 13 he happens to speak of the Epicureans gives testimony which is above suspicion to the ethical system of Epicurus My verdict is however and in thus speaking I go to some extent against many of my own countrymen that the moral precepts of Epicurus prescribe a way of life that is holy and just and when closely considered even sorrowful For every pleasure of Epicurus turns on something very paltry and poor and we scarcely know how restricted it is and how insipid The self same law which we lay down for virtue he prescribes for pleasure he requires that Nature be obeyed but very little in the way of luxury is required to satisfy Nature What have we then here He who calls a lazy self indulgent and dissolute life happiness merely seeks a good authority for a thing that is evil and while drawn on by a dazzling name he turns in the direction where he hears the praise of pleasure sounding he does not follow the pleasures to which he is invited by Epicurus but those which he himself brings with him Men who thus abandon themselves to crime seek only to hide their wickedness under the mantle of philosophy and to furnish for their excesses a pretext and an excuse Thus it is by no means permitted that youth should hold up its head again for the reason that to the laxity of its morality an honourable title has been affixed By the employment of our reflective powers which keep guard over pleasure and consider whether there can be any enjoyment in that which is fraught with dangers fear anxiety and other troubles the possibility of our obtaining pleasure pure and unalloyed is reduced to a minimum The principle of Epicurus is to live in freedom and ease and with the mind at rest and to this end it is needful to renounce much of that which men allow to sway them and in which they find their pleasure The life of a Stoic is therefore but little different from that of an Epicurean who keeps well before his eyes what Epicurus enjoins It might perhaps occur to us that the Cyrenaics had the same moral principle as the Epicureans but Diogenes Laertius X 139 136 137 shows us the difference that there was between them The Cyrenaics rather made pleasure as a particular thing their end while Epicurus on the contrary regarded it as a means since he asserted painlessness to be pleasure and allowed of no intermediate state Neither do the Cyrenaics recognise pleasure in rest katasthmatikhn but only in the determination of motion or as something affirmative that consists in the enjoyment of the pleasant Epicurus on the contrary admits both the pleasure of the body as well as that of the soul He meant by this that pleasure in rest is negative as the absence of the unpleasant and also an inward contentment whereby rest is maintained within the mind Epicurus explained these two kinds of pleasure more clearly as follows Freedom from fear and desire ataraxia and from pain and trouble aponia are the passive pleasures katasthmatikai hdonai the setting of our affections on nothing which we may run the risk of losing pleasures of the senses on the other hand like joy and mirth xara de kai enfrosunh are pleasures involving movement kata kinhsin energeia blepontai The former pleasures Epicurus held to be the truest and highest Besides this pain of the body was held by the Cyrenaics to be worse than sorrow of the soul while with the Epicureans this is reversed The main teaching of Epicurus in respect of morals is contained in a letter to Menoeceus which Diogenes Laertius has preserved and in which Epicurus expresses himself as follows The youth must neither be slow to study philosophy nor must the old man feel it a burden for no one is either too young or too old to study the health of his soul We must therefore endeavour to find out wherein the happy life consists the following are its elements First we must hold that God is a living Being incorruptible and happy as the general belief supposes Him to be and that nothing is lacking to His incorruptibility nor to His happiness But though the existence of the gods is known to be a fact yet they are not such as the multitude suppose them to be He is therefore not impious who discards his faith in the gods of the multitude but he who applies to them the opinions entertained of them by the mass By these gods of Epicurus we can understand nothing else than the Holy the Universal in concrete form The Stoics held more to the ordinary conception without indeed giving much thought to the Being of God with the Epicureans on the other hand the gods express an immediate Idea of the system Epicurus says That which is holy and incorruptible has itself no trouble nor causes it to others therefore it is unstirred by either anger or show of favour for it is in weakness only that such find a place The gods may be known by means of Reason they consist partly in Number others are the perfected type of man which owing to the similarity of the images arises from the continuous confluence of like images on one and the same subject The gods are thus the altogether general images which we receive into ourselves and Cicero says Do Natura Deorum 18 38 that they come singly upon us in sleep This general image which is at the same time ail anthropomorphic conception is the same to which we give the name of Ideal only that here the source assigned to it is the reiterated occurrence of images The gods thus seem to Epicurus to be Ideals of the holy life they are also existent things consisting of the finest atoms they are however pure souls unmixed with any grosser element and therefore exempt from toil and trouble and pain Their self enjoyment is wholly passive as it must be if consistent for action has always in it something alien the opposition of itself and reality and the toil and trouble which are involved in it really represent the aspect of consciousness of opposition rather than that of realisation The gods lead an existence of pure and passive self enjoyment and trouble themselves not with the affairs of the world and of men Epicurus goes on to say Men must pay reverence to the gods on account of the perfection of their nature and their surpassing holiness not in order to gain from them some special good or for the sake of this or that advantage The manner in which Epicurus represents the gods as corporeal Beings in human likeness has been much derided thus Cicero for instance in the passage quoted c 18 laughs at Epicurus for alleging that the gods have only quasi bodies flesh and blood But from this there follows only that they are as it were the implicit as we see it stated of the soul and things palpable to the senses that they have behind them what is implicit Our talk of qualities is no better for if justice goodness and so on are to be taken in sensu eminentiori and not as they are with men we have in God a Being in the same way possessed of only something resembling justice and the other qualities With this there is closely connected the theory of Epicurus that the gods dwell in vacant space in the intermediate spaces of the world where they are exposed neither to rain or wind or snow or the like For the intermediate spaces are the vacuum wherein as the principle of movement are the atoms in themselves Worlds as phenomena are complete continuous concretions of such atoms but concretions which are only external relations Between them as in vacuum there are thus these Beings also which themselves are certainly concretions of atoms but concretions which remain implicit Yet this leads only to confusion if a closer definition is given for concretion constitutes what is for the senses but the gods even if they were concretions would not be realities exactly such as these In illogical fashion the general the implicit is taken out of reality and set above it not as atoms but just as before as a combination of these atoms in this way this combination is not itself the sensuous This seems ridiculous but it is connected with the interruptions spoken of and with the relation of the vacuum to the plenum the atom So far therefore the gods belong to the category of negativity as against sensuality and as this negative is thought in that sense what Epicurus said of the gods may still to some extent be said To this determination of God a larger measure of objectivity of course belongs but it is a perfectly correct assertion that God as Thought is a holy Being to whom reverence is due for His own sake alone The first element in a happy life is therefore reverence for the gods uninfluenced by fear or hope Farther a second point with Epicurus is the contemplation of death the negative of existence of self consciousness in man he requires us to have a true conception of death because otherwise it disturbs our tranquillity He accordingly says Accustom thyself then to the thought that death concerns us not for all good and evil is a matter of sensation but death is a deprivation sterhsis of sensation Therefore the true reflection that death is no concern of ours makes our mortal life one of enjoyment since this thought does not add an endless length of days but does away with the longing after immortality For nothing in life has terrors for him who has once truly recognised the fact that not to live is not a matter of dread Thus it is a vain thing to fear death not because its presence but because the anticipation of it brings us pain For how can the anticipation of a thing pain us when its reality does not There is therefore in death nothing to trouble us For when we are in life death is not there and when death is there we are not Therefore death does not concern either the living or the dead This is quite correct if we look at the immediate it is a thought full of meaning and drives away fear Mere privation which death is is not to be confounded with the feeling of being alive which is positive and there is no reason for worrying oneself about it But the future in general is neither ours nor is it not ours hence we must not count upon it as something that will come to pass nor yet despair of it as if it would not come to pass It is no concern of ours either that it is or that it is not and it need not therefore cause us uneasiness This the right way in which to regard the future also Epicurus passes on to speak of impulses saying This moreover is to be kept in mind that amongst impulses some are natural but others are vain and of those that are natural some are necessary while others are natural only Those that are necessary are either necessary to happiness or tend to save the body from pain or to self preservation in general The perfect theory teaches how to choose that which promotes health of body and steadfastness of soul and how to reject what impairs them this being the aim of the holy life This is the end of all our actions to have neither pain of body nor uneasiness of mind If we but attain to this all turmoil of the soul is stilled since the life no longer has to strive after something which it needs and no longer has to seek anything outside of itself by which the welfare of soul and body is arrived at But even on the supposition that pleasure is the first and the inborn good we do not for that reason choose all pleasures but many we renounce when they are more than counterbalanced by their painful results and many pains we prefer to pleasures if there follows from them a pleasure that is greater Contentment we hold to be a good not that we may aim at merely reducing our requirements to a minimum as the Cynics did but that we may seek not to be discontented even when we have not very much knowing that they most enjoy abundance who can do without it and that what is naturally desired is easy to procure while what is a mere idle fancy can be procured only with difficulty Simple dishes afford just as much enjoyment as costly banquets if they appease hunger Therefore when we make pleasure our aim it is not the enjoyments of the gourmand as is often falsely thought but freedom from both pain of body and uneasiness of mind We attain to this life of happiness by sober reason alone which examines the grounds of all choice and all rejection and expels the thoughts by which the soul s rest is most disturbed It is surely better to be unhappy and reasonable than to be happy and unreasonable for it is better that in our actions we should judge correctly than that we should be favoured by luck Meditate on this day and night and let thyself be shaken by nought from thy peace of soul that thou mayest live as a god amongst men for the man who lives amongst such imperishable treasures has nothing in common with mortal men Of all those the first and foremost is reasonableness fronhsis which on this account is still more excellent than philosophy from it spring all the other virtues For they show that one cannot live happily unless he lives wisely and honourably and justly nor can he live wisely and honourably and justly without living happily Therefore although at first sigh t there seems not much to be said for the principle of Epicurus nevertheless by means of the inversion of making the guiding principle to be found in thought proceeding from Reason it passes into Stoicism as even Seneca himself has admitted v supra pp 302 303 and actually the same result is reached as with the Stoics Hence the Epicureans describe their wise man in at least as glowing terms as the Stoics do theirs and in both these systems the wise man is depicted with the same qualities these being negative With the Stoics the Universal is the essential principle not pleasure the self consciousness of the particular as particular but the reality of this self consciousness is equally something pleasant With the Epicureans pleasure is the essential principle but pleasure sought and enjoyed in such a way that it is pure and unalloyed that is to say in accordance with sound judgment and with no greater evil following to destroy it therefore pleasure is regarded in its whole extent that is as being itself a universal In Diogenes Laertius however X 11 7 12 1 the Epicurean delineation of the wise man has a character of greater mildness he shapes his conduct more according to laws already in operation while the Stoic wise man on the other hand does not take these into account at all The Epicurean wise man is less combative than the Stoic because the latter makes his starting point the thought of self dependence which while denying self exercises activity the Epicureans on the other hand proceed from the thought of existence which is not so exacting and seeks not so much this activity directed outwards as rest this however is not won by lethargy but by the highest mental culture Yet although the content of the Epicurean philosophy its aim and result stands thus on as high a level as the Stoic philosophy and is its exact parallel the two are nevertheless in other respects directly opposed to one another but each of these systems is one sided and therefore both of them are dogmatisms inconsistent with themselves by the necessity of the Notion that is they contain the contrary principle within them The Stoics take the content of their thought from Being from the sensuous demanding that thought should be the thought of something existent the Epicureans on the contrary extend their particularity of existence to the atoms which are only things of thought and to pleasure as a universal but in accordance with their respective principles both schools know themselves to be definitely opposed to each other The negative mean to these one sided principles is the Notion which abrogating fixed extremes of determination such as these moves them and sets them free from a mere state of opposition This movement of the Notion the revival of dialectic directed as it is against these one sided principles of abstract thinking and sensation we now see in its negative aspect both in the New Academy and in the Sceptics Even the Stoics as having their principle in thought cultivated dialectic though theirs was pp 254 255 a common logic in which the form of simplicity passes for the Notion while the Notion as such represents the negative element in it and dissolves the determinations which are taken up into that simplicity There is a higher form of the Notion of dialectic reality which not only applies itself to sensuous existence but also to determinate Notions and which brings to consciousness the opposition between thought and existence not expressing the Universal as simple Idea but as a universality in which all comes back into consciousness as an essential moment of existence In Scepticism we now really have an abrogation of the two one sided systems that we have hitherto dealt with but this negative remains negative only and is incapable of passing into an affirmative""");

# In[9]:

println(naive_multi_search(patterns,rawtext)==aho_corasick(patterns,rawtext))

# In[10]:

#0.003519 seconds (939 allocations: 38.125 KiB)
@time naive_multi_search(patterns,rawtext);

# In[11]:

#0.046457 seconds (393.32 k allocations: 10.088 MiB)
#ac is significantly faster than naïve in python but not julia
@time aho_corasick(patterns,rawtext);

# In[ ]:

max_stars_repo_path: aho corasick search.jl

max_stars_repo_name: tattooday/search-and-sort

max_issues_repo_path: aho corasick search.jl

max_issues_repo_name: tattooday/search-and-sort

max_forks_repo_path: aho corasick search.jl

max_forks_repo_name: tattooday/search-and-sort


text:
reset_default_graph(); sess = Session()

@testset "xavier_init" begin
    @test_nowarn a = xavier_init([100,10], Float32)
end

@testset "load_op" begin
    @test_nowarn load_op(ADCME.LIBADCME, "sparse_solver")
    @test_nowarn load_op_and_grad(ADCME.LIBADCME, "sparse_solver")
end

@testset "ae" begin
    n = ae_num([2,20,20,20,3])
    @test n==length(ae_init([2,20,20,20,3]))
end

@testset "register" begin
    forward = x->log(1+exp(x))
    backward = (dy, y, x)->dy*(1-1/(1+y))
    f = register(forward, backward)
    x_ = rand(10)
    x = constant(x_)
    @test run(sess, f(x)) ≈ @. log(1+exp(x_))
    @test_nowarn run(sess,gradients(sum(f(x)), x))

    ADCME.options.newton_raphson.verbose = true
    function forward2(x, θ)
        f = (θ, y)->(y^3+1.0-θ -x, spdiag(3y^2))
        nr = newton_raphson(f, constant(ones(length(x))), θ)
        y = nr.x
        return y
    end

    function backward2(dy, y, x, θ)
        e = 1/3*(θ+x-1)^(-2/3)
        e, e
    end

    f2 = register(forward2, backward2)

    θ = constant(ones(5))
    x = constant(8ones(5))
    y = f2(x, θ)
    @test run(sess, y)≈ones(5)*2

    @test run(sess, gradients(sum(y), θ))≈0.08333333333333333*ones(5)
end

@testset "list_physical_devices" begin
    devices = list_physical_devices()
    @test length(devices)>0
end

ext: jl


text:
using PaddedViews

function CreateData(dimx, dimy, dimz; init=0, mid=1, rng=4)

    midx = (Int(round(dimx/2 - dimx/rng)):Int(round(dimx/2 + dimx/rng)))
    midy = (Int(round(dimy/2 - dimy/rng)):Int(round(dimy/2 + dimy/rng)))
    midz = (Int(round(dimz/2 - dimz/rng)):Int(round(dimz/2 + dimz/rng)))

    data = fill(Float32(init), (dimx, dimy, dimz))
    data[midx,midy, midz] .= mid

    return data
end

function PadData(pd, data)
    x = size(data,1)
    y = size(data,2)
    z = size(data,3)
    padx = 1:(x+2pd)
    pady = 1:(y+2pd)
    padz = 1:z
    datax = (pd+1):(x+pd)
    datay = (pd+1):(y+pd)
    dataz = (1:z)
    return PaddedView(0, data, (padx,pady,padz), (datax, datay, dataz))

end

function PadDataCpu(pd,data)
    x = size(data,1)
    y = size(data,2)
    z = size(data,3)
    padx = 1:(x+2pd)
    pady = 1:(y+2pd)
    padz = 1:(z+2pd)
    datax = (pd+1):(x+pd)
    datay = (pd+1):(y+pd)
    dataz = (pd+1):(z+pd)
    return PaddedView(0, data, (padx,pady,padz), (datax, datay, dataz))
end

nothing


text:
using LinAlgBigFloat
using Test

@time @testset "Utils" begin include("utils_test.jl") end
# @time @testset "Schur BigFloat" begin include("schurbf_test.jl") end
@time @testset "VectorSpaces" begin include("spaces_test.jl") end

0

max_stars_repo_name: KlausC/LinAlgBigFloat

max_issues_repo_name: KlausC/LinAlgBigFloat

max_forks_repo_name: KlausC/LinAlgBigFloat


text:
function fweight(a, b; d=3)
    return length(a)^d + length(b)^d - length(union(a, b))^d
end

function mergeclique!(cliques, cliqueG, i, j; d=3)
    cliques[i] = unique(sort([cliques[i]; cliques[j]]))
    cliques[j] = cliques[end]
    cliques = cliques[1:end-1]
    for neighbor in neighbors(cliqueG, j)
        if neighbor != i
            add_edge!(cliqueG, i, neighbor)
        end
    end
    rem_vertex!(cliqueG, j)
    for neighbor in neighbors(cliqueG, i)
        weight = fweight(cliques[i], cliques[neighbor], d=d)
        set_prop!(cliqueG, i, neighbor, :weight, weight)
    end
    return cliques,cliqueG
end

function clique_merge!(cliques; d=3, QUIET=true)
    cql = length(cliques)
    cliqueG = MetaGraph(cql)
    for i = 1:cql, j = i+1:cql
        if intersect(cliques[i], cliques[j]) != []
            add_edge!(cliqueG, i, j)
            weight = fweight(cliques[i], cliques[j], d=d)
            set_prop!(cliqueG, i, j, :weight, weight)
        end
    end
    merge = true
    while merge == true
        mweight = 0
        medge = 0
        for edge in edges(cliqueG)
            weight = get_prop(cliqueG, edge, :weight)
            if weight > mweight
                mweight = weight
                medge = edge
            end
        end
        if mweight > 0
            cliques,cliqueG = mergeclique!(cliques, cliqueG, src(medge), dst(medge), d=d)
        else
            break
        end
    end
    cliquesize = length.(cliques)
    cql = length(cliquesize)
    if QUIET == false
        uc = sort(unique(cliquesize), rev=true)
        sizes = [sum(cliquesize.== i) for i in uc]
        println("-------------------------------------------")
        println("The size of blocks after merging:\n$uc\n$sizes")
        println("-------------------------------------------")
    end
    return cliques,cql,cliquesize
end


text:
#=
	dirdiff.jl

Command line directory analysis tool.

Features:
- pass arguments to program by passing shell args [see docs.](https://argparsejl.readthedocs.io/en/latest/argparse.html)
- control anaylsis behaviour by passing shell args

TODO:
- rename v51, v54 to generic variables
- setup argparse variable generation routine
- exapnd file format capabilities fast .txt & .bmp
- think about types of analysis (start with name/content/diff analysis, expand later)
- split-up main script into sub parts (keep centralized until further system planning done)
=#

# for now assume given directory paths, in future these will be provided via ArgParse shell args

v51_files = CSV.File("../../dev-ops/sdcards/v51.csv") |> DataFrame |> x -> x[!, :Files]
v54_files = CSV.File("../../dev-ops/sdcards/v54.csv") |> DataFrame |> x -> x[!, :Files]

v51_path = "../../dev-ops/sdcards/CHGCTV51/"
v54_path = "../../dev-ops/sdcards/CHGCTV54/"

# filter out txt files from bmp files

"""
	filterformat(mixed_filenames)

Split `.txt` and `.bmp` files from array of mixed string file names.
"""
function filterformat(mixed_filenames)
	bmp_filenames = []
	txt_filenames = []
	for filename in mixed_filenames
		if split(filename, ".")[2] != "txt"
			push!(bmp_filenames, filename)
		else
			push!(txt_filenames, filename)
		end
	end

	return bmp_filenames, txt_filenames
end

# separated file types (only works for .txt and .bmp for now)

v51_bmp, v51_txt = filterformat(v51_files)
v54_bmp, v54_txt = filterformat(v54_files)

# load images and text files into dictionaries, keeping track of (filename => contents) pairs

# images
v51_images = Dict(v51_bmp .=> load.(v51_path .* v51_bmp))
v54_images = Dict(v54_bmp .=> load.(v54_path .* v54_bmp))

# txt
v51_text = Dict(v51_txt .=> read.(v51_path .* v51_txt, String))
v54_text = Dict(v54_txt .=> read.(v54_path .* v54_txt, String))

"""
	encodeimages(collection::Dict{String, Matrix{ColorTypes.RGB{FixedPointNumbers.N0f8}}})

Encode a dictionary of `filename::String => image::Matrix{ColorTypes.RGB{FixedPointNumbers.N0f8}}` to a dictionary of `id::Int => image::Matrix{ColorTypes.RGB{FixedPointNumbers.N0f8}}` pairs.
Ensure image entries are unique before adding to dictionary.
"""
function encodeimages(collection)
	encoded = Dict{Int, Matrix{ColorTypes.RGB{FixedPointNumbers.N0f8}}}() # initialise empty dictionary
	count = 1
	for pair in collection
		# ensure image not already encoded for (such that allunique(values(encoded)) = true)
		if !in(pair[2], values(encoded))
			push!(encoded, count => pair[2]) # add unique image to encode dictionary
			count += 1 # only increment count if image has been added
		end
	end

	return encoded
end

v51_lenraw = length(v51_images)
v54_lenraw = length(v54_images)

v51_imgenc = encodeimages(v51_images)
v54_imgenc = encodeimages(v54_images)

v51_lenenc = length(v51_imgenc)
v54_lenenc = length(v54_imgenc)

# we now want to sort the files into five categories:
# (consider direction change from v51 to v54)
# - unchanged	(filename & image unchanged)
# - renamed		(image unchanged & new file name (careful with duplicates))
# - reassigned	(filename unchanged & new image)
# - removed		(filename & image removed)
# - added		(new filename & image content)

struct Differences
	unchanged
	reassigned
	renamed
	removed
	added
end

function sortdiffs(collection1, collection2)
	return Differences(
		unchangedpairs(collection1, collection2),
		reassignedpairs(collection1, collection2),
		renamedpairs(collection1, collection2),
		diffpairs(collection1, collection2),	# removed (v51 to v54)
		diffpairs(collection2, collection1)		# added
	)
end

function unchangedpairs(collection1, collection2)
	# unchanged = Dict{String, Matrix{ColorTypes.RGB{FixedPointNumbers.N0f8}}}()
	unchanged = Dict()
	for pair in collection2
		if in(pair, collection1)
			push!(unchanged, pair)
		end
	end

	return unchanged
end

function reassignedpairs(collection1, collection2)
	# reassigned = Dict{String, Matrix{ColorTypes.RGB{FixedPointNumbers.N0f8}}}()
	reassigned = Dict()
	for pair in collection2
		if in(pair[1], keys(collection1)) && !in(pair[2], values(collection1))
			push!(reassigned, pair)
		end
	end

	return reassigned
end

function renamedpairs(collection1, collection2)
	# renamed = Dict{String, Matrix{ColorTypes.RGB{FixedPointNumbers.N0f8}}}()
	renamed = Dict()
	for pair in collection2
		if in(pair[2], values(collection1)) && !in(pair[1], keys(collection1))
			push!(renamed, pair)
		end
	end

	return renamed
end

# works for both removed and added pairs, switch argument order to change functionality
function diffpairs(collection1, collection2)
	# removed = Dict{String, Matrix{ColorTypes.RGB{FixedPointNumbers.N0f8}}}()
	removed = Dict()
	for pair in collection1
		if !in(pair[2], values(collection2)) && !in(pair, collection2) && !in(pair[1], keys(collection2))
			push!(removed, pair)
		end
	end

	return removed
end

diff = sortdiffs(v51_images, v54_images) # diff type of version change info

# test that `diff` is valid (length testing)
function testdiff(diff)
	for pair in diff.unchanged
		@assert !in(pair, diff.reassigned)
		@assert !in(pair, diff.renamed)
		@assert !in(pair, diff.removed)
		@assert !in(pair, diff.added)
	end
	for pair in diff.reassigned
		@assert !in(pair, diff.unchanged)
		@assert !in(pair, diff.renamed)
		@assert !in(pair, diff.removed)
		@assert !in(pair, diff.added) # fails for v51, v54 diff
	end
	for pair in diff.renamed
		@assert !in(pair, diff.unchanged)
		@assert !in(pair, diff.reassigned)
		@assert !in(pair, diff.removed)
		@assert !in(pair, diff.added)
	end
	for pair in diff.removed
		@assert !in(pair, diff.unchanged)
		@assert !in(pair, diff.reassigned)
		@assert !in(pair, diff.renamed)
		@assert !in(pair, diff.added)
	end
	for pair in diff.added
		@assert !in(pair, diff.unchanged)
		@assert !in(pair, diff.reassigned) # fails for v51, v54 diff -- overlap between added & reassigned sets
		@assert !in(pair, diff.renamed)
		@assert !in(pair, diff.removed)
	end
end

testdiff(diff)

# length() dispatch re-write for `bmpdiffs` type
# returns a tuple of integers
function Base.length(x::Differences)
	return length.((x.unchanged, x.reassigned, x.renamed, x.removed, x.added))
end

length(diff)

# """
# - group renamed files
# - point reassigned files to
# """
# function transitioninfo()
#
# end

#=
TESTING
---

Create a test case to validate that sortdiffs(c2, c2) works properly and treats all edge cases.
=#

x1 = Dict(
	"one" => 1,
	"two" => 2,
	"three" => 2,
	"four" => 4,
	"five" => 5,
	"six" => 6,
	"seven" => 7,
	"eight" => 8,
	"nine" => 9
)
x2 = Dict(
	"one" => 1,
	"eleven" => 2,
	"three" => 2,
	"four" => 11,
	"five" => 5,
	"six" => 6,
	"seven" => 7,
	"nine" => 9,
	"ten" => 10
)

test1 = sortdiffs(x1, x2) # looks good!

max_stars_repo_name: zceepst/dirdiff

max_issues_repo_name: zceepst/dirdiff

max_forks_repo_name: zceepst/dirdiff


text:
struct GaussianRBF

end


text:
# ------------------------------------------------------------------
# Licensed under the MIT License. See LICENSE in the project root.
# ------------------------------------------------------------------

"""
    GridTopology(dims)

A data structure for grid topologies with `dims` elements.
"""
struct GridTopology{D} <: Topology
  dims::Dims{D}
end

GridTopology(dims::Vararg{Int,D}) where {D} = GridTopology{D}(dims)

"""
    size(t)

Return the size of the grid topology `t`, i.e. the
number of elements along each dimension of the grid.
"""
Base.size(t::GridTopology) = t.dims

# ---------------------
# HIGH-LEVEL INTERFACE
# ---------------------

nvertices(t::GridTopology) = prod(t.dims .+ 1)

function faces(t::GridTopology{D}, rank) where {D}
  if rank == D
    elements(t)
  elseif rank == D - 1
    facets(t)
  else
    throw(ErrorException("not implemented"))
  end
end

function element(t::GridTopology{D}, ind) where {D}
  l2c(ind) = CartesianIndices(t.dims)[ind].I
  c2l(ind...) = LinearIndices(t.dims .+ 1)[ind...]
  if D == 1
    i1 = ind
    i2 = ind+1
    connect((i1, i2), Segment)
  elseif D == 2
    i, j = l2c(ind)
    i1 = c2l(i  , j  )
    i2 = c2l(i+1, j  )
    i3 = c2l(i+1, j+1)
    i4 = c2l(i  , j+1)
    connect((i1, i2, i3, i4), Quadrangle)
  elseif D == 3
    i, j, k = l2c(ind)
    i1 = c2l(i  , j  , k  )
    i2 = c2l(i+1, j  , k  )
    i3 = c2l(i+1, j+1, k  )
    i4 = c2l(i  , j+1, k  )
    i5 = c2l(i  , j  , k+1)
    i6 = c2l(i+1, j  , k+1)
    i7 = c2l(i+1, j+1, k+1)
    i8 = c2l(i  , j+1, k+1)
    connect((i1, i2, i3, i4, i5, i6, i7, i8), Hexahedron)
  else
    throw(ErrorException("not implemented"))
  end
end

nelements(t::GridTopology) = prod(t.dims)

function facet(t::GridTopology{D}, ind) where {D}
  l2c(ind) = CartesianIndices(t.dims)[ind].I
  c2l(ind...) = LinearIndices(t.dims .+ 1)[ind...]
  if D == 1
    ind
  elseif D == 2
    N = 2prod(t.dims)
    if ind ≤ N
      if isodd(ind)
        i, j = l2c((ind + 1) ÷ 2)
        i1 = c2l(i,   j)
        i2 = c2l(i+1, j)
      else
        i, j = l2c(ind ÷ 2)
        i1 = c2l(i,   j)
        i2 = c2l(i, j+1)
      end
    else
      if isodd(ind)
        i = t.dims[1] + 1
        j = ((ind - N) + 1) ÷ 2
        i1 = c2l(i,   j)
        i2 = c2l(i, j+1)
      else
        i = (ind - N) ÷ 2
        j = t.dims[2] + 1
        i1 = c2l(i,   j)
        i2 = c2l(i+1, j)
      end
    end
    connect((i1, i2), Segment)
  elseif D == 3
    throw(ErrorException("not implemented"))
  else
    throw(ErrorException("not implemented"))
  end
end

function nfacets(t::GridTopology{D}) where {D}
  if D == 1
    t.dims[1] + 1
  elseif D == 2
    2prod(t.dims) +
    t.dims[1] +
    t.dims[2]
  elseif D == 3
    3prod(t.dims) +
    prod(t.dims[[1,2]]) +
    prod(t.dims[[1,3]]) +
    prod(t.dims[[2,3]])
  else
    throw(ErrorException("not implemented"))
  end
end


text:
function simulate_gtilde(; NC, NT, etaC, etaT, loc, scale, df, skew)
  K = length(loc)

  @assert K == length(etaC) == length(etaT)
  @assert K == length(scale) == length(df) == length(skew)

  mmC = MixtureModel(SkewT.(loc, scale, df, skew), etaC)
  mmT = MixtureModel(SkewT.(loc, scale, df, skew), etaT)

  yC = rand(mmC, NC)
  yT = rand(mmT, NT)

  return (yC=yC, yT=yT, etaC=etaC, etaT=etaT, loc=loc, scale=scale, df=df,
          skew=skew, mmC=mmC, mmT=mmT)
end

function simulate_ftilde(; NC, NT, etaC, etaT, loc, scale, df, skew, gammaC, gammaT)
  QC = sum(gammaC .> rand(NC))
  QT = sum(gammaT .> rand(NT))

  NC_finite = NC - QC
  NT_finite = NT - QT

  pzero = (gammaC=gammaC, gammaT=gammaT, QC=QC, QT=QT, NC=NC, NT=NT)

  gtilde = simulate_gtilde(NC=NC_finite, NT=NT_finite, etaC=etaC, etaT=etaT, loc=loc,
                           scale=scale, df=df, skew=skew)

  return merge(pzero, gtilde)
end


text:
using DimensionalData, Test
using DimensionalData.LookupArrays, DimensionalData.Dimensions

A = zeros(X(4.0:7.0), Y(10.0:12.0))
di = DimIndices(A)

ci = CartesianIndices(A)
@test val.(collect(di)) == Tuple.(collect(ci))

@testset "DimIndices" begin
    @test di[4, 3] == (X(4), Y(3))
    @test di[X(1)] == [(X(1), Y(1),), (X(1), Y(2),), (X(1), Y(3),)]
    @test map(ds -> A[ds...] + 2, di) == fill(2.0, 4, 3)
    @test map(ds -> A[ds...], di[X(At(7.0))]) == [0.0, 0.0, 0.0]
    @test_throws ArgumentError DimIndices(zeros(2, 2))
    @test_throws ArgumentError DimIndices(nothing)
    @test size(di) == (4, 3)
    # Vector
    @test collect(DimIndices(X(1.0:2.0))) == [(X(1),), (X(2),)]
end

@testset "DimPoints" begin
    dp = DimPoints(A)
    @test dp[4, 3] == (7.0, 12.0)
    @test dp[X(1)] == [(4.0, 10.0), (4.0, 11.0), (4.0, 12.0)]
    @test size(dp) == (4, 3)
    @test_throws ArgumentError DimPoints(zeros(2, 2))
    @test_throws ArgumentError DimPoints(nothing)
    # Vector
    @test collect(DimPoints(X(1.0:2.0))) == [(1.0,), (2.0,)]
end

@testset "DimKeys" begin
    dk = DimKeys(A)
    @test size(dk) == (4, 3)
    @test dk[4, 3] == (X(At(7.0; atol=eps(Float64))), Y(At(12.0, atol=eps(Float64))))
    @test dk[X(1)] ==  dk[X(At(4.0))] ==
        [(X(At(4.0; atol=eps(Float64))), Y(At(10.0; atol=eps(Float64))),),
         (X(At(4.0; atol=eps(Float64))), Y(At(11.0; atol=eps(Float64))),),
         (X(At(4.0; atol=eps(Float64))), Y(At(12.0; atol=eps(Float64))),)]
    @test broadcast(ds -> A[ds...] + 2, dk) == fill(2.0, 4, 3)
    @test broadcast(ds -> A[ds...], dk[X(At(7.0))]) == [0.0 for i in 1:3]
    @test_throws ArgumentError DimKeys(zeros(2, 2))
    @test_throws ArgumentError DimKeys(nothing)

    @test collect(DimKeys(X(1.0:2.0))) ==
        [(X(At(1.0; atol=eps(Float64))),), (X(At(2.0; atol=eps(Float64))),)]

    @testset "atol" begin
        dka = DimKeys(A; atol=0.3)
        # Mess up the lookups a little...
        B = zeros(X(4.25:1:7.27), Y(9.95:1:12.27))
        @test dka[4, 3] == (X(At(7.0; atol=0.3)), Y(At(12.0, atol=0.3)))
        @test broadcast(ds -> B[ds...] + 2, dka) == fill(2.0, 4, 3)
        @test broadcast(ds -> B[ds...], dka[X(At(7.0))]) == [0.0 for i in 1:3]
        @test_throws ArgumentError broadcast(ds -> B[ds...] + 2, dk) == fill(2.0, 4, 3)
        @test_throws ArgumentError DimKeys(zeros(2, 2))
        @test_throws ArgumentError DimKeys(nothing)
    end

    @testset "mixed atol" begin
        dka2 = DimKeys(A; atol=(0.1, 0.2))
        # Mess up the lookups again
        C = zeros(X(4.05:7.05), Y(10.15:12.15))
        @test dka2[4, 3] == (X(At(7.0; atol=0.1)), Y(At(12.0, atol=0.2)))
        @test collect(dka2[X(1)]) == [(X(At(4.0; atol=0.1)), Y(At(10.0; atol=0.2)),),
                                     (X(At(4.0; atol=0.1)), Y(At(11.0; atol=0.2)),),
                                     (X(At(4.0; atol=0.1)), Y(At(12.0; atol=0.2)),)]
        @test broadcast(ds -> C[ds...] + 2, dka2) == fill(2.0, 4, 3)
        @test broadcast(ds -> C[ds...], dka2[X(At(7.0))]) == [0.0 for i in 1:3]
        # without atol it errors
        @test_throws ArgumentError broadcast(ds -> C[ds...] + 2, dk) == fill(2.0, 4, 3)
        # no dims errors
        @test_throws ArgumentError DimKeys(zeros(2, 2))
        @test_throws ArgumentError DimKeys(nothing)
        # Only Y can handle errors > 0.1
        D = zeros(X(4.15:7.15), Y(10.15:12.15))
        @test_throws ArgumentError broadcast(ds -> D[ds...] + 2, dka2) == fill(2.0, 4, 3)
    end
end


text:
using DataStructures

function solve()
    m = 998244353
    n, k = [parse(Int, x) for x in split(readline())]
    segments = zeros(Int, k, 2)
    for s=1:k
        segments[s, 1], segments[s, 2] = [parse(Int, x) for x in split(readline())]
    end
    ft = FenwickTree{Int}(n)
    inc!(ft, 1, 1)
    for i=2:n
        ways = 0
        for s=1:k
            lindex = i - segments[s, 2] - 1
            rindex = i - segments[s, 1]
            l = lindex > 0 ? prefixsum(ft, lindex) % m : 0
            r = rindex > 0 ? prefixsum(ft, rindex) % m : 0
            ways += ((r - l) + m) % m
            ways %= m
        end
        inc!(ft, i, ways)
    end
    (prefixsum(ft, n) - prefixsum(ft, n-1) + m) % m
end

println(solve())

max_stars_repo_name: aishikawa/atcoder-julia

max_issues_repo_name: aishikawa/atcoder-julia

max_forks_repo_name: aishikawa/atcoder-julia