def __init__(self, _project): self.project = _project self.projects = OrderedSet.OrderedSet() self.projectsNonRequired = OrderedSet.OrderedSet() self.projectsIncludedInSolution = OrderedSet.OrderedSet() self.useBefore = [] self.isTopLevel = False # logger self.__logger = logging.getLogger("CSnake")
def __init__(self): ''' pre: None post: An initial empty OrderedSet (the collection of CounterEvents later) ''' #Construct the Empty CounterSim Object #Initialize the virtual time self.event = OrderedSet() self.t = 0.0
def __init__(self, name=None): """Initialize a new System object. This must be run before the system can be used. Args: name (str): The name of the system >>> print __init__(name='sysname') """ if name: self._name = name else: self._name = "Untitled" self._v1x = 0.0 self._v2x = 0.0 self._v3x = 0.0 self._v1y = 0.0 self._v2y = 0.0 self._v3y = 0.0 self._v1z = 0.0 self._v2z = 0.0 self._v3z = 0.0 self._nbFunc = 0 self._combinationRule = 0 self._genpairs = True self._ljCorrection = 0 self._coulombCorrection = 0 self._molecules = OrderedDict.OrderedDict() self._atomtypes = HashMap.HashMap() self._forces = OrderedSet.OrderedSet() self._boxVector = []
def getPrimesBelowAsSet(somevalue): primes = OrderedSet.OrderedSet([2, 3]) tempPrimes = [2, 3] start = 4 # range of numbers searching for primes for num in range(start, somevalue): #intialize not-a-prime as false nap = 0 # cycle through list of known primes for prime in tempPrimes: # check if a previous prime divides evenly # into the current number -- if so the number # we are checking (num) is not a prime if (num % prime) == 0: nap = 1 break # if prime squared is bigger than the number # than we don't need to check any more if prime * prime > num: break # did we determine it's not a prime # if not, then we found a prime if nap != 1: # add prime to list of known primes primes.add(num) tempPrimes.append(num) return primes
def SetSuperSubCategory(self, super, sub): """ Makes super a supercategory of sub. This information is used to be able to disable all Tests with a single click (since Tests will be a supercategory of each Test project). """ if not self.GetSubCategoriesOf().has_key(super): self.GetSubCategoriesOf()[super] = OrderedSet.OrderedSet() self.GetSubCategoriesOf()[super].add(sub) self.__NotifyListeners(ChangeEvent(self))
def searchForMultipleWords(keyword_list, frontFileName): endFileName = "_output.txt" full_output_path = "".join((frontFileName, endFileName)) titleList = [] descList = [] catList = [] seen_titles = OrderedSet() seen_desc = OrderedSet() seen_cat = [] for keyword in keyword_list: titleList_temp, descList_temp, catList_temp = checkIfStringExistsInCSV( keyword) titleList += titleList_temp descList += descList_temp catList += catList_temp unique_categories_list = OrderedSet(catList) for title1, description1, category1 in zip(titleList, descList, catList): if title1 not in seen_titles and description1 not in seen_desc: seen_titles.add(title1) seen_desc.add(description1) seen_cat.append(category1) with open(full_output_path, "at", encoding="utf-8") as text_file: for unique_category in unique_categories_list: text_file.write("\n%s:\n\n" % unique_category) for title, desc, cat in zip(seen_titles, seen_desc, seen_cat): if cat == unique_category: text_file.write("\n\nTitle: %s\n\nDescription: %s\n\n" % (title, desc)) else: pass
def GetProjects(self, _recursive=False, _onlyRequiredProjects=False, _includeSelf=False, _onlyPublicDependencies=False, _onlyNonRequiredProjects=False, _filter=True, _skipList=[], _stack=[], _cache=None): """ Returns list of all projects associated with this project. _recursive -- If true, returns not only child projects but all projects in the tree below this project. _onlyRequiredProjects -- If true, only projects that this project requires are returned. _includeSelf _onlyPublicDependencies _onlyNonRequiredProjects _filter -- use the filter or not _stack -- do not touch, only used internally in recursive loops _cache -- cache for intermediate results, can be provided as external dictionary to be shared between calls """ if _cache is None: _cache = dict() _recursive = bool(_recursive) _onlyRequiredProjects = bool(_onlyRequiredProjects) _includeSelf = bool(_includeSelf) _onlyPublicDependencies = bool(_onlyPublicDependencies) _onlyNonRequiredProjects = bool(_onlyNonRequiredProjects) _filter = bool(_filter) if self.project in _stack: if _onlyRequiredProjects: namelist = [] foundStart = False for project in _stack: if project == self.project: foundStart = True if foundStart: namelist.append(project.name) namelist.append(self.project.name) raise DependencyError("Cyclic dependency: %s" % namelist) return OrderedSet.OrderedSet() _stack = _stack + [self.project] if self.project in _cache: if _includeSelf: return _cache[self.project] + [self.project] else: return _cache[self.project] directDependencies = OrderedSet.OrderedSet() toSubtract = OrderedSet.OrderedSet() toAdd = OrderedSet.OrderedSet() if _onlyNonRequiredProjects: toAdd.update(self.projectsNonRequired) else: toAdd.update(self.projects) if _filter: toAddFiltered = OrderedSet.OrderedSet() toAddFiltered.update([ project for project in toAdd if not (project.MatchesFilter() and project in self.projectsNonRequired) ]) toAdd = toAddFiltered if _onlyRequiredProjects: toSubtract.update(self.projectsNonRequired) directDependencies.update(toAdd - toSubtract) if _recursive: _cache[self.project] = OrderedSet.OrderedSet() for project in directDependencies: _cache[self.project].update( project.dependenciesManager.GetProjects( _recursive=_recursive, _onlyRequiredProjects=_onlyRequiredProjects, _onlyPublicDependencies=_onlyPublicDependencies, _includeSelf=True, _onlyNonRequiredProjects=_onlyNonRequiredProjects, _filter=_filter, _skipList=_skipList, _stack=_stack, _cache=_cache)) else: _cache[self.project] = directDependencies if _includeSelf: return _cache[self.project] + [self.project] else: return _cache[self.project]
class CounterSim(object): ''' CounterSim is the real driver for the DES simulation. The info 1. is an OrderedSet Whose Elements are CounterEvents 2. and also a Virtual Time Keeper initially at 0.0 ''' #Constructor def __init__(self): ''' pre: None post: An initial empty OrderedSet (the collection of CounterEvents later) ''' #Construct the Empty CounterSim Object #Initialize the virtual time self.event = OrderedSet() self.t = 0.0 #Current time method def now(self): ''' pre:None post:return the current virtual time ''' return self.t #Insertion Method def insert(self,x): ''' pre: X is a CounterEvent Ojbect post: insert the CounterEvent to the event Collection(OrderedSet) exception:TypeErro if x is not CounterEvent Object ''' #raise typeError if x not the right Type if not isinstance(x,CounterEvent): raise TypeError #insert if right type self.event.insert(x) #Setup Method def setup (self, t=0): ''' pre: t is a numeric Type post: 1. construct COunterEvent with time t ( 0.0 if t not inptued) 2. The constructed CounterEvent is inserted to the event collection (OrderedSet) Exception:TypeError if t is not a numeric type ''' #raise typeError if x not the right Type if not (isinstance(t,int) or isinstance(t,float)): raise TypeError #Construct and insert the CounterEvent Object with t self.insert(CounterEvent(t)) # the simulation Engine method def doAllEvents(self): ''' pre:None post:THe SImulator has porperly run ''' #The main loop for carrying out DES #going through the Events collection #applying right method to it while len(self.event) > 0: event = self.event.removeFirst() self.t = event.time() event.execute(self) #the getset method to get the ordered set (events collection in the simulator) def getset(self): ''' pre:None post: the orderedSet (events collection) is returned ''' return self.event
def Generate(self, _targetProject, _generatedList=None): """ Generates the CMakeLists.txt for _targetProject (a csnBuild.Project) in the build folder. _generatedList -- List of projects for which Generate was already called (internal to the function). """ _targetProject.dependenciesManager.isTopLevel = _generatedList is None if _targetProject.dependenciesManager.isTopLevel: _targetProject.installManager.ResolvePathsOfFilesToInstall() _generatedList = [] # Trying to Generate a project twice indicates a logical error in the code assert not _targetProject in _generatedList, "\n\nError: Trying to Generate a project twice. Target project name = %s" % ( _targetProject.name) for generatedProject in _generatedList: if generatedProject.name == _targetProject.name: raise NameError, "Each project must have a unique name. Conflicting projects are %s (in folder %s) and %s (in folder %s)\n" % ( _targetProject.name, _targetProject.GetSourceRootFolder(), generatedProject.name, generatedProject.GetSourceRootFolder()) _generatedList.append(_targetProject) # check for backward slashes if csnUtility.HasBackSlash(_targetProject.context.GetBuildFolder()): raise SyntaxError, "Error, backslash found in build folder %s" % _targetProject.context.GetBuildFolder( ) # check trying to build a third party library if _targetProject.type == "third party": warnings.warn( "CSnake warning: you are trying to generate CMake scripts for a third party module (nothing generated)\n" ) return # create build folder os.path.exists(_targetProject.GetBuildFolder()) or os.makedirs( _targetProject.GetBuildFolder()) # create Win32Header if _targetProject.type != "executable" and _targetProject.GetCompileManager( ).generateWin32Header: _targetProject.GetCompileManager().GenerateWin32Header() # add search path to the generated win32 header if not _targetProject.GetBuildFolder( ) in _targetProject.GetCompileManager().public.includeFolders: _targetProject.GetCompileManager( ).public.includeFolders.append(_targetProject.GetBuildFolder()) _targetProject.RunCustomCommands() # Find projects that must be generated. A separate list is used to ease debugging. projectsToGenerate = OrderedSet.OrderedSet() requiredProjects = _targetProject.GetProjects(_recursive=1, _onlyRequiredProjects=1) for projectToGenerate in requiredProjects: # determine if we must Generate the project. If a required project will generate it, # then leave it to the required project. This will prevent multiple generation of the same project. # If a non-required project will generate it, then still generate the project # (the non-required project may depend on target project to generate project, creating a race condition). generateProject = not projectToGenerate in _generatedList and projectToGenerate.type in ( "dll", "executable", "library") if generateProject: for requiredProject in _targetProject.GetProjects( _recursive=0, _onlyRequiredProjects=1): if requiredProject.dependenciesManager.DependsOn( projectToGenerate): generateProject = 0 if generateProject: projectsToGenerate.add(projectToGenerate) # add non-required projects that have not yet been generated to projectsToGenerate for project in _targetProject.GetProjects( _onlyNonRequiredProjects=True): if not project in _generatedList: projectsToGenerate.add(project) # generate projects, and add a line with ADD_SUBDIRECTORY generatedProjects = OrderedSet.OrderedSet() for project in projectsToGenerate: # check again if a previous iteration of this loop didn't add project to the generated list if not project in _generatedList: self.Generate(project, _generatedList) generatedProjects.append(project) # write cmake files writer = csnCMake.Writer(_targetProject) writer.GenerateConfigFile(_public=0) writer.GenerateConfigFile(_public=1) writer.GenerateUseFile() writer.GenerateCMakeLists(generatedProjects, requiredProjects, _writeInstallCommands=_targetProject. dependenciesManager.isTopLevel)
wubi_prefix = wubi.wubi_prefix from OrderedSet import * import regex as re g_trans_map = {} g_reverse_map = {} char_re = re.compile("[a-z]") for comp in wubi.g_quail_map: if char_re.match(comp): chars = [char for char in wubi.g_quail_map[comp] if len(char) == 1] for char in chars: if char not in g_reverse_map: g_reverse_map[char] = OrderedSet() g_reverse_map[char].add('"' + (comp + 'zz')[0:2] + '"') for i in range(1, len(comp)): prefix = comp[0:i] if prefix not in g_trans_map: g_trans_map[prefix] = OrderedSet() g_trans_map[prefix].add(comp[i]) trans_file = open(wubi_prefix + "_trans.py", "w") reverse_file = open(wubi_prefix + "_reverse.py", "w") #trans_file = sys.stdout
import wubi86 from OrderedSet import * import sys g_trans_map = {} for comp in wubi86.g_quail_map: for i in range(1, len(comp)): prefix = comp[0:i] if prefix not in g_trans_map: g_trans_map[prefix] = OrderedSet() g_trans_map[prefix].add(comp[i]) trans_file = open("wubi86_trans.py", "w") #trans_file = sys.stdout trans_file.write("g_trans_map = {\n") keys = list(g_trans_map.keys()) keys.sort() for prefix in keys: trans = list(g_trans_map[prefix]) trans.sort() trans = ''.join(trans) trans_file.write('%s : %s,\n' % (repr(prefix), repr(trans))) trans_file.write("}\n")
def getPregeneratedPrimesBelow1MAsSet(): text = open("./1000000primes.txt", 'r').read() nums = [int(n) for n in text.split()] toReturn = OrderedSet.OrderedSet(nums) return toReturn
prefix_url = "https://api.adcenter.excitedigitalmedia.com/v2/" dlux/excitedigitalmedia/g/ suffix_url = "?apiKey=4d28cf3ed125ed03&pageSize=1000" dlux/excitedigitalmedia/g/ page_param = "¤tPage=" full_url = prefix_url + stage + suffix_url dlux/excitedigitalmedia/g/ resp = urllib.urlopen(full_url) dlux/excitedigitalmedia/g/ json_resp = json.load(resp) dlux/excitedigitalmedia/g/ data = [] keys = OrderedSet() dlux/excitedigitalmedia/g/ for row in json_resp.itervalues(): dlux/excitedigitalmedia/g/ total_pages = int(row['totalPages']) dlux/excitedigitalmedia/g/ total_items = int(row['totalItems']) dlux/excitedigitalmedia/g/ if total_items==0: dlux/excitedigitalmedia/g/ continue for x in range(1,total_pages + 1): dlux/excitedigitalmedia/g/ paged_url = full_url + page_param + str(x) dlux/excitedigitalmedia/g/ paged_resp = json.load(urllib.urlopen(paged_url),object_pairs_hook=collections.OrderedDict())
import eulerutils as eu import OrderedSet import time def currentMillis(): return int(round(time.time() * 1000)) startTime = currentMillis() primes = [] primes = eu.getPrimesBelowAsSet(1000000) primesList = list(primes) primeSums = OrderedSet.OrderedSet([]) print "Got Primes. Time: %d" % (currentMillis() - startTime) #print primesList #print len(primesList) slidingWindowSum = 0 smallestPrimesSum = 2 #start at 2, window size = 1, smallest prime numberOfPrimesInSum = 1 largestWindowSize = 1 largestSum = 1 #loop through length of primes. listLen = len(primesList) for windowsize in xrange(1, listLen): #for each window size, we loop through to the length, minus the window size.