def inner_emit(self, lines, parent, context): if None != self.definition.get('emit'): captures = map(lambda s: String(s).to_xs(), list(self.cache)) return String(self.definition['emit']).format_with_array(captures) group = '' if self.cache.lastindex: group = self.cache.group(1) return ''.join([self.start_tag()] + self.transform_syntax([group], context) + [self.end_tag()])
def lab4(): num1_1, num1_2, num2_1, num2_2 = '0', '0', '0', '0' s, result = 'lol', '' if request.method == 'POST': try: if request.form['submit'] == 'Довжина рядка': s = request.form.get('string') st = String(s) result = st.get_length() if request.form['submit'] == 'Додавання': num1_1 = request.form.get('num1_1') num1_2 = request.form.get('num1_2') num2_1 = request.form.get('num2_1') num2_2 = request.form.get('num2_2') num1 = ComplexNum(num1_1, num1_2) num2 = ComplexNum(num2_1, num2_2) result = num1 + num2 if request.form['submit'] == 'Множення': num1_1 = request.form.get('num1_1') num1_2 = request.form.get('num1_2') num2_1 = request.form.get('num2_1') num2_2 = request.form.get('num2_2') num1 = ComplexNum(num1_1, num1_2) num2 = ComplexNum(num2_1, num2_2) result = num1 * num2 if request.form['submit'] == 'Порівняння': num1_1 = request.form.get('num1_1') num1_2 = request.form.get('num1_2') num2_1 = request.form.get('num2_1') num2_2 = request.form.get('num2_2') num1 = ComplexNum(num1_1, num1_2) num2 = ComplexNum(num2_1, num2_2) result = num1 == num2 return render_template('lab4.html', result=result, string=s, num1_1=num1_1, num1_2=num1_2, num2_1=num2_1, num2_2=num2_2) except: pass return render_template('lab4.html', result=result, string=s, num1_1=num1_1, num1_2=num1_2, num2_1=num2_1, num2_2=num2_2)
def ChangeExtension(oldFileName, extentionStr = ".txt"): oldFileName = String.Str2QString(oldFileName) index = oldFileName.indexOf('.') if index == -1: return None newFileName = oldFileName.left(index) + extentionStr return newFileName
def __setitem__(self, key, item): opts = dict(self._options) #opts['path'] = self.path opts['key'] = self.key + '/' + key # avoid to circular imports if Item._ItemClasses.has_key('Object'): Object = Item._ItemClasses['Object'] else: Object = Dict #clsname = type(item).__name__ if isinstance(item, Hex): item = Hex(item, **opts) elif isinstance(item, Object): item = Object(item, **opts) elif isinstance(item, bool): item = Boolean(item, **opts) elif isinstance(item, int): #int and Integer etc all derived from int. item = Integer(item, **opts) elif isinstance(item, str): item = String(item, **opts) elif isinstance(item, float): item = Float(item, **opts) elif isinstance(item, dict): item = Dict(item, **opts) elif item == Loading and not self.loadOnDemand: item = self.LoadItem(**opts) self.data[key] = item
def createHtml(self): html = self.start_html() if self.option.OUTPUT_PATH == 0: print('create path: => ' + String(self.option.htmlName).formatStr()) img = cv2.imread(self.imagePath, cv2.IMREAD_COLOR) if img is None: print('Failuer loaded image') return hei, wid = img.shape[:2] for wid_num in range(0, hei): if wid_num == 0: html = html + '<pre style="font: 10px/5px monospace;">' else: html = html + '<br>' for hei_num in range(0, wid): if img[wid_num, hei_num, 0] is None: print("none obj") else: color = self.emurateColor(wid_num, hei_num, img) html = html + self.span_html(color[0], color[1], color[2]) html = html + self.end_html() self.writeToFile(html) print('Complete\n🍺 ')
def words(self, word, line): str = '' for w in word: if w in self.symbols and self.reading_string == False: if str != '': if str.lower() in self.table: self.channel_values.append(Word( str, str.lower(), line)) #print(Word(str, self.table.get(str.lower()), line).toString()) else: self.channel_values.append( Word(str, 'identifier', line)) #print(Word(str, Tag.IDENTIFIER, line).toString()) str = '' self.channel_values.append(Token(w, w, line)) #print(Token(w, self.symbols.get(w), line).toString()) else: str += w if w == "'" and self.reading_string == False: self.reading_string = True elif w == "'" and self.reading_string: self.big_string += str self.channel_values.append(String(self.big_string, line)) #print(String(self.big_string, line).toString()) self.reading_string = False str = '' self.big_string = '' if self.reading_string: self.big_string += str + ' ' else: if str != '': self.channel_values.append(Word(str, 'identifier', line))
def setup(self, string): self.currentStep = self.ComputationStep(self.stateMachine.startState, String(string), Stack()) if self.computationHistory != None: self.computationHistory = ComputationHistoryList() self.computationHistory.inputTypes = ["Str", "Pop"] self.computationHistory.outputTypes = ["Push"]
def emit(self, lines, parent, context): for i in range(0, len(self.cache) + 2): lines.popleft() if self.must_preserve_whitespace( ) or self.sheet.preserve_whitespace > 0: self.cache = map(lambda s: String(s).unchomp(), self.cache) return [self.start_tag() + "\n"] + self.transform_syntax( self.cache, context) + [self.end_tag()]
def setup(self, string): computationStep = self.ComputationStep(self.stateMachine.startState, String(string)) self.currentSteps = [computationStep] if self.computationHistory != None: self.computationHistory = ComputationHistoryTree() self.computationHistory.inputTypes = ["Str"] self.computationHistory.root = ComputationHistoryTree.Node( self.stateMachine.startState, []) computationStep.node = self.computationHistory.root
def normalize( self, text ): # Normalize new lines text = re.sub( r'\r\n', "\n", text ) text = re.sub( r'\r', "\n", text ) # Join lines with trailing backslash (\) text = re.sub( r'\s*\\\s*(\n|$)', ' ', text ) # Escape character entities text = String(text).to_xs() return text
def mutate(self, parent, characters=1) -> str: """Generates a mutation from parent""" mutation = list(parent.content) previous_indexes = [] for _ in range(characters): index = random.randint(0, len(parent.content) - 1) while index in previous_indexes: index = random.randint(0, len(parent.content) - 1) previous_indexes.append(index) mutation[index] = random.choice(self.letters) content = "".join(mutation) return String(content, self.goal)
def compile_pattern(self, pattern, tightly=False): pattern = pattern or '' if isinstance(pattern, dict) and pattern.get('regexp'): return pattern['regexp'] pattern_segments = [pattern] # TODO What does tight mean? stopper = '' if tightly: pattern_segments = filter(bool, re.split(r'(\s*[^\s\w]+)', pattern)) chars = list(set(pattern_segments[0])) if 1 == len(chars): stopper = '(?!' + String( chars[0]).to_xs().escape_regexp() + ')' pattern_segments = map(lambda s: String(s).escape_regexp().to_xs(), pattern_segments) pattern_segments = [pattern_segments[0]] + [stopper ] + pattern_segments[1:] return ''.join(pattern_segments)
def match(self, lines): self.cache = super(Link, self).match(lines) # If the 'text' part of a link is devoid of significant characters, # this is not a match. e.g. [[ ! ]] is not a match, but [[ a! ]] is. if self.cache: captures = list(self.cache.groups()) for i in range(0, len(captures)): if i < len(self.uri_encode_map ) and self.uri_encode_map[i] and 0 == len( String(captures[i]).canonicalize()): return return self.cache
def escape_inline_syntax( self, text ): if not self.escape_inline_syntax_regexp: self.escape_inline_syntax_regexp = re.compile( String( '|'.join( map( lambda r: "(#" + r + ")", unique(self.inline_regexps) ) ) ).from_xs() ) return re.sub( self.escape_inline_syntax_regexp, lambda md: "`" + md.group(0) + "`", text )
def match_lines(lines): body = [] while len(lines) > 0: match_data = re.search(self.regexp, lines[0]) if not match_data: return body line = match_data.group(1) if self.must_preserve_whitespace( ) or self.sheet.preserve_whitespace > 0: line = String(line).unchomp() if self.regexps.get('starts_delimited_by'): line = re.sub( '^' + self.regexps.get('starts_delimited_by'), '', line) body.append(line) lines.popleft() return body
# Import NetworkTables to communicate with the RIO from networktables import NetworkTables from String import String # Connect to the RIO as a client NetworkTables.initialize(server='DESKTOP-T5DSCVI.local') # Get an instance of the table ledTable = NetworkTables.getTable('PiLED/strip') string = String() def LED_value_changed(source, key, value, isNew): global string print("==================") print("New file: " + value) # Get media type effectType = ledTable.getString("type", "off") print("Of type: " + effectType) result = string.display(effectType, value) ledTable.putBoolean("result", result) print("Result:") print(result) ledTable.addEntryListener(LED_value_changed, True, "file") print("Press Ctrl+C to exit")
def inner_emit(self, lines, parent, context): # Duplicate the match array because we are going to manipulate it in place captures = map(lambda c: c or '', list(self.cache.groups())) if not self.sheet.preserve_whitespace: captures = map(str.strip, captures) trailing_punctuation = '' if self.strip_trailing_punctuation: regexp = re.compile(r'([^\w\/]?)\z') def capture_trailing_punctuation(md): trailing_punctuation = md.group(0) return "" captures[-1] = re.sub(regexp, capture_trailing_punctuation, captures[-1]) uri_captures = [] for i in range(0, len(captures)): uri_captures.append(captures[i]) if i < len(self.uri_encode_map) and self.uri_encode_map[i]: uri_captures[i] = re.sub( r'\.', '%2e', String(uri_captures[i]).from_xs().encode_uri()) href = text = before = after = '' if self.definition['link'].get('href'): href = String(self.definition['link']['href']).format_with_array( uri_captures).format_with_hash( context).unescape_variable_interpolations().decode_uri() if self.definition['link'].get('text'): text = String(self.definition['link']['text']).format_with_array( captures).format_with_hash( context).unescape_variable_interpolations() if self.definition['link'].get('before'): before = String( self.definition['link']['before']).format_with_array( captures).format_with_hash( context).unescape_variable_interpolations() if self.definition['link'].get('after'): after = String(self.definition['link']['after']).format_with_array( captures).format_with_hash( context).unescape_variable_interpolations() klass = self.name if None != self.definition['link'].get( 'page_missing') and not context['page_exists'](href, context): klass = klass + ' ' + self.definition['link']['page_missing'] result = None if None != self.definition['link'].get('image') and re.match( Patterns.patterns['image'], href): alt = '' if '' != self.definition['link']['image']: alt = " alt='" + String(self.definition['link']['image'] ).format_with_array(captures) + "'" result = "<img src='" + href + "' class='" + klass + "'" + alt + "/>" elif None != self.definition['link'].get('name'): result = "<a name='" + String(self.definition['link']['name'] ).format_with_array(captures) + "'/>" else: result = "<a href='" + href + "' class='" + klass + "'>" + text + "</a>" return before + result + after + trailing_punctuation
def writeToFile(self, html): write_html = open(String(self.option.htmlName).formatStr(), 'w') write_html.write(html) write_html.close()
def str(name, default="", public=None, validator=None, tip="", doc=""): from String import String return String(name, default, public, validator, tip, doc)
Processor sub-class defining processing functions for the productions. """ def __init__(self): self.context = None def reset(self): self.context = Context() def _regex(self, (tag, left, right, sublist), buffer): regex = Regex() regex.data = getString(sublist[0], buffer) return regex def _string(self, (tag, left, right, sublist), buffer): string = getString(sublist[0], buffer) return String(self.context, string) def _varname(self, token, buffer): varname = getString(token, buffer) return self.context.lexicon[varname] def _number(self, token, buffer): number = getString(token, buffer) return Number(int(number)) def _expression(self, token, buffer): tag = token[0] if tag == 'string': return self._string(token, buffer) elif tag == 'regex': return self._regex(token, buffer)
def GetFileNameWithoutExtension(fileName): oldFileName = String.Str2QString(fileName) index = oldFileName.indexOf('.') if index == -1: return fileName return oldFileName.left(index)
count = 0 i = -1 j = 0 while j < len(pattern) - 1: if i == -1 or pattern[i] == pattern[j]: i += 1 j += 1 next[j] = i else: i = next[i] count += 1 print('count 2:', count) return next s = String("ADABDACDBABCABDABCDABDABCADBCDD") p = String("ABCDABD") next = getnext(p) print(next) print(kmp(s, p, next)) s = String("AAADAAAAA") p = String("AAAA") next = getnext(p) print(next) print(kmp(s, p, next)) s = String("ADABDACDBABCABDABCDABDABCADBCDD") p = String("ABCDABD") next = getnext_dp(p) print(next)
def __repr__(self): S = String('') if len(self.labels): S.concatenate(String(' ')) for c in self.labels: if self.weighted: S.concatenate(String(' %s ' % c)) else: S.concatenate(String(' %s ' % c)) S.concatenate(String('\n')) for i in range(self.graph.shape[0]): s = String(self.labels[i] + ' [' if len(self.labels) > 0 else ' [') for j in range(self.graph.shape[1]): if self.weighted: s.concatenate(String(' %.2f ' % self.graph[i, j])) else: s.concatenate(String(' %s ' % str(self.graph[i, j]))) s.concatenate(String(']\n')) S.concatenate(s) return S.__repr__()
def __repr__(self): S = String('[ \n') for i in range(self.shape[0]): s = String(' [') for j in range(self.shape[1]): s.concatenate(String(' %.1f ' % self[i, j])) s.concatenate(String(']\n')) S.concatenate(s) S.concatenate(String(']')) return S.__repr__()
def VisitStrNode(self, node, context): return RTResult().success( String(node.token.value).setContext(context).setPosition( node.startPos, node.endPos))
def first_string(self) -> String: """Generates a random string of 'abcdefghijklmnopqrstuvwxyz '.""" letters = string.ascii_lowercase + ' ' return String( ''.join(random.choice(letters) for _ in range(len(goal))), goal)