def truncate( s: str, length: Optional[int] = 79, prefix: Optional[str] = None, suffix: Optional[str] = ELP, smart: Optional[int] = 1, ) -> str: """Returns prefix + s + suffix, if the total length of this is <length> characters at most. If not, then it removes characters from s, then from the prefix, then from the suffix, until an acceptable length is achieved. :param int length: maximum length of the resulting string :param str prefix: str to add right before s :param str prefix: str to append to s :param bool smart: 0: nothing; 1: double whitespace reduced to single whitespace, trailing whitespace removed; 2: all whitespace removed :returns: prefix + s + suffix, possibly truncated """ # ensure length is a non-negative integer if not isinstance(length, int): raise TypeError("length must be int.") if length < 0: raise ValueError("length must not be negative.") # check types of both prefix and suffix if prefix is not None and not isinstance(prefix, str): raise TypeError("prefix must be str or None.") if suffix is not None: if not isinstance(suffix, str): raise TypeError("suffix must be str or None.") elif len(suffix) >= length: # if the suffix alone exceeds the target window, simply truncate it return suffix[:length] # whitespace processing, if smart is 1 or 2 if smart == 1: # remove trailing whitespace # s = re.sub(r"(^\s+|\s+$)", "", s) s = s.strip() # replace double whitespace with single whitespace s = re.sub(r"\s{2,}", SPACE, s) elif smart == 2: # remove all whitespace s = re.sub("\s+", "", s) elif smart != 0: # not in (0, False): raise ValueError("smart must be either 0, 1 or 2.") # actual truncating trunc = prefix + s if prefix else s was_long = len(trunc) > length trunc = trunc[:length] if was_long and suffix: trunc = make_end(trunc, suffix) return trunc
def click(self, texto, escribir): #Si el parámetro 'escribir' es True, entonces el parámetro texto debe mostrarse en pantalla. Si es False, no. if not escribir: #Sólo calcular si hay una operación a ser evaluada y si el usuario presionó '=' if texto=="=" and self.operacion!="": #Reemplazar el valor unicode de la división por el operador división de Python '/' self.operacion=re.sub(u"\u00F7", "/", self.operacion) self.operacion=re.sub(u"x", "*", self.operacion) self.operacion=re.sub(u"ans", self.ans, self.operacion) try: resultado=str(eval(self.operacion)) self.ans=resultado except: resultado="Error" self.operacion=resultado self.limpiarPantalla() self.mostrarEnPantalla(resultado) #Si se presionó el botón de borrado, limpiar la pantalla dependiendo de la operación que haya elif texto==u"\u232B": if(self.operacion.__contains__("Error")): self.limpiarPantalla() self.operacion="" elif((self.operacion.__contains__("ans") and self.operacion[-1] == "s") or (len(self.operacion) >=1 and self.operacion[-1] == " ")): self.operacion = self.operacion[:-1] self.operacion = self.operacion[:-1] self.operacion = self.operacion[:-1] self.limpiarPantalla() self.mostrarEnPantalla(self.operacion) else: self.operacion = self.operacion[:-1] self.limpiarPantalla() self.mostrarEnPantalla(self.operacion) #Mostrar texto else: if(self.operacion.__contains__("Error")): self.operacion="" self.limpiarPantalla() self.operacion+=str(texto) self.mostrarEnPantalla(texto) return
def click(self, texto, escribir): if not escribir: if texto == "=" and self.operacion != "": self.operacion = re.sub(u"\u00F7", "/", self.operacion) resultado = str(eval(self.operacion)) self.operacion = "" self.limpiarPantalla() self.mostrarEnPantalla(resultado) elif texto == u"\u00F7": self.operacion = "" self.limpiarPantalla() else: self.operacion += str(texto) self.mostrarEnPantalla(texto) return
def click(self, texto, escribir): #si el parametro 'escribir' rs True, entonces el parametro texto debe mostrarse en pantalla. Si es false, no. if not escribir: if texto == "=" and self.operacion != "": self.operacion = re.sub(u"\u00F7", "/", self.operacion) resultado = str(eval(self.operacion)) self.operacion = "" self.limpiarPantalla() self.mostrarEnPantalla(resultado) elif texto == u"\u232B": self.operacion = "" self.limpiarPantalla() #Mostrar texto else: self.operacion += str(texto) self.limpiarPantalla(texto) return
def click(self, texto, escribir): if not escribir: if texto == "=" and self.operacion != "": #Reemplazar unicode de división por división de Python '/' self.operacion = re.sub(u"\u00F7", "/", self.operacion) resultado = str(eval(self.operacion)) self.operacion = "" self.limpiarPantalla() self.mostrarEnPantalla(resultado) #limpiar la pantalla elif texto == u"\u232B": self.operacion = "" self.limpiarPantalla() #Mostrar texto else: self.operacion += str(texto) self.mostrarEnPantalla(texto) return
def click(self, text, write): # this function handles what happens when you click a button # 'write' argument if True means the value 'val' should be written on screen, if None, should not be written on screen if write == None: # only evaluate code when there is an equation to be evaluated if text == '=' and self.equation: # replace the unicode value of division ./.with python division symbol / using regex self.equation = re.sub(u"\u00F7", '/', self.equation) print(self.equation) answer = str(eval(self.equation)) self.clear_screen() self.insert_screen(answer, newline=True) elif text == u"\u232B": self.clear_screen() else: # add text to screen self.insert_screen(text)
def click(self, texto, escribir): #Si el parámetro 'escribir' es True, entonces el parámetro texto debe mostrarse en pantalla. Si es False, no. if not escribir: #Sólo calcular si hay una operación a ser evaluada y si el usuario presionó '=' if texto == "=" and self.operacion != "": #Reemplazar el valor unicode de la división por el operador división de Python '/' self.operacion = re.sub(u"\u00F7", "/", self.operacion) resultado = str(eval(self.operacion)) self.operacion = "" self.limpiarPantalla() self.mostrarEnPantalla(resultado) #Si se presionó el botón de borrado, limpiar la pantalla elif texto == u"\u232B": self.operacion = "" self.limpiarPantalla() #Mostrar texto else: self.operacion += str(texto) self.mostrarEnPantalla(texto) return
def click(self, texto, escribir): if not escribir: try: if texto == "=" and self.operacion != "": self.operacion = re.sub(u"\u00F7", "/", self.operacion) resultado = str(eval(self.operacion)) self.operacion = "" self.limpiarPantalla() self.mostrarEnPantalla(resultado) elif texto == u"\u232B": self.operacion = "" self.limpiarPantalla() except ZeroDivisionError: self.limpiarPantalla() self.mostrarEnPantalla("Sintaxis Error") except SyntaxError: self.limpiarPantalla() self.mostrarEnPantalla("Sintaxis Error") else: self.operacion += str(texto) self.mostrarEnPantalla(texto) return
def read( self, text: Sequence[str], configuration: Union[dict, Configuration] ) -> None: if isinstance(configuration, (dict, Configuration)): configs = Configuration(configuration) else: raise ValueError(f"{repr(configuration)} must be dict or Configuration!") # configs is necessarily a Configuration instance self.location = self.OUT sample = SPACE.join(text[:6]) print(truncate(sample, prefix="Reading: ")) indexes = var_zfill(*range(1, len(text) + 1)) # assert len(list(indexes)) == len(text) for index, line in zip(indexes, text): # enumerate(text, start=1): line = line.strip() print(truncate(line, prefix=f"{index}: ")) if line.startswith(PERCENT): # the current line is a LaTeX comment # first, disregard the % character line = re.sub(r"^%+", "", line) # .strip(PERCENT) # delete(line, PERCENT) if self.location == self.OUT: # a question has started! self.question_type = "" self.location = self.IN_QUESTION # this first line should look like this: # % UFRJ-RJ 2011 tokens = line.split() self.source = SPACE.join(tokens[:-1]) self.year = tokens[-1] elif line.startswith(configs.USO): # the current line is a # % Uso: lista01-19, aula13-19 # line line = delete(line, configs.USO) tokens = line.split(COMMA) self.histories.extend(tokens) elif line.startswith(configs.TAGS): # the current line is a # % Tags: figuras de linguagem, sintaxe # line line = delete(line, configs.TAGS) tokens = [t.strip() for t in line.split(",")] self.tags.extend(tokens) elif line.startswith(configs.BEGIN_QUESTION): # the current line is a # \begin{Exercise}[label=ufa,origin={UFA-AM}] # line for latex_key, latex_value in self.pattern.findall(line): latex_key = latex_key.lower() latex_value = latex_value.lower() source = self.source.lower() if latex_key == configs.LABEL: if latex_value.lstrip("q:") not in source: print(f"> {latex_value} is not in {self.source}!") else: pass # print(f"{latex_key}={latex_value} is ok!") elif latex_key == configs.ORIGIN: if latex_value.strip("}{") not in self.source: print(f"> {latex_value} is not in {self.source}!") else: pass # print(f"{latex_key}={latex_value} is ok!") elif line.startswith(configs.BEGIN_CHOICES): # this question is a choices question self.question_type = Question.CHOICES_TYPE elif line.startswith(configs.CHOICE): # this line contains a choice: # \choice fática. assert self.question_type == Question.CHOICES_TYPE line = delete(line, configs.CHOICE) self.choices.append(line) elif line.startswith(configs.CORRECT): # this line contains the correct choice: # \CorrectChoice fática. assert self.question_type == Question.CHOICES_TYPE line = delete(line, configs.CORRECT) self.answer = line self.choices.append(line) elif line.startswith(configs.END_CHOICES): # this is the \end{choices} line self.wrongs.extend(self.choices) self.wrongs.remove(self.answer) elif line.startswith(configs.END_QUESTION): # this is the \end{Exercise} line assert self.location == self.IN_QUESTION self.location = self.OUT if not self.question_type: self.question_type = Question.WRITTEN_TYPE elif line.startswith(configs.BEGIN_ANSWER): assert self.location == self.OUT self.location = self.IN_ANSWER elif line.startswith(configs.END_ANSWER): assert self.location == self.IN_ANSWER q = self.get_question(configs) self.questions.append(q) print("Nova questão:") print(q) print(truncate(str(self.questions), prefix="self.questions: ")) self.location = self.OUT elif line: # the line is plain text; append it in the proper list: if self.location == self.IN_QUESTION: self.texts.append(line) elif self.location == self.IN_ANSWER: self.explanations.append(line) else: raise ParsingException # print(reveal(self)) self.location = None