Esempio n. 1
0
def def_first():
    """Game for matching word to definiton"""
    content = helpers.init()
    print("\nYou can exit at anytime by entering 'exit'.\n")
    random.shuffle(content)
    count = len(content)
    correct = 0
    incorrect = 0
    for word in content:
        print("\n{}. {}".format(operator.indexOf(content, word) + 1, word["definition"]))
        res = input("\nWhat word does this definition belong to?\n\t=>").lower()

        if res == word["key"].lower():
            count -= 1
            correct += 1
            if count > 0:
                print("\nGood Job! next word!")
        elif res == "exit":
            return
        else:
            incorrect += 1
            count -= 1
            if count > 1:
                print("\nIncorrect. Next word.")

    print("\nYou got {} correct and {} incorrect".format(correct, incorrect))
    helpers.callback(def_first)
Esempio n. 2
0
    def _on_exit(self, process, exit_status, term_signal):
        # exit callback called when a process exit

        # notify other that the process exited
        self._publish("proc.%s.exit" % process.name, name=process.name,
                pid=process.id, exit_status=exit_status,
                term_signal=term_signal)

        with self._lock:
            state = self.get_process_state(process.name)

            if process in self._stopped:
                # this exit was expected. remove it from the garbage
                # collection.
                del self._stopped[operator.indexOf(self._stopped,
                    process)]
            else:
                # unexpected exit, remove the process from the list of
                # running processes.

                if process.id in self.running:
                    self.running.pop(process.id)

                if state is not None:
                    state.remove(process)

            # this remplate has been removed
            if not state:
                return

            if not state.stopped:
                # manage the template, eventually restart a new one.
                if self._check_flapping(state):
                    self._manage_processes(state)
 def clusterize(self,noClusters,noNouranksToKeep,**kwargs):
     """
     """
     storage = getUtility(INounPhraseStorage)
     
     docids = storage.rankedNouns.keys()
     docnouns = []
     allNouns = set()
     vectors = []
     
     for key in docids:
         importantNouns = storage.getNounTerms(
             key,
             noNouranksToKeep)
         docnouns.append(importantNouns)
         allNouns = allNouns.union(importantNouns)
     
     for nouns in docnouns:
         vector = [(noun in nouns and 1 or 0) for noun in allNouns]
         vectors.append(numpy.array(vector))
     
     clusterer = KMeansClusterer(noClusters,pearson,**kwargs)
     clusters = clusterer.cluster(vectors,True)
     
     result = {}
     for i in range(noClusters):
         result[i] = []
     for docid in docids:
         index = indexOf(docids,docid)
         result[clusters[index]] = result[clusters[index]] + [docid]
     return result
Esempio n. 4
0
    def __delitem__(self, id_):
        """Delete a Holding by id.

        :raises ValueError:
        """
        index = indexOf((x['id'] for x in self), str(id_))
        del self._iterable[index]
Esempio n. 5
0
def wzc_arith(opstr):
    """

    calculator application for operators: + - * / % **
    """

    import operator

    ops = ('+', '-', '*', '/', '%', '**')
    expr = str(opstr).split()

    op = expr[1]
    op_index = operator.indexOf(ops, op)

    num1 = float(expr[0])
    num2 = float(expr[2])

    if op_index == 0:
        return num1 + num2
    elif op_index == 1:
        return num1 - num2
    elif op_index == 2:
        return num1 * num2
    elif op_index == 3:
        return num1 / num2
    elif op_index == 4:
        return num1 % num2
    elif op_index == 5:
        return num1 ** num2
Esempio n. 6
0
 def __volUp(self):
     self.__mute = False
     index = indexOf(self.__volumeSteps, self.__volume)+1
     if index < len(self.__volumeSteps):
         self.__volume = self.__volumeSteps[index]
         return self.__createVolumeCommand()
     return []
Esempio n. 7
0
def def_first():
	"""Game for matching word to definiton"""
	content = helpers.init()
	print('\nYou can exit at anytime by entering \'menu\'.\n') 
	random.shuffle(content)
	count = len(content)
	correct = 0
	incorrect = 0
	for word in content:
		print('\n{}. {}'.format(operator.indexOf(content, word) + 1, word['definition']))
		res = input('\nWhat word does this definition belong to?\n\t=>').lower()

		if res == word['key'].lower():
			count -= 1
			correct += 1
			if count > 0:
				print('\nGood Job! next word!')		
		elif res == 'menu':
			main.menu()
		else:
			incorrect += 1
			count -= 1
			if count > 1:
				print('\nIncorrect. Next word.')
				
	print('\nYou got {} correct and {} incorrect'.format(correct, incorrect))
	helpers.callback(def_first)
Esempio n. 8
0
 def __volDown(self):
     self.__mute = False
     index = indexOf(self.__volumeSteps, self.__volume)-1
     if index >= 0:
         self.__volume = self.__volumeSteps[index]
         return self.__createVolumeCommand()
     return []
def parse_file_byte(src_folder, tt, all_keywords=None, all_extension=None):
    """TODO: Docstring for parse_file_byte.

    :returns: TODO

    """
    X, y = [], []
    all_files = [x for x in listdir(src_folder) if x[0] != '.']
    if all_extension is None:
        temp = [splitext(x)[1] for x in all_files if x[0] != '.']
        all_extension = list(set(temp))
    all_extension = sorted(all_extension)

    for one in all_files:
        index = operator.indexOf(all_extension, splitext(one)[1])
        with open(join(src_folder, one), 'r') as fh:
            feature = [ord(i) for i in fh.read()[:900]]
        X.append(feature)
        y.append([int(i == index) for i in range(len(all_extension))])

    print 'The number of feature: %d' % (900)
    print 'The number of label: %d' % (len(all_extension))

    with open('all_extension.txt', 'w') as tmp:
        tmp.write(str(all_extension))

    sio.savemat(tt+'_sample', {
            'input': X, 'label': y,
            })
    with open(join(PARAM_FOLDER, 'extension'), 'w') as tmp:
        tmp.write(json.dumps(all_extension))
    with open(join(PARAM_FOLDER, 'keyword'), 'w') as tmp:
        tmp.write(json.dumps(all_keywords))

    return numpy.array(X), numpy.array(y)
Esempio n. 10
0
def parse_multi_file(output_file, exclude_file):
    """TODO: Docstring for parse_multi_file.
    :returns: TODO

    """
    all_keywords  = {}
    all_files     = [x for x in os.listdir('./train') if x[0] != '.']
    all_keywords  = fill_feature_dict(all_files, './train/', exclude_file)
    temp          = [os.path.splitext(x)[1] for x in all_files if x[0] != '.']
    all_extension = list(set(temp))

    for one in all_files:
        single_list = [one]
        index       = operator.indexOf(all_extension, os.path.splitext(one)[1]) + 1
        keywords    = fill_feature_dict(single_list, './train/')
        result      = keyword_to_feature(keywords, all_keywords, index)

        output_file.write(result + os.linesep)

    with open('all_extension.txt', 'w') as extension_file:
        extension_file.write(json.dumps(all_extension))

    with open('all_keywords.txt', 'w') as keyword_file:
        keyword_file.write(json.dumps(all_keywords))

    with open('oct_extension.txt', 'w') as oct_extension:
        for extension in all_extension:
            oct_extension.write(extension + os.linesep)
Esempio n. 11
0
 def AddData(self, words, labels):
     self.context.append([])
     self.spelling.append([])
     self.both.append([])
     for word in words:
         self.both[len(self.spelling)-1].append(word)
         if word[0:3] == 'in=':
             self.spelling[len(self.spelling)-1].append(word)
         else:
             self.context[len(self.spelling)-1].append(word)
             
     if sum(labels) == 1:
         self.labels.append(indexOf(labels, 1))
         self.seedlabels.append(indexOf(labels, 1)+1)
     else:
         self.labels.append(-1)
         self.seedlabels.append(-1)
Esempio n. 12
0
    def encode(self,message,key = 0):
        if (key != 0):
            self.key = key

        nm = ""
        for letter in message:
            nm += self.dict[(operator.indexOf(self.dict,letter) + self.key) % 27]
        return nm
Esempio n. 13
0
def score_name(s):
    """Score a word by giving each letter its
    value in the alphabet (a->1, b->2, ...)
    and summing the results"""
    score = 0
    alpha = " abcdefghijklmnopqrstuvwxyz"
    for i in s.lower():
        score += operator.indexOf(alpha, i)
    return score
Esempio n. 14
0
    def decode(self,message, key = 0):
        if (key != 0):
            self.key = key

        om = ""
        for letter in message:
            om += self.dict[(operator.indexOf(self.dict,letter) - self.key) %27]

        return om
Esempio n. 15
0
    def spawn_link(cls, func, *args, **kwargs):
        curr = core.getcurrent()
        if not hasattr(curr, 'mailbox'):
            curr = cls.wrap(curr)

        if operator.indexOf(self.links, curr.ref) < 0:
            self.links.append(curr.ref)

        return cls.spawn(func, *args, **kwargs)
Esempio n. 16
0
	def _get_arg(self, args, argname) :
		if not argname in args :
			print 'given arguments do not contain files argument {0}. Please supply it'.format(argname)
			return -1
		ix = operator.indexOf(args, argname)
		if args[ix+1] in self.arglist :
			print 'invalid argument value given for argument {0}'.format(argname)
			return -1
		return args[ix+1]
Esempio n. 17
0
    def update(self):
        self.queue_draw()
        
        cellsToPop=[]
        for cell in self.cells:
            cell.update(self.currentState)
            if cell.type=="NormalCell":
                if cell.posX+cell.width<0 or (cell.status=="Dead" and len(cell.dyingParticles)<=0):
                    cellsToPop.append(cell)
        for cell in cellsToPop:
            self.cells.pop(indexOf(self.cells,cell))
            if cell==self.virus[0].targetCell:
                self.virus[0].targetCell=None

        if self.currentState=="Running":
            self.ticksToNextCell-=1
            if self.ticksToNextCell<=0:
                self.ticksToNextCell=random.randint(self.minTimeToNextCell,self.maxTimeToNextCell)
                newCell=Cell(WINDOW_SIZE,
                    random.randint(0,TRAINING_ZONE_LIMIT-CELL_HEIGHT))
                newCell.velX=-random.random()*2
                newCell.type="NormalCell"
                self.cells.append(newCell)

            #update virus
            for virus in self.virus:
                if not virus.isDead:
                    virus.update(self.currentState)
                    if len(self.cells)>0 and virus.targetCell==None:
                        virus.targetCell=self.cells[len(self.cells)-1]
                        #This is a temprorary decision function
                        #Actual classification should do this
                        self.classify_cell(widget=None)
                        
                        

                if virus.is_colliding_with(virus.targetCell):
                    if not virus.targetCell.status:
                        if virus.status=="Attacking":
                            virus.targetCell.status="Dying"
                        if virus.status=="Eating":
                            virus.targetCell.status="BeingEaten"

                    if virus.targetCell.status=="Dead":
                        virus.targetCell=None

            for (cell,type) in self.trainingSet:
                for i in xrange(len(self.classificationList)):
                    if type==self.classificationList[i]:
                        rightLimit=self.divisionPoints[i]
                        if i==0:
                            leftLimit=0
                        else:
                            leftLimit=self.divisionPoints[i-1]
                        break
                            
                cell.update(self.currentState,[leftLimit,rightLimit-cell.width,TRAINING_ZONE_LIMIT,WINDOW_SIZE-cell.height])
Esempio n. 18
0
File: views.py Progetto: hupeng/Blog
def escape_to_url(urlvalue):
    escapeCode_value = {'+':'%2B',' ':'%20','/':'%2F','?':'%3F','%':'%25','#':'%23','&':'%26','=':'%3D'}
    res = 0
    for k in escapeCode_value.iterkeys():
        try:
            res = operator.indexOf(urlvalue,k)
            urlvalue = urlvalue.replace(k,escapeCode_value.get)
        except:
            pass
    return urlvalue
Esempio n. 19
0
    def taskwakeup(self, task):
        if task is None:
            return

        try:
            del self._squeue[operator.indexOf(self._squeue, task)]
        except ValueError:
            pass

        self.append(task)
Esempio n. 20
0
def simplify_digits(i, j):
    """Do a "stupid" digits simplification in the
    i/j fraction"""
    ni, nj = i, j
    for k, e in enumerate(str(i)):
        if e in str(j):
            ni = int("".join([n for m, n in enumerate(str(i)) if m != k]))
            nj = int("".join([n for m, n in enumerate(str(j)) if m != operator.indexOf(str(j), e)]))
    if 0 in (ni, nj):
        return i, j
    return ni, nj
Esempio n. 21
0
    def encode(self,message,a = 0, k = 0):
        if not (a == 0):
            self.a = a
        if not (k == 0):
            self.k = k

        nm = ""
        for letter in message:
            nm += self.dict[(operator.indexOf(self.dict,letter)*self.a + self.k) % 27]

        return nm
Esempio n. 22
0
    def test_indexOf(self):
        from operator import indexOf

        self.assertEqual(indexOf([1, 2, 2, 3, 2, 5], 1), 0)
        self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 2), 1)
        self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 3), 3)
        self.assertEqual(indexOf((1, 2, 2, 3, 2, 5), 5), 5)
        self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 0)
        self.assertRaises(ValueError, indexOf, (1, 2, 2, 3, 2, 5), 6)

        self.assertEqual(indexOf("122325", "2"), 1)
        self.assertEqual(indexOf("122325", "5"), 5)
        self.assertRaises(ValueError, indexOf, "122325", "6")

        self.assertRaises(TypeError, indexOf, 42, 1)
        self.assertRaises(TypeError, indexOf, indexOf, indexOf)

        f = open(TESTFN, "w")
        try:
            f.write("a\n" "b\n" "c\n" "d\n" "e\n")
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            fiter = iter(f)
            self.assertEqual(indexOf(fiter, "b\n"), 1)
            self.assertEqual(indexOf(fiter, "d\n"), 1)
            self.assertEqual(indexOf(fiter, "e\n"), 0)
            self.assertRaises(ValueError, indexOf, fiter, "a\n")
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass

        iclass = IteratingSequenceClass(3)
        for i in range(3):
            self.assertEqual(indexOf(iclass, i), i)
        self.assertRaises(ValueError, indexOf, iclass, -1)
 def parse(self, response):
     if response.status == 200:
         title = response.xpath('//dt[contains(@class,"clearfix join_tc_icon")]//h1/@title').extract()[0]
         job_id = response.xpath('//input[contains(@id,"jobid")]/@value').extract()[0]
         job_request = response.xpath('//dd[contains(@class,"job_request")]//span/text()').extract()
         job_other_ben = response.xpath('//dd[contains(@class,"job_request")]/text()').extract()
         job_des = response.xpath('//dd[contains(@class,"job_bt")]//p/text()').extract()
         job_address = response.xpath('//dl[contains(@class,"job_company")]//div/text()').extract()[2]
         job_benefits = job_other_ben[-2].strip()
         job_benefits_arr = job_benefits[operator.indexOf(job_benefits, ":") + 1:].split(u"、")
         job_item = JobItem(title, job_request[0], job_address.strip(), job_des, job_benefits_arr, job_request[1:],
                            response.url, job_id)
         mongo_store.save(job_item)
Esempio n. 24
0
    def decode(self,message,a = 0, k = 0):
        if not (a == 0):
            self.a = a
        if not (k == 0):
            self.k = k

        om = ""
        inv = self.mi()
        for letter in message:
            aa = inv * (operator.indexOf(self.dict,letter)-self.k)
            om += self.dict[aa % 27]

        return om
Esempio n. 25
0
    def __setitem__(self, key, new):
        try:
            idx = indexOf(self._allowed_keys, (key))
        except ValueError:
            raise ValueError("key '%s' not allowed" % key)

        t = self._allowed_types[idx]
        if type(new) != t:
            try:
                new = t(new)
            except Exception as e:
                raise TypeError("Conversion to %s failed for %s: %s" % (t, key, e))

        dict.__setitem__(self, key, new)
Esempio n. 26
0
def goodPrecisionFloToStr(floatNumber):
# returns string from rational or irrational float containing "0" or "9"
    resA, resB = str(floatNumber), "0"
    if "." in resA:
        resA, resB = resA.split(".")
    if fabs(floatNumber) < 0.1 or fabs(floatNumber) > 999:
        return "%.1E" % floatNumber
    if "0" in resB:
        T0 = indexOf(resB, "0")
    else:
        T0 = -1
    if "9" in resB:
        T9 = indexOf(resB, "9")
        if len(resB) >= T9 + 2:
            if resB[T9+1] < 6:
                T9 = -1
        else:
            T9 = -1
    else:
        T9 = -1
    if T0 == -1:
        if T9 == -1:
            return resA + "." + resB
        if T9 == 0:
            return str(int(resA) + 1)
        return resA + "." + str(int(resB[:T9]) + 1)
    elif T9 == -1:
        if T0 == 0:
            return resA
        return resA + "." + resB[:T0]
    elif T9 < T0:
        if T9 == 0:
            return str(int(resA) + 1)
        return resA + "." + str(int(resB[:T9]) + 1)
    if T0 == 0:
        return resA
    return resA + "." + resB[:T0]
Esempio n. 27
0
def test(all_extension, all_keywords, exclude_file=[]):
    """TODO: Docstring for parse_multi_file.
    :returns: TODO

    """
    all_files     = [x for x in os.listdir('./test') if x[0] != '.']

    with open('test.txt', 'w') as test_file:
        for one in all_files:
            single_list = [one]
            index       = operator.indexOf(all_extension, os.path.splitext(one)[1]) + 1
            keywords    = fill_feature_dict(single_list, './test/')
            result      = keyword_to_feature(keywords, all_keywords, index)

            test_file.write(result + os.linesep)
Esempio n. 28
0
def create_predict_file(filename, all_extension, all_keywords, exclude_file):
    """TODO: Docstring for predict.

    :filename: TODO
    :exclude_file: TODO
    :returns: TODO

    """
    keywords    = {}
    single_file = [filename]
    index       = operator.indexOf(all_extension, os.path.splitext(filename)[1]) + 1
    keywords    = fill_feature_dict(single_file, './unknow/')
    result      = keyword_to_feature(keywords, all_keywords, index)

    with open('unknow.txt', 'w') as unknow_file:
        unknow_file.write(result + os.linesep)
Esempio n. 29
0
 def unregister(self, ref_or_name):
     """ unregister a name in the registery. If the name doesn't
     exist we safely ignore it. """
     try:
         if isinstance(ref_or_name, six.string_types):
             with self._lock:
                 ref = self._registered_names[ref_or_name]
                 names = self._by_ref[ref]
                 del names[operator.indexOf(names, ref_or_name)]
                 del self._registered_names[ref_or_name]
         else:
             with self._lock:
                 names = self._by_ref[ref_or_name]
                 for name in names:
                     del self._registered_names[name]
     except (KeyError, IndexError):
         pass
Esempio n. 30
0
 def add_records_to_array(self,records,array):
   if(len(array) == 0):
     array.append(self.field_names)
     self.used_array = [False for i in self.field_names]
   name_hash = {}
   header = records.pop(0)
   for field in self.field_names:
     if(field in header):
       name_hash[field] = operator.indexOf(header,field)
   for record in records:
     output = ['' for s in self.field_names]
     for name in self.field_names:
       if(name in name_hash):
         s = record[name_hash[name]].strip()
         if(len(s) > 0):
           n = self.field_hash[name]
           output[n] = s
           self.used_array[n] = True
     array.append(output)