问:
How to use QThread in both gui and non-gui application in Python?
I am writing a fuzzy search application which finds words in text even if words have mistakes. I wrote gui form but it freezed because of heavy calculation. So I created class inherited from QThread and emitted signals from it to gui so that progress bar started to work and gui form wasn't freezed anymore. BUT I should also create console version of this application where I don't need gui form but I need methods that written in class inherited from QThread. But it's impossible without using PyQT library which strange to use in console version. So I don't know how to solve this problem. My teacher recommended to use threading but I didn't find how to emit signals from Thread class as I colud do in QThread.

That's a QThread class

```<code>import text_methods
from PyQt5.QtCore import pyqtSignal, QThread

class FuzzySearch(QThread):
    sig_words_count = pyqtSignal(int)
    sig_step = pyqtSignal(int)
    sig_done = pyqtSignal(bool)
    sig_insertions = pyqtSignal(str)
    sig_insertions_indexes = pyqtSignal(list)

    def __init__(self, text, words, case_sensitive):
        super().__init__()
        self.text = text
        self.words = words
        self.case_sensitive = case_sensitive
        self.insertions_indexes = {}
        self.text_dict = {}

    def run(self):
        self.get_insertions_info(self.text, self.words)

    def find_insertions_of_word(self, word, word_number):
        word_insertions = {}
        for textword in self.text_dict.keys():
            if text_methods.is_optimal_distance(word, textword):
                word_insertions[textword] = self.text_dict[textword]
                for index in self.text_dict[textword]:
                    self.insertions_indexes[index] = index + len(textword)
        self.sig_step.emit(word_number)
        return word_insertions

    '''Get information about insertions of words in the text'''
    def find_insertions(self, text, words):
        word_number = 1
        insertions = {}
        self.text_dict = text_methods.transform_text_to_dict(text, self.case_sensitive)
        words_list = text_methods.transform_words_to_list(words, self.case_sensitive)
        self.sig_words_count.emit(len(words_list))
        for word in words_list:
            print(word_number)
            insertions[word] = self.find_insertions_of_word(word, word_number)
            word_number += 1
        self.insertions_indexes = sorted(self.insertions_indexes.items())
        return insertions

    '''Get information about insertions of words in the text in special format'''
    def get_insertions_info(self, text, words):
        insertions = self.find_insertions(text, words)
        insertions_info = ''
        for word in insertions.keys():
            insertions_info += 'Вы искали слово "' + word + '"\n'
            if len(insertions[word]) == 0:
                insertions_info += '  По этому запросу не было найдено слов\n'
            else:
                insertions_info += '  По этому запросу были найдены слова:\n'
                for textword in insertions[word].keys():
                    insertions_info += '   "' + textword + '" на позициях: '
                    insertions_info += ", ".join([str(i) for i in insertions[word][textword]])
                    insertions_info += '\n'
        self.sig_done.emit(True)
        self.sig_insertions.emit(insertions_info)
        self.sig_insertions_indexes.emit(self.insertions_indexes)
        self.quit()
</code>```

As you see there are a lot of emitted signals that I transfer to gui module where they connect to slots in class FindButton in method find_insertions:

```<code>from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QApplication, QWidget,\
                            QLabel, QPushButton, QTextEdit, QFileDialog,\
                            QMessageBox, QProgressBar, QCheckBox
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from fuzzysearch import FuzzySearch
import sys

class OpenButton(QPushButton):
    def __init__(self, name, font, textedit):
        super().__init__(name, font=font)
        self.textedit = textedit
        self.clicked.connect(self.open_dialog)

    def open_dialog(self):
        fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
        if fname[0]:
            with open(fname[0], 'r') as f:
                data = f.read()
                self.textedit.setText(data)

class FindButton(QPushButton):
    def __init__(self, name, font, text, words, result, window):
        super().__init__(name, font=font)
        self.window = window
        self.textedit = text
        self.wordsedit = words
        self.resultedit = result
        self.checkbox = window.case_sensitive_checkbox
        self.clicked.connect(self.find_insertions)

    def find_insertions(self):
        text = self.textedit.toPlainText()
        words = self.wordsedit.toPlainText()
        if text == '':
            QMessageBox.information(self, 'Нет текста',
                                    'Текст не был введен. \nВведите текст.')
        elif words == '':
            QMessageBox.information(self, 'Нет слов',
                                    'Слова не были введены. \nВведите слова через запятую.')
        else:
            self.setDisabled(True)
            self.text_editor = TextEditor(text, self.textedit)
            self.fuzzy_search = FuzzySearch(text, words, self.checkbox.checkState())
            self.fuzzy_search.sig_words_count.connect(self.window.progress_bar.setMaximum)
            self.fuzzy_search.sig_step.connect(self.window.progress_bar.setValue)
            self.fuzzy_search.sig_done.connect(self.setEnabled)
            self.fuzzy_search.sig_insertions.connect(self.resultedit.setText)
            self.fuzzy_search.sig_insertions_indexes.connect(self.text_editor.mark)
            self.fuzzy_search.start()

class TextEditor:
    def __init__(self, text, textedit):
        self.text = text
        self.textedit = textedit

    def mark(self, to_mark):
        self.textedit.clear()
        current_index = 0
        for item in to_mark:
            self.write_not_marked_text(self.text[current_index:item[0]])
            self.write_marked_text(self.text[item[0]:item[1]])
            current_index = item[1]
        self.write_not_marked_text(self.text[current_index:])

    def write_not_marked_text(self, text):
        font = QFont("Times", 10)
        font.setItalic(False)
        font.setBold(False)
        self.textedit.setCurrentFont(font)
        self.textedit.setTextColor(Qt.black)
        self.textedit.insertPlainText(text)

    def write_marked_text(self, text):
        font = QFont("Times", 10)
        font.setItalic(True)
        font.setBold(True)
        self.textedit.setCurrentFont(font)
        self.textedit.setTextColor(Qt.red)
        self.textedit.insertPlainText(text)

class Window(QWidget):
    def __init__(self, font):
        super().__init__()
        self.standard_font = font
        self.text_edit_font = QFont("Times", 10)

        text_label = QLabel("Введите или откройте текст",
                            font=self.standard_font)
        words_label = QLabel("Введите или откройте слова (через запятую)",
                             font=self.standard_font)
        result_label = QLabel("Результат",
                              font=self.standard_font)

        text_edit = QTextEdit(font=self.text_edit_font)
        words_edit = QTextEdit(font=self.text_edit_font)
        result_edit = QTextEdit(font=self.text_edit_font)

        self.case_sensitive_checkbox = QCheckBox('Учитывать регистр')
        self.case_sensitive_checkbox.setFont(self.standard_font)

        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)

        open_btn1 = OpenButton("Открыть", self.standard_font, text_edit)
        open_btn2 = OpenButton("Открыть", self.standard_font, words_edit)
        find_btn = FindButton("Найти слова в тексте", self.standard_font,
                              text_edit, words_edit, result_edit, self)

        text_label_box = QHBoxLayout()
        text_label_box.addWidget(text_label, alignment=Qt.AlignLeft)
        text_label_box.addWidget(open_btn1, alignment=Qt.AlignRight)

        words_label_box = QHBoxLayout()
        words_label_box.addWidget(words_label, alignment=Qt.AlignLeft)
        words_label_box.addWidget(open_btn2, alignment=Qt.AlignRight)

        words_box = QVBoxLayout()
        words_box.addLayout(words_label_box)
        words_box.addWidget(words_edit)

        result_box = QVBoxLayout()
        result_box.addWidget(result_label, alignment=Qt.AlignLeft)
        result_box.addWidget(result_edit)

        bottom_box = QHBoxLayout()
        bottom_box.addLayout(words_box)
        bottom_box.addLayout(result_box)

        find_and_progress_box = QHBoxLayout()
        find_and_progress_box.addWidget(find_btn, alignment=Qt.AlignLeft)
        find_and_progress_box.addWidget(self.case_sensitive_checkbox)
        find_and_progress_box.addWidget(self.progress_bar)

        main_box = QVBoxLayout()
        main_box.addLayout(text_label_box)
        main_box.addWidget(text_edit)
        main_box.addLayout(bottom_box)
        main_box.addLayout(find_and_progress_box)

        self.setLayout(main_box)

        self.setGeometry(300, 300, 1100, 700)
        self.setWindowTitle('Нечеткий поиск')
        self.show()

def start_application():
    app = QApplication(sys.argv)
    w = Window(QFont("Times", 12))
    sys.exit(app.exec_())
</code>```

And it works perfectly. But it will not work in console version because without QEventLoop QThread will not work:

```<code>import fuzzysearch

class ConsoleVersion():
    def __init__(self, text, words):
        self.text = text
        self.words = words

    def search_words_in_text(self):
        with self.text:
            with self.words:
                self.f = fuzzysearch.FuzzySearch(self.text.read(), self.words.read(), False)
                self.f.sig_insertions.connect(self.get_insertions)
                self.f.start()

    def get_insertions(self, insertions):
        print(insertions)
</code>```

and in main file I wrote parsing arguments and choise between two versions

```<code>import argparse
import gui
import console_version

def parse_args():
    parser = argparse.ArgumentParser(description='Fuzzy search in text')
    parser.add_argument('-g', '--graphics', help='graphical version', action='store_true')
    parser.add_argument('-c', '--console', help='console version', nargs=2, type=argparse.FileType('r'), metavar=('TEXTFILE', 'WORDSFILE'))
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    if args.graphics:
        gui.start_application()
    if args.console:
        cv = console_version.ConsoleVersion(args.console[0], args.console[1])
        cv.search_words_in_text()
</code>```

and module text_methods:

```<code>from re import split, sub

def transform_text_to_dict(text, case_sensitive):
    text_dict = {}
    index = 0
    if case_sensitive:
        splitted_text = split("[^'а-яА-ЯA-Za-z0-9_-]", text)
    else:
        splitted_text = split("[^'а-яА-ЯA-Za-z0-9_-]", text.lower())
    for element in splitted_text:
        if element not in text_dict:
            text_dict[element] = []
        text_dict[element].append(index)
        index += len(element) + 1
    return text_dict

def transform_words_to_list(words, case_sensitive):
    words = sub("^\s+|\n|\r|\s+$", '', words)
    if case_sensitive:
        return split(' *, *', words)
    else:
        return split(' *, *', words.lower())

'''Damerau-Levenstein'''
def find_distance(word1: str, word2: str):
    len1, len2 = len(word1), len(word2)
    if len1 > len2:
        word1, word2 = word2, word1
        len1, len2 = len2, len1
    current_row = range(len1 + 1)
    previous_row = range(len1 + 1)
    pre_previous_row = range(len1 + 1)
    for i in range(1, len2 + 1):
        if i == 1:
            previous_row, current_row = current_row, [i] + [0] * len1
        else:
            pre_previous_row, previous_row, current_row = previous_row, current_row, [i] + [0] * len1
        for j in range(1, len1 + 1):
            add = previous_row[j] + 1
            delete = current_row[j - 1] + 1
            change = previous_row[j - 1]
            if word1[j - 1] != word2[i - 1]:
                change += 1
            if word1[j - 1] == word2[i - 2] and word1[j - 2] == word2[i - 1]:
                transpose = pre_previous_row[j - 2] + 1
                current_row[j] = min(add, delete, change, transpose)
            else:
                current_row[j] = min(add, delete, change)
    return current_row[len1]

def is_optimal_distance(word1 : str, word2 : str):
    distance = find_distance(word1, word2)
    l = min(len(word1), len(word2))
    return distance <= l // 4
</code>```

so what can you advise me?

答:
Qt so that to handle the tasks always needs a loop that is created internally for it one must construct an object of the type QCoreApplication, QGuiApplication or QApplication, this needs it for example for this case for QThread that is not a thread but a thread handler for that is monitoring the state of the thread, if you do not place the application is closed immediately since the run method is not executed in the main thread.

```<code>if args.console:
    app = QCoreApplication(sys.argv)
    cv = console_version.ConsoleVersion(args.console[0], args.console[1])
    cv.search_words_in_text()
    sys.exit(app.exec_())
</code>```

Body:
I am writing a fuzzy search application which finds words in text even if words have mistakes. I wrote gui form but it freezed because of heavy calculation. So I created class inherited from QThread and emitted signals from it to gui so that progress bar started to work and gui form wasn't freezed anymore. BUT I should also create console version of this application where I don't need gui form but I need methods that written in class inherited from QThread. But it's impossible without using PyQT library which strange to use in console version. So I don't know how to solve this problem. My teacher recommended to use threading but I didn't find how to emit signals from Thread class as I colud do in QThread.

That's a QThread class

import text_methods
from PyQt5.QtCore import pyqtSignal, QThread

class FuzzySearch(QThread):
    sig_words_count = pyqtSignal(int)
    sig_step = pyqtSignal(int)
    sig_done = pyqtSignal(bool)
    sig_insertions = pyqtSignal(str)
    sig_insertions_indexes = pyqtSignal(list)

    def __init__(self, text, words, case_sensitive):
        super().__init__()
        self.text = text
        self.words = words
        self.case_sensitive = case_sensitive
        self.insertions_indexes = {}
        self.text_dict = {}

    def run(self):
        self.get_insertions_info(self.text, self.words)

    def find_insertions_of_word(self, word, word_number):
        word_insertions = {}
        for textword in self.text_dict.keys():
            if text_methods.is_optimal_distance(word, textword):
                word_insertions[textword] = self.text_dict[textword]
                for index in self.text_dict[textword]:
                    self.insertions_indexes[index] = index + len(textword)
        self.sig_step.emit(word_number)
        return word_insertions

    '''Get information about insertions of words in the text'''
    def find_insertions(self, text, words):
        word_number = 1
        insertions = {}
        self.text_dict = text_methods.transform_text_to_dict(text, self.case_sensitive)
        words_list = text_methods.transform_words_to_list(words, self.case_sensitive)
        self.sig_words_count.emit(len(words_list))
        for word in words_list:
            print(word_number)
            insertions[word] = self.find_insertions_of_word(word, word_number)
            word_number += 1
        self.insertions_indexes = sorted(self.insertions_indexes.items())
        return insertions

    '''Get information about insertions of words in the text in special format'''
    def get_insertions_info(self, text, words):
        insertions = self.find_insertions(text, words)
        insertions_info = ''
        for word in insertions.keys():
            insertions_info += 'Вы искали слово "' + word + '"\n'
            if len(insertions[word]) == 0:
                insertions_info += '  По этому запросу не было найдено слов\n'
            else:
                insertions_info += '  По этому запросу были найдены слова:\n'
                for textword in insertions[word].keys():
                    insertions_info += '   "' + textword + '" на позициях: '
                    insertions_info += ", ".join([str(i) for i in insertions[word][textword]])
                    insertions_info += '\n'
        self.sig_done.emit(True)
        self.sig_insertions.emit(insertions_info)
        self.sig_insertions_indexes.emit(self.insertions_indexes)
        self.quit()

As you see there are a lot of emitted signals that I transfer to gui module where they connect to slots in class FindButton in method find_insertions:

from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QApplication, QWidget,\
                            QLabel, QPushButton, QTextEdit, QFileDialog,\
                            QMessageBox, QProgressBar, QCheckBox
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from fuzzysearch import FuzzySearch
import sys

class OpenButton(QPushButton):
    def __init__(self, name, font, textedit):
        super().__init__(name, font=font)
        self.textedit = textedit
        self.clicked.connect(self.open_dialog)

    def open_dialog(self):
        fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
        if fname[0]:
            with open(fname[0], 'r') as f:
                data = f.read()
                self.textedit.setText(data)

class FindButton(QPushButton):
    def __init__(self, name, font, text, words, result, window):
        super().__init__(name, font=font)
        self.window = window
        self.textedit = text
        self.wordsedit = words
        self.resultedit = result
        self.checkbox = window.case_sensitive_checkbox
        self.clicked.connect(self.find_insertions)

    def find_insertions(self):
        text = self.textedit.toPlainText()
        words = self.wordsedit.toPlainText()
        if text == '':
            QMessageBox.information(self, 'Нет текста',
                                    'Текст не был введен. \nВведите текст.')
        elif words == '':
            QMessageBox.information(self, 'Нет слов',
                                    'Слова не были введены. \nВведите слова через запятую.')
        else:
            self.setDisabled(True)
            self.text_editor = TextEditor(text, self.textedit)
            self.fuzzy_search = FuzzySearch(text, words, self.checkbox.checkState())
            self.fuzzy_search.sig_words_count.connect(self.window.progress_bar.setMaximum)
            self.fuzzy_search.sig_step.connect(self.window.progress_bar.setValue)
            self.fuzzy_search.sig_done.connect(self.setEnabled)
            self.fuzzy_search.sig_insertions.connect(self.resultedit.setText)
            self.fuzzy_search.sig_insertions_indexes.connect(self.text_editor.mark)
            self.fuzzy_search.start()

class TextEditor:
    def __init__(self, text, textedit):
        self.text = text
        self.textedit = textedit

    def mark(self, to_mark):
        self.textedit.clear()
        current_index = 0
        for item in to_mark:
            self.write_not_marked_text(self.text[current_index:item[0]])
            self.write_marked_text(self.text[item[0]:item[1]])
            current_index = item[1]
        self.write_not_marked_text(self.text[current_index:])

    def write_not_marked_text(self, text):
        font = QFont("Times", 10)
        font.setItalic(False)
        font.setBold(False)
        self.textedit.setCurrentFont(font)
        self.textedit.setTextColor(Qt.black)
        self.textedit.insertPlainText(text)

    def write_marked_text(self, text):
        font = QFont("Times", 10)
        font.setItalic(True)
        font.setBold(True)
        self.textedit.setCurrentFont(font)
        self.textedit.setTextColor(Qt.red)
        self.textedit.insertPlainText(text)

class Window(QWidget):
    def __init__(self, font):
        super().__init__()
        self.standard_font = font
        self.text_edit_font = QFont("Times", 10)

        text_label = QLabel("Введите или откройте текст",
                            font=self.standard_font)
        words_label = QLabel("Введите или откройте слова (через запятую)",
                             font=self.standard_font)
        result_label = QLabel("Результат",
                              font=self.standard_font)

        text_edit = QTextEdit(font=self.text_edit_font)
        words_edit = QTextEdit(font=self.text_edit_font)
        result_edit = QTextEdit(font=self.text_edit_font)

        self.case_sensitive_checkbox = QCheckBox('Учитывать регистр')
        self.case_sensitive_checkbox.setFont(self.standard_font)

        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)

        open_btn1 = OpenButton("Открыть", self.standard_font, text_edit)
        open_btn2 = OpenButton("Открыть", self.standard_font, words_edit)
        find_btn = FindButton("Найти слова в тексте", self.standard_font,
                              text_edit, words_edit, result_edit, self)

        text_label_box = QHBoxLayout()
        text_label_box.addWidget(text_label, alignment=Qt.AlignLeft)
        text_label_box.addWidget(open_btn1, alignment=Qt.AlignRight)

        words_label_box = QHBoxLayout()
        words_label_box.addWidget(words_label, alignment=Qt.AlignLeft)
        words_label_box.addWidget(open_btn2, alignment=Qt.AlignRight)

        words_box = QVBoxLayout()
        words_box.addLayout(words_label_box)
        words_box.addWidget(words_edit)

        result_box = QVBoxLayout()
        result_box.addWidget(result_label, alignment=Qt.AlignLeft)
        result_box.addWidget(result_edit)

        bottom_box = QHBoxLayout()
        bottom_box.addLayout(words_box)
        bottom_box.addLayout(result_box)

        find_and_progress_box = QHBoxLayout()
        find_and_progress_box.addWidget(find_btn, alignment=Qt.AlignLeft)
        find_and_progress_box.addWidget(self.case_sensitive_checkbox)
        find_and_progress_box.addWidget(self.progress_bar)

        main_box = QVBoxLayout()
        main_box.addLayout(text_label_box)
        main_box.addWidget(text_edit)
        main_box.addLayout(bottom_box)
        main_box.addLayout(find_and_progress_box)

        self.setLayout(main_box)

        self.setGeometry(300, 300, 1100, 700)
        self.setWindowTitle('Нечеткий поиск')
        self.show()

def start_application():
    app = QApplication(sys.argv)
    w = Window(QFont("Times", 12))
    sys.exit(app.exec_())

And it works perfectly. But it will not work in console version because without QEventLoop QThread will not work:

import fuzzysearch

class ConsoleVersion():
    def __init__(self, text, words):
        self.text = text
        self.words = words

    def search_words_in_text(self):
        with self.text:
            with self.words:
                self.f = fuzzysearch.FuzzySearch(self.text.read(), self.words.read(), False)
                self.f.sig_insertions.connect(self.get_insertions)
                self.f.start()

    def get_insertions(self, insertions):
        print(insertions)

and in main file I wrote parsing arguments and choise between two versions

import argparse
import gui
import console_version

def parse_args():
    parser = argparse.ArgumentParser(description='Fuzzy search in text')
    parser.add_argument('-g', '--graphics', help='graphical version', action='store_true')
    parser.add_argument('-c', '--console', help='console version', nargs=2, type=argparse.FileType('r'), metavar=('TEXTFILE', 'WORDSFILE'))
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    if args.graphics:
        gui.start_application()
    if args.console:
        cv = console_version.ConsoleVersion(args.console[0], args.console[1])
        cv.search_words_in_text()

and module text_methods:

from re import split, sub

def transform_text_to_dict(text, case_sensitive):
    text_dict = {}
    index = 0
    if case_sensitive:
        splitted_text = split("[^'а-яА-ЯA-Za-z0-9_-]", text)
    else:
        splitted_text = split("[^'а-яА-ЯA-Za-z0-9_-]", text.lower())
    for element in splitted_text:
        if element not in text_dict:
            text_dict[element] = []
        text_dict[element].append(index)
        index += len(element) + 1
    return text_dict

def transform_words_to_list(words, case_sensitive):
    words = sub("^\s+|\n|\r|\s+$", '', words)
    if case_sensitive:
        return split(' *, *', words)
    else:
        return split(' *, *', words.lower())

'''Damerau-Levenstein'''
def find_distance(word1: str, word2: str):
    len1, len2 = len(word1), len(word2)
    if len1 > len2:
        word1, word2 = word2, word1
        len1, len2 = len2, len1
    current_row = range(len1 + 1)
    previous_row = range(len1 + 1)
    pre_previous_row = range(len1 + 1)
    for i in range(1, len2 + 1):
        if i == 1:
            previous_row, current_row = current_row, [i] + [0] * len1
        else:
            pre_previous_row, previous_row, current_row = previous_row, current_row, [i] + [0] * len1
        for j in range(1, len1 + 1):
            add = previous_row[j] + 1
            delete = current_row[j - 1] + 1
            change = previous_row[j - 1]
            if word1[j - 1] != word2[i - 1]:
                change += 1
            if word1[j - 1] == word2[i - 2] and word1[j - 2] == word2[i - 1]:
                transpose = pre_previous_row[j - 2] + 1
                current_row[j] = min(add, delete, change, transpose)
            else:
                current_row[j] = min(add, delete, change)
    return current_row[len1]

def is_optimal_distance(word1 : str, word2 : str):
    distance = find_distance(word1, word2)
    l = min(len(word1), len(word2))
    return distance <= l // 4

so what can you advise me?

Body:
Qt so that to handle the tasks always needs a loop that is created internally for it one must construct an object of the type QCoreApplication, QGuiApplication or QApplication, this needs it for example for this case for QThread that is not a thread but a thread handler for that is monitoring the state of the thread, if you do not place the application is closed immediately since the run method is not executed in the main thread.

if args.console:
    app = QCoreApplication(sys.argv)
    cv = console_version.ConsoleVersion(args.console[0], args.console[1])
    cv.search_words_in_text()
    sys.exit(app.exec_())


来源: stackexchange

问:
rake error: "warning: already initialized constant FileUtils::OPT_TABLE"
I've seen similar questions regarding this error, but all of them rails-related. I'm not using rails; I'm working on a local rake task that reads from a yaml file and then does stuff with the data. I'd rather not install bundler for this (the solutions for the similar rails issues suggest prepending with bundle exec), since this script is simple and thus shouldn't need it.

Here's the simplified code, (which gets the same error as the code I'm working on):

```<code>require 'FileUtils'
require 'yaml'

SOME_FILE = "#{Dir.pwd}/some_file.yaml"

task default: :foo

task :foo do
  bar = File.open(SOME_FILE) { |yf| YAML::load( yf ) }
  bar.each {|k,v| puts k}
end
</code>```

And here's the list of errors:

```<code>/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:93: warning: already initialized constant FileUtils::OPT_TABLE
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:93: warning: previous definition of OPT_TABLE was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1272: warning: already initialized constant FileUtils::Entry_::S_IF_DOOR
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1272: warning: previous definition of S_IF_DOOR was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1535: warning: already initialized constant FileUtils::Entry_::DIRECTORY_TERM
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1535: warning: previous definition of DIRECTORY_TERM was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1537: warning: already initialized constant FileUtils::Entry_::SYSCASE
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1537: warning: previous definition of SYSCASE was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1656: warning: already initialized constant FileUtils::LOW_METHODS
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1656: warning: previous definition of LOW_METHODS was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1662: warning: already initialized constant FileUtils::METHODS
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1662: warning: previous definition of METHODS was here
</code>```

The script will run fine despite the warnings; the above code would puts the keys as expected, right after the warnings.

答:
Wanted to answer this clearly (two years after it was asked) in case anyone wanders in here.

First, note that require in Ruby does not load a Module, as in the object FileUtils that is in memory. It loads the file "fileutils.rb" from your hard drive. The ".rb" is omitted by convention but you could write require 'fileutils.rb'.

The purpose of require in Ruby is to load a file only once, as opposed to load which will reload the file every time it is used. The way require avoids loading a file multiple times is by recording the filename argument and skipping it if it if that filename is passed again.

When you first require a file, Ruby responds with true to indicate that it was loaded. If you require the same file again it will return false to indicate that it was already loaded:

```<code>> require 'fileutils'
=> true
> require 'fileutils'
=> false
</code>```

Since the filename stored by require is case-sensitive, but the actual file lookup is not, fileutils.rb will still be found if you use caps in the name:

```<code>> require 'FileUtils'
=> true
</code>```

But if something in your Ruby program already loaded that file without caps (in your case "yaml.rb" probably requires "fileutils" as well) you will reload the file and may see warnings:

```<code>> require 'fileutils'
=> true
> require 'FileUtils'
/bin/ruby/lib/ruby/2.3.0/FileUtils.rb:96: warning: already initialized constant FileUtils::OPT_TABLE
etc.
</code>```

By convention Ruby files should be named in lowercase with underscores, e.g. "my_class.rb", so you would always use require 'my_class'.

Things get a little trickier if you are requiring using absolute or relative paths, e.g. require 'special_classes/my_class'. I suggest reading about require_relative and the Ruby load path ($LOAD_PATH).

ContentLicense: CC BY-SA 3.0

Body:
I've seen similar questions regarding this error, but all of them rails-related. I'm not using rails; I'm working on a local rake task that reads from a yaml file and then does stuff with the data. I'd rather not install bundler for this (the solutions for the similar rails issues suggest prepending with bundle exec), since this script is simple and thus shouldn't need it.

Here's the simplified code, (which gets the same error as the code I'm working on):

require 'FileUtils'
require 'yaml'

SOME_FILE = "#{Dir.pwd}/some_file.yaml"

task default: :foo

task :foo do
  bar = File.open(SOME_FILE) { |yf| YAML::load( yf ) }
  bar.each {|k,v| puts k}
end

And here's the list of errors:

/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:93: warning: already initialized constant FileUtils::OPT_TABLE
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:93: warning: previous definition of OPT_TABLE was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1272: warning: already initialized constant FileUtils::Entry_::S_IF_DOOR
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1272: warning: previous definition of S_IF_DOOR was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1535: warning: already initialized constant FileUtils::Entry_::DIRECTORY_TERM
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1535: warning: previous definition of DIRECTORY_TERM was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1537: warning: already initialized constant FileUtils::Entry_::SYSCASE
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1537: warning: previous definition of SYSCASE was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1656: warning: already initialized constant FileUtils::LOW_METHODS
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1656: warning: previous definition of LOW_METHODS was here
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/FileUtils.rb:1662: warning: already initialized constant FileUtils::METHODS
/Users/jpalmieri/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/fileutils.rb:1662: warning: previous definition of METHODS was here

The script will run fine despite the warnings; the above code would puts the keys as expected, right after the warnings.

Body:
Wanted to answer this clearly (two years after it was asked) in case anyone wanders in here.

First, note that require in Ruby does not load a Module, as in the object FileUtils that is in memory. It loads the file "fileutils.rb" from your hard drive. The ".rb" is omitted by convention but you could write require 'fileutils.rb'.

The purpose of require in Ruby is to load a file only once, as opposed to load which will reload the file every time it is used. The way require avoids loading a file multiple times is by recording the filename argument and skipping it if it if that filename is passed again.

When you first require a file, Ruby responds with true to indicate that it was loaded. If you require the same file again it will return false to indicate that it was already loaded:

> require 'fileutils'
=> true
> require 'fileutils'
=> false

Since the filename stored by require is case-sensitive, but the actual file lookup is not, fileutils.rb will still be found if you use caps in the name:

> require 'FileUtils'
=> true

But if something in your Ruby program already loaded that file without caps (in your case "yaml.rb" probably requires "fileutils" as well) you will reload the file and may see warnings:

> require 'fileutils'
=> true
> require 'FileUtils'
/bin/ruby/lib/ruby/2.3.0/FileUtils.rb:96: warning: already initialized constant FileUtils::OPT_TABLE
etc.

By convention Ruby files should be named in lowercase with underscores, e.g. "my_class.rb", so you would always use require 'my_class'.

Things get a little trickier if you are requiring using absolute or relative paths, e.g. require 'special_classes/my_class'. I suggest reading about require_relative and the Ruby load path ($LOAD_PATH).


问:
Java For Loop Unreachable Code
I have a for loop in my code that's giving an error on the entire loop itself, saying it's "unreachable code". I'm completely unsure about what's causing this with this loop:

```<code>public ArrayList<Double> Update(ArrayList<Double> addInputs)
{
// stores the resultant outputs from each layer

ArrayList<Double> outputs = null;

int cWeight = 0;

// first check that we have the correct amount of inputs

if (addInputs.size() != numInputs);
{
    // just return an empty vector if incorrect
    return outputs;
}

// For each layer....

for (int i = 0; i < numHiddenLayers + 1; ++i)
{
    if (i > 0)
    {
        addInputs = outputs;
    }

    outputs.clear();

    cWeight = 0;

    // for each neuron sum the (inputs * corresponding weights) .Throw

    // the total at our sigmoid function to get the output.

    for (int j = 0; j < neuronLayers.get(i).numNeurons; ++j)
    {
        double netinput = 0;

        int numberInputs = neuronLayers.get(i).listNeurons.get(j).numInputs;

    // for each weight

    for (int k = 0; k < numberInputs - 1; ++k)
    {
        // sum the weights x inputs

        netinput += neuronLayers.get(i).listNeurons.get(j).weights.get(k) *
                addInputs.get(cWeight++);
    }

    // add in the bias

    netinput += neuronLayers.get(i).listNeurons.get(j).weights.get(numberInputs - 1)
            *  dBias;

    // we can store the outputs from each layer as we generate them.

    // the combined activation is first filtered through the sigmoid

    //function

    outputs.add(sigmoid(netinput,dActivationResponse));
    }
}
</code>```

It's claiming the entire for loop after

```<code>// For each layer....
</code>```

is unreachable code. Any help would be greatly appreciated.

答:
You have a semicolon here, so the method is always returning outputs. Just remove it

```<code>if (addInputs.size() != numInputs); // <---- this one
{
    // just return an empty vector if incorrect
    return outputs;
}
</code>```

Title: Java For Loop Unreachable Code

Body:
I have a for loop in my code that's giving an error on the entire loop itself, saying it's "unreachable code". I'm completely unsure about what's causing this with this loop:

public ArrayList<Double> Update(ArrayList<Double> addInputs)
{
// stores the resultant outputs from each layer

ArrayList<Double> outputs = null;

int cWeight = 0;

// first check that we have the correct amount of inputs

if (addInputs.size() != numInputs);
{
    // just return an empty vector if incorrect
    return outputs;
}

// For each layer....

for (int i = 0; i < numHiddenLayers + 1; ++i)
{
    if (i > 0)
    {
        addInputs = outputs;
    }

    outputs.clear();

    cWeight = 0;

    // for each neuron sum the (inputs * corresponding weights) .Throw

    // the total at our sigmoid function to get the output.

    for (int j = 0; j < neuronLayers.get(i).numNeurons; ++j)
    {
        double netinput = 0;

        int numberInputs = neuronLayers.get(i).listNeurons.get(j).numInputs;

    // for each weight

    for (int k = 0; k < numberInputs - 1; ++k)
    {
        // sum the weights x inputs

        netinput += neuronLayers.get(i).listNeurons.get(j).weights.get(k) *
                addInputs.get(cWeight++);
    }

    // add in the bias

    netinput += neuronLayers.get(i).listNeurons.get(j).weights.get(numberInputs - 1)
            *  dBias;

    // we can store the outputs from each layer as we generate them.

    // the combined activation is first filtered through the sigmoid

    //function

    outputs.add(sigmoid(netinput,dActivationResponse));
    }
}

It's claiming the entire for loop after

// For each layer....

is unreachable code. Any help would be greatly appreciated.

Body:
You have a semicolon here, so the method is always returning outputs. Just remove it

if (addInputs.size() != numInputs); // <---- this one
{
    // just return an empty vector if incorrect
    return outputs;
}


问:
Permissioning in Hyperlededger Fabric Composer transactions
I have two Participants A and B, each have their own identity issued to them by the CA

There is a transaction that enables one Participant to transfer Coins to the other.

```<code>participant Person identified by id {
    o String id
    o String firstName
    o String lastName
    o Double coins
}
</code>```

The transaction cto file

```<code>transaction TransferCoins {
    o Double coinsTransferred
    --> Person receiver
    --> Person sender
}
</code>```

The permissions.acl file

```<code>rule PersonCanModifyOnlySelf {
    description: "Allow Persons to modify only their profile"
    participant(p): "org.varun.business.Person"
    operation: READ, UPDATE, DELETE
    resource(r): "org.varun.business.Person"
    condition: (r.getIdentifier() === p.getIdentifier())
    action: ALLOW
}

rule PersonCanReadAllProfile {
    description: "Allow Persons read access to other Persons"
    participant: "org.varun.business.Person"
    operation: READ
    resource: "org.varun.business.Person"
    action: ALLOW
}
</code>```

The transaction.js file

```<code>/**
 * Person to Person transaction
 * @param {org.varun.business.TransferCoins} transferCoins
 * @transaction
 */
function TransferCoins(transferCoins) {

    var coinsToTransfer = transferCoins.coinsTransferred;
    transferCoins.sender.coins = transferCoins.sender.coins - coinsToTransfer;
    transferCoins.receiver.coins = transferCoins.receiver.coins + coinsToTransfer;

    return getParticipantRegistry('org.varun.business.Person')
        .then(registry => {
            return registry.updateAll([transferCoins.sender, transferCoins.receiver]);
        })
}
</code>```

In short

Each Person can only update their own profile

Each Person has universal read access

When the TransferCoins function is called, coins are subtracted from A while coins are added to B. The participant registry is called and updated.

Now If A were to call this transaction, I am getting an error saying A cannot update B's coins (Obviously due to acl defined above). So how does this kind of transaction work? Could someone please help me out.

答:
I see, at asset level as well. A transaction is submitted with one identity. In your case, participant A's. If ACLs restrict him/her to its own record, then that regime makes it hard for a transaction processor to achieve what you want in a single blockchain transaction.

So is it possible to submit the transaction with a party, that is not tied to A or B but can update both? That might be the best way. The transaction history would be used to see what changes occurred once the transaction is committed.

A listing record pairing sender and receiver and timestamp etc, could also be recorded as part of the same transaction logic if need be (for the purposes of reporting or otherwise).

Body:
I have two Participants A and B, each have their own identity issued to them by the CA

There is a transaction that enables one Participant to transfer Coins to the other.

participant Person identified by id {
    o String id
    o String firstName
    o String lastName
    o Double coins
}

The transaction cto file

transaction TransferCoins {
    o Double coinsTransferred
    --> Person receiver
    --> Person sender
}

The permissions.acl file

rule PersonCanModifyOnlySelf {
    description: "Allow Persons to modify only their profile"
    participant(p): "org.varun.business.Person"
    operation: READ, UPDATE, DELETE
    resource(r): "org.varun.business.Person"
    condition: (r.getIdentifier() === p.getIdentifier())
    action: ALLOW
}

rule PersonCanReadAllProfile {
    description: "Allow Persons read access to other Persons"
    participant: "org.varun.business.Person"
    operation: READ
    resource: "org.varun.business.Person"
    action: ALLOW
}

The transaction.js file

/**
 * Person to Person transaction
 * @param {org.varun.business.TransferCoins} transferCoins
 * @transaction
 */
function TransferCoins(transferCoins) {

    var coinsToTransfer = transferCoins.coinsTransferred;
    transferCoins.sender.coins = transferCoins.sender.coins - coinsToTransfer;
    transferCoins.receiver.coins = transferCoins.receiver.coins + coinsToTransfer;

    return getParticipantRegistry('org.varun.business.Person')
        .then(registry => {
            return registry.updateAll([transferCoins.sender, transferCoins.receiver]);
        })
}

In short

Each Person can only update their own profile

Each Person has universal read access

When the TransferCoins function is called, coins are subtracted from A while coins are added to B. The participant registry is called and updated.

Now If A were to call this transaction, I am getting an error saying A cannot update B's coins (Obviously due to acl defined above). So how does this kind of transaction work? Could someone please help me out.


答:
You have a semicolon at the end of your if:

```<code>... != numInputs);
</code>```

Meaning the return underneath it will always happen, making the code under it unreachable.

Remove the semicolon.

Title: Java For Loop Unreachable Code

Body:
You have a semicolon at the end of your if:

... != numInputs);

Meaning the return underneath it will always happen, making the code under it unreachable.

Remove the semicolon.


问:
passing data frame to mutate within function
I would like to pass a data frame and its columns to be processed by dplyr's mutate within a function.

Here is an example

```<code>multifun <- function(dataf,vari){
 mutate(dataf,newvar=vari*2)
}

multifun(mtcars,gear)
</code>```

The problem with this function is that the variable 'gear' is not a recognized object. More specifically I get the error

Error in mutate_impl(.data, named_dots(...), environment()) object
  'gear' not found

This is a problem with the environment where dplyr's mutate is looking for the variable in question.

I understand that

```<code>multifun(mtcars,mtcars$gear)
</code>```

will give me the answer that I want, namely

```<code>    mpg  cyl  disp  hp   drat  wt   qsec  vs am   gear carb newvar
1  21.0   6   160.0 110  3.90 2.620 16.46  0  1    4    4      8
2  21.0   6   160.0 110  3.90 2.875 17.02  0  1    4    4      8
3  22.8   4   108.0  93  3.85 2.320 18.61  1  1    4    1      8
</code>```

but I would like to see if there is a way of avoiding the need to reference each variable used from the data frame in the function call.

I am also aware that taking mutate out of the function call works without problems. Namely, mutate(mtcars,newvar=gear*2) does the job. However, I am trying to understand how dplyr's mutate is looking for the variable in question in the different environments when placed inside a function.

答:
With dplyr 0.7.0, this can now be done with tidyeval:

```<code>multifun <- function(dataf,vari){
  mutate(dataf,newvar = UQ(enquo(vari))*2)
}

multifun(mtcars,gear)
</code>```

enquo quotes the symbol referring to the function argument and bundles it with the environment in which the function is being called into a quosure. UQ or !! can then be used to unquote the quosure and evaluate it immediately within mutate.

ContentLicense: CC BY-SA 4.0

Body:
I would like to pass a data frame and its columns to be processed by dplyr's mutate within a function.

Here is an example

multifun <- function(dataf,vari){
 mutate(dataf,newvar=vari*2)
}

multifun(mtcars,gear)

The problem with this function is that the variable 'gear' is not a recognized object. More specifically I get the error

Error in mutate_impl(.data, named_dots(...), environment()) object
  'gear' not found

This is a problem with the environment where dplyr's mutate is looking for the variable in question.

I understand that

multifun(mtcars,mtcars$gear)

will give me the answer that I want, namely

    mpg  cyl  disp  hp   drat  wt   qsec  vs am   gear carb newvar
1  21.0   6   160.0 110  3.90 2.620 16.46  0  1    4    4      8
2  21.0   6   160.0 110  3.90 2.875 17.02  0  1    4    4      8
3  22.8   4   108.0  93  3.85 2.320 18.61  1  1    4    1      8

but I would like to see if there is a way of avoiding the need to reference each variable used from the data frame in the function call.

I am also aware that taking mutate out of the function call works without problems. Namely, mutate(mtcars,newvar=gear*2) does the job. However, I am trying to understand how dplyr's mutate is looking for the variable in question in the different environments when placed inside a function.

Body:
With dplyr 0.7.0, this can now be done with tidyeval:

multifun <- function(dataf,vari){
  mutate(dataf,newvar = UQ(enquo(vari))*2)
}

multifun(mtcars,gear)

enquo quotes the symbol referring to the function argument and bundles it with the environment in which the function is being called into a quosure. UQ or !! can then be used to unquote the quosure and evaluate it immediately within mutate.


问:
active menu item - asp.net mvc3 master page
I've been scanning around trying to find an appropriate solution for assigning "active/current" class to menu items from the master page.  The line is split down the middle with regards of whether to do this client vs server side.

Truthfully I'm new to both JavaScript and MVC so i don't have an opinion. I would prefer to do this in the "cleanest" and most appropriate way.

I have the following jQuery code to assign the "active" class to the
 item...the only problem is the "index" or default view menu item will always be assigned the active class, because the URL is always a substring of the other menu links:

```<code>(default) index = localhost/
link 1 = localhost/home/link1
link 2 = localhost/home/link1

$(function () {
 var str = location.href.toLowerCase();
  $('#nav ul li a').each(function() {
   if (str.indexOf(this.href.toLowerCase()) > -1) {
    $(this).parent().attr("class","active"); //hightlight parent tab
   }
});
</code>```

Is there a better way of doing this, guys?  Would someone at least help me get the client-side version bulletproof? So that the "index" or default link is always "active"? Is there a way of assigning a fake extension to the index method?  like instead of just the base URL it would be localhost/home/dashboard so that it wouldn't be a substring of every link?

Truthfully, i don't really follow the methods of doing this server-side, which is why I'm trying to do it client side with jQuery...any help would be appreciated.

答:
A custom HTML helper usually does the job fine:

```<code>public static MvcHtmlString MenuLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName
)
{
    string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
    string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
    if (actionName == currentAction && controllerName == currentController)
    {
        return htmlHelper.ActionLink(
            linkText,
            actionName,
            controllerName,
            null,
            new {
                @class = "current"
            });
    }
    return htmlHelper.ActionLink(linkText, actionName, controllerName);
}
</code>```

and in your master page:

```<code><ul>
    <li>@Html.MenuLink("Link 1", "link1", "Home")</li>
    <li>@Html.MenuLink("Link 2", "link2", "Home")</li>
</ul>
</code>```

Now all that's left is define the .current CSS class.

Body:
I've been scanning around trying to find an appropriate solution for assigning "active/current" class to menu items from the master page.  The line is split down the middle with regards of whether to do this client vs server side.

Truthfully I'm new to both JavaScript and MVC so i don't have an opinion. I would prefer to do this in the "cleanest" and most appropriate way.

I have the following jQuery code to assign the "active" class to the
 item...the only problem is the "index" or default view menu item will always be assigned the active class, because the URL is always a substring of the other menu links:

(default) index = localhost/
link 1 = localhost/home/link1
link 2 = localhost/home/link1

$(function () {
 var str = location.href.toLowerCase();
  $('#nav ul li a').each(function() {
   if (str.indexOf(this.href.toLowerCase()) > -1) {
    $(this).parent().attr("class","active"); //hightlight parent tab
   }
});

Is there a better way of doing this, guys?  Would someone at least help me get the client-side version bulletproof? So that the "index" or default link is always "active"? Is there a way of assigning a fake extension to the index method?  like instead of just the base URL it would be localhost/home/dashboard so that it wouldn't be a substring of every link?

Truthfully, i don't really follow the methods of doing this server-side, which is why I'm trying to do it client side with jQuery...any help would be appreciated.

Body:
A custom HTML helper usually does the job fine:

public static MvcHtmlString MenuLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName
)
{
    string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
    string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
    if (actionName == currentAction && controllerName == currentController)
    {
        return htmlHelper.ActionLink(
            linkText,
            actionName,
            controllerName,
            null,
            new {
                @class = "current"
            });
    }
    return htmlHelper.ActionLink(linkText, actionName, controllerName);
}

and in your master page:

<ul>
    <li>@Html.MenuLink("Link 1", "link1", "Home")</li>
    <li>@Html.MenuLink("Link 2", "link2", "Home")</li>
</ul>

Now all that's left is define the .current CSS class.

ContentLicense: CC BY-SA 2.5


问:
possible lossy conversion float to int in foreach-loop
I was trying to write the following code that is supposed to calculate the average of all numbers in an array, and we're supposed to use the foreach-loop!
The problem is that the compiler tells me about lossy conversions from float to int in line 3 ("    for(int k: numbers)" ).

Casting k to float doesn't work, casting numbers doesn't work ('f course), and casting everything else doesn't seem to work either!
Where is the problem, please help!

Thanks in advance!

```<code>float calculateAverage(float[] numbers){
    float a = 0.0f;
    for(int k: numbers){
        (a) = a+numbers[k];
    }
    return a/(numbers.length-1);

}
</code>```

答:
So, here you hold each element of numbers in k in turn, adding them into a. You then return the value of a divided by the number of elements in the array:

```<code>float calculatedAverage(float[] numbers){
    float a = 0.0f;
    for (float k : numbers) {
        a += k;
    }
    return a / numbers.length;
}
</code>```

The enhanced for loop doesn't use a counter variable so there's no need to be accessing numbers[] with an index.

Body:
I was trying to write the following code that is supposed to calculate the average of all numbers in an array, and we're supposed to use the foreach-loop!
The problem is that the compiler tells me about lossy conversions from float to int in line 3 ("    for(int k: numbers)" ).

Casting k to float doesn't work, casting numbers doesn't work ('f course), and casting everything else doesn't seem to work either!
Where is the problem, please help!

Thanks in advance!

float calculateAverage(float[] numbers){
    float a = 0.0f;
    for(int k: numbers){
        (a) = a+numbers[k];
    }
    return a/(numbers.length-1);

}

Body:
So, here you hold each element of numbers in k in turn, adding them into a. You then return the value of a divided by the number of elements in the array:

float calculatedAverage(float[] numbers){
    float a = 0.0f;
    for (float k : numbers) {
        a += k;
    }
    return a / numbers.length;
}

The enhanced for loop doesn't use a counter variable so there's no need to be accessing numbers[] with an index.


问:
POST list of objects in rails. How can I whitelist the list of objects in strong params?
I'm trying to post a list of objects called tasks that looks like the following.

```<code>{
  // Shared attributes
  "parent_id": "1",
  "author": "Name Name",
  // Task list
  "tasks": [
   {"name":"task 1"},
   {"name":"task 2"}...
  ]
}
</code>```

In my controller, I have the following, which iterates through tasks, appends the shared attributes, and creates a new Task object:

```<code>task_params[:tasks].each do |task|
      new_params = task
      new_params[:parent_id] = task_params[:parent_id]
      new_params[:author] = task_params[:author]

      new_task = Task.new(new_params)
end
</code>```

The problem is that :tasks isn't showing up in my task_params despite being passed in as a parameter. This seems to be because it isn't whitelisted in strong_params, but that doesn't seem to make a difference. It looks to me like I can only whitelist parameters that correspond to attr_accessors. So how can I pass in the custom parameter tasks through strong_params and into the controller method?

Edit:

My params definition:

```<code>def task_params
     params.require(:task).permit(:parent_id, :author, tasks: [:name])
end
</code>```

Rails output:

```<code>  Parameters: {"parent_id"=>1, "author"=> "Name name", "tasks"=>[{"name"=>"task 1"}, {"name"=>"task 2"}], "task"=>{"job_id"=>1, "author"=>"Name name"}}
</code>```

But when I print the task params in the controller:

```<code>{"parent_id"=>1, "author"=>"Name name"}
</code>```

答:
Look at the documentation on nested parameters with Strong Parameters. You'd do something like:</p>

```<code>params.permit(:parent_id, :author, tasks: [:name])
</code>```

Body:
I'm trying to post a list of objects called tasks that looks like the following.

{
  // Shared attributes
  "parent_id": "1",
  "author": "Name Name",
  // Task list
  "tasks": [
   {"name":"task 1"},
   {"name":"task 2"}...
  ]
}

In my controller, I have the following, which iterates through tasks, appends the shared attributes, and creates a new Task object:

task_params[:tasks].each do |task|
      new_params = task
      new_params[:parent_id] = task_params[:parent_id]
      new_params[:author] = task_params[:author]

      new_task = Task.new(new_params)
end

The problem is that :tasks isn't showing up in my task_params despite being passed in as a parameter. This seems to be because it isn't whitelisted in strong_params, but that doesn't seem to make a difference. It looks to me like I can only whitelist parameters that correspond to attr_accessors. So how can I pass in the custom parameter tasks through strong_params and into the controller method?

Edit:

My params definition:

def task_params
     params.require(:task).permit(:parent_id, :author, tasks: [:name])
end

Rails output:

  Parameters: {"parent_id"=>1, "author"=> "Name name", "tasks"=>[{"name"=>"task 1"}, {"name"=>"task 2"}], "task"=>{"job_id"=>1, "author"=>"Name name"}}

But when I print the task params in the controller:

{"parent_id"=>1, "author"=>"Name name"}

Body:
Look at the documentation on nested parameters with Strong Parameters. You'd do something like:

params.permit(:parent_id, :author, tasks: [:name])


问:
Realm - module file was created by an older version of compiler
I use latest version of xcode and swift 2.2. One of my projects, which I havent open for several month now not building, because of error
module file was created by an older version of compiler

I tried the following

Removed realm frameworks from project, then download the latest version from realm.io and copy the new frameworks to project

Building realm by build.sh build from github sources with REALM_SWIFT_VERSION=2.2 and adding to project

Neither of these helped, still got error.

Any advices ?

答: I faced the same issue when used Swift 3.2 in my project. After upgrading to Swift 4.0 issue disappeared. Cleaning project folder, derived data, restarting Mac - nothing helped.</p>


问:
How can I merge overlapping strings in python?
I have some strings,

```<code>['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']
</code>```

These strings partially overlap each other. If you manually overlapped them you would get:

```<code>SGALWDVPSPV
</code>```

I want a way to go from the list of overlapping strings to the final compressed string in python.  I feel like this must be a problem that someone has solved already and am trying to avoid reinventing the wheel.  The methods I can imagine now are either brute force or involve getting more complicated by using biopython and sequence aligners than I would like.  I have some simple short strings and just want to properly merge them in a simple way.

Does anyone have any advice on a nice way to do this in python?  Thanks!

答:
Here is a quick sorting solution:

```<code>s = ['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']
new_s = sorted(s, key=lambda x:s[0].index(x[0]))
a = new_s[0]
b = new_s[-1]
final_s = a[:a.index(b[0])]+b
</code>```

Output:

```<code>'SGALWDVPSPV'
</code>```

This program sorts s by the value of the index of the first character of each element, in an attempt to find the string that will maximize the overlap distance between the first element and the desired output.

Body:
I have some strings,

['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']

These strings partially overlap each other. If you manually overlapped them you would get:

SGALWDVPSPV

I want a way to go from the list of overlapping strings to the final compressed string in python.  I feel like this must be a problem that someone has solved already and am trying to avoid reinventing the wheel.  The methods I can imagine now are either brute force or involve getting more complicated by using biopython and sequence aligners than I would like.  I have some simple short strings and just want to properly merge them in a simple way.

Does anyone have any advice on a nice way to do this in python?  Thanks!

Body:
Here is a quick sorting solution:

s = ['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']
new_s = sorted(s, key=lambda x:s[0].index(x[0]))
a = new_s[0]
b = new_s[-1]
final_s = a[:a.index(b[0])]+b

Output:

'SGALWDVPSPV'

This program sorts s by the value of the index of the first character of each element, in an attempt to find the string that will maximize the overlap distance between the first element and the desired output.


问:
IO.File.GetLastAccessTime is off by one hour
I'm working on a program that records date metadata from files, such as creation time, last modified time, etc. An old version of the program is written in VBA, and does something like this:

```<code>Public Function GetFileLastAccessTime(ByVal FilePath As String) As Date
    Dim fso As New Scripting.FileSystemObject
    Dim f As Scripting.File
    Set f = fso.GetFile(FilePath)
    GetFileLastAccessTime = f.DateLastAccessed
End Function
</code>```

Output for the file in question:

```<code>?getfilelastaccesstime("SomePath")
7/30/2010 2:16:07 PM
</code>```

That is the value I get from the file properties in Windows Exploder. Happiness.

I'm porting this functionality to a VB.Net app. The new code:

```<code>Public Function GetLastAccessTime(ByVal FilePath As String) As Date
    Return IO.File.GetLastAccessTime(FilePath)
End Function
</code>```

Simplicity itself. The output:

```<code>?GetLastAccessTime("SomePath")
#7/30/2010 3:16:07 PM#
</code>```

One hour later.

Both functions are running on the same machine, checking the same file. I've also tried using the IO.FileInfo class with the same result. I've checked thousands of files and they are all off by one hour. The other date properties for creation time and last modified time are also off by one hour.

Help!

I forgot to mention in the original post, The computer's time zone is CST, and daylight savings time is currently not in effect.

I've reproduced the problem on Windows 7 64 bit and Windows XP 32 bit.

Thanks.

1/6/2011 update:

Thanks to everyone who suggested trying to calculate the desired date from UTC using the appropriate time zone offsets. At this time I'm deciding its not worth the risk to do so. For this particular business requirement, its much better to say the date value is not what you expected it to be because thats just the way the API works. If I attempt to "fix" this then I own it, and I'd rather not.

Just for kicks I tried using the good old Scripting.FileSystemObject via interop. It gives the expected results that agree with Windows Explorer, with about a 5x performance penalty compared to System.IO. If it turns out I must get dates that match what Windows Explorer has, I will bite the bullet and go this route.

Another experiment I tried was going directly to the GetFileTime API function in kernel32 via C#:

```<code>[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetFileTime(
IntPtr hFile,
ref FILETIME lpCreationTime,
ref FILETIME lpLastAccessTime,
ref FILETIME lpLastWriteTime
);
</code>```

That resulted in exactly the same behavior System.IO had, the time was off by an hour from Windows Explorer.

Thanks again everyone.

答:
I encountered this problem as well, and I believe I understand what is happening.

I have a Powershell script and a CMD script (using the DIR command) that reports the modified date/time of files. After the recent change from Daylight to Standard time, the Powershell script was reporting the time of files created before the time change as one hour later than the DIR command. Windows Explorer reported the same time as Powershell.

Since NTFS file timestamps are stored as UTC, they are convered to local time for display/output. It appears that the DIR command uses the current time zone offset from UTC when displaying the time (+8, since I'm in Pacific time zone and it's now standard time), while Powershell (and Windows Explorer) is using the local time offset THAT WAS IN EFFECT at the time of the timestamp (when the files were created), which was UTC +7, since it was still daylight time.

I think the Powershell conversion is correct. I suppose you can argue either way, but if you look at the timestamp before and after a daylight time change, Powershell results would be the same, while DIR results would be different, and inconsistent.

Body:
I'm working on a program that records date metadata from files, such as creation time, last modified time, etc. An old version of the program is written in VBA, and does something like this:

Public Function GetFileLastAccessTime(ByVal FilePath As String) As Date
    Dim fso As New Scripting.FileSystemObject
    Dim f As Scripting.File
    Set f = fso.GetFile(FilePath)
    GetFileLastAccessTime = f.DateLastAccessed
End Function

Output for the file in question:

?getfilelastaccesstime("SomePath")
7/30/2010 2:16:07 PM

That is the value I get from the file properties in Windows Exploder. Happiness.

I'm porting this functionality to a VB.Net app. The new code:

Public Function GetLastAccessTime(ByVal FilePath As String) As Date
    Return IO.File.GetLastAccessTime(FilePath)
End Function

Simplicity itself. The output:

?GetLastAccessTime("SomePath")
#7/30/2010 3:16:07 PM#

One hour later.

Both functions are running on the same machine, checking the same file. I've also tried using the IO.FileInfo class with the same result. I've checked thousands of files and they are all off by one hour. The other date properties for creation time and last modified time are also off by one hour.

Help!

I forgot to mention in the original post, The computer's time zone is CST, and daylight savings time is currently not in effect.

I've reproduced the problem on Windows 7 64 bit and Windows XP 32 bit.

Thanks.

1/6/2011 update:

Thanks to everyone who suggested trying to calculate the desired date from UTC using the appropriate time zone offsets. At this time I'm deciding its not worth the risk to do so. For this particular business requirement, its much better to say the date value is not what you expected it to be because thats just the way the API works. If I attempt to "fix" this then I own it, and I'd rather not.

Just for kicks I tried using the good old Scripting.FileSystemObject via interop. It gives the expected results that agree with Windows Explorer, with about a 5x performance penalty compared to System.IO. If it turns out I must get dates that match what Windows Explorer has, I will bite the bullet and go this route.

Another experiment I tried was going directly to the GetFileTime API function in kernel32 via C#:

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetFileTime(
IntPtr hFile,
ref FILETIME lpCreationTime,
ref FILETIME lpLastAccessTime,
ref FILETIME lpLastWriteTime
);

That resulted in exactly the same behavior System.IO had, the time was off by an hour from Windows Explorer.

Thanks again everyone.


问:
LazyInitializationException for some of requests
This is probably a duplicate, but I am struggling with this problem for few days now. After dozens of tutorials, books, stack answers etc I am in the dead end.

This is RESTfull Spring hibernate app

How to eliminate lazyinitializationexception and problems with Session? I tried to set eager fetch in model class, but it didn't work for me, I have Transaction annotations but its still the same. I bet that it must be set somehow in Spring xml config, but have no clue how to do that.

Why ... /getAllCountries works perfectly fine, and /getCountry/id throw Session error? I see no difference between them.

Please give me a code based answer.

Controller:

```<code>    @RestController
    public class CountryController {

        @Autowired
        CountryService countryService;

        @RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/json")
        public List<Country> getCountries() {
            List<Country> listOfCountries = countryService.getAllCountries();
            return listOfCountries;
        }

        @RequestMapping(value = "/getCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
        public Country getCountryById(@PathVariable int id) {
            return countryService.getCountry(id);
        }

        // .....
    }
</code>```

DAO:

```<code>@Repository
public class CountryDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf) {
        this.sessionFactory = sf;
    }

    public List<Country> getAllCountries() {
         Session session = this.sessionFactory.getCurrentSession();
         List<Country> countryList = session.createQuery("from Country").list();
    return countryList;
    }

    public Country getCountry(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Country country = (Country) session.load(Country.class, new Integer(id));
        return country;
    }
    // ......
}
</code>```

Service:

```<code>@Service("countryService")
public class CountryService {

    @Autowired
    CountryDAO countryDao;

    @Transactional
    public List<Country> getAllCountries() {
        return countryDao.getAllCountries();
    }

    @Transactional
    public Country getCountry(int id) {
        return countryDao.getCountry(id);
    }
}
</code>```

Entity:

```<code>@Entity
@Table(name="COUNTRY")
public class Country{

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;

    @Column(name="countryName")
    String countryName;

    @Column(name="population")
    long population;

    public Country() {
            super();
    }
    public Country(int i, String countryName,long population) {
        super();
        this.id = i;
        this.countryName = countryName;
        this.population=population;
    }

    // getters and setters...
}
</code>```

Spring config xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <annotation-driven />

    <resources mapping="/resources/**" location="/resources/" />

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <beans:property name="driverClassName" value="org.postgresql.Driver" />
            <beans:property name="url"
                    value="..." />
            <beans:property name="username" value="postgres" />
            <beans:property name="password" value="..." />
    </beans:bean>

    <!-- Hibernate 4 SessionFactory Bean definition -->
    <beans:bean id="hibernate4AnnotatedSessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <beans:property name="dataSource" ref="dataSource" />
            <beans:property name="annotatedClasses">
                    <beans:list>
                            <beans:value>org.arpit.java2blog.model.Country</beans:value>
                    </beans:list>
            </beans:property>
            <beans:property name="hibernateProperties">
                    <beans:props>
                            <beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
                            </beans:prop>
                            <beans:prop key="hibernate.show_sql">true</beans:prop>
                    </beans:props>
            </beans:property>
    </beans:bean>

    <context:component-scan base-package="org.arpit.java2blog" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
</beans:beans>
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
 <servlet-name>spring</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>spring</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>
</code>```

答:
Your problem comes from the Session.load() method that doesn't return an object but a proxy of the object which is initialized at the first access of an non-identifier property.

Hibernate Documentation:

 T load(Class theClass,
             Serializable id)

Return the persistent instance of the given entity class with the given  identifier, assuming that the
  instance exists. This method might return a proxied instance that is
  initialized on-demand, when a non-identifier method is accessed.

And for you it means it's initialized when Spring will try to marshall the object, which is when the Session is close.

To fix it you can either add @org.hibernate.annotations.Proxy(lazy = false) on the class level, use Session.get() instead of Session.load() in the dao to get a fully loaded object (depending on the lazy strategy on members).

Or manually trigger the lazy loading when the Session is still like by calling any member of the object (like calling List.size() on a collection to force the loading).

Body:
This is probably a duplicate, but I am struggling with this problem for few days now. After dozens of tutorials, books, stack answers etc I am in the dead end.

This is RESTfull Spring hibernate app

How to eliminate lazyinitializationexception and problems with Session? I tried to set eager fetch in model class, but it didn't work for me, I have Transaction annotations but its still the same. I bet that it must be set somehow in Spring xml config, but have no clue how to do that.

Why ... /getAllCountries works perfectly fine, and /getCountry/id throw Session error? I see no difference between them.

Please give me a code based answer.

Controller:

    @RestController
    public class CountryController {

        @Autowired
        CountryService countryService;

        @RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/json")
        public List<Country> getCountries() {
            List<Country> listOfCountries = countryService.getAllCountries();
            return listOfCountries;
        }

        @RequestMapping(value = "/getCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
        public Country getCountryById(@PathVariable int id) {
            return countryService.getCountry(id);
        }

        // .....
    }

DAO:

@Repository
public class CountryDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf) {
        this.sessionFactory = sf;
    }

    public List<Country> getAllCountries() {
         Session session = this.sessionFactory.getCurrentSession();
         List<Country> countryList = session.createQuery("from Country").list();
    return countryList;
    }

    public Country getCountry(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Country country = (Country) session.load(Country.class, new Integer(id));
        return country;
    }
    // ......
}

Service:

@Service("countryService")
public class CountryService {

    @Autowired
    CountryDAO countryDao;

    @Transactional
    public List<Country> getAllCountries() {
        return countryDao.getAllCountries();
    }

    @Transactional
    public Country getCountry(int id) {
        return countryDao.getCountry(id);
    }
}

Entity:

@Entity
@Table(name="COUNTRY")
public class Country{

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;

    @Column(name="countryName")
    String countryName;

    @Column(name="population")
    long population;

    public Country() {
            super();
    }
    public Country(int i, String countryName,long population) {
        super();
        this.id = i;
        this.countryName = countryName;
        this.population=population;
    }

    // getters and setters...
}

Spring config xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <annotation-driven />

    <resources mapping="/resources/**" location="/resources/" />

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <beans:property name="driverClassName" value="org.postgresql.Driver" />
            <beans:property name="url"
                    value="..." />
            <beans:property name="username" value="postgres" />
            <beans:property name="password" value="..." />
    </beans:bean>

    <beans:bean id="hibernate4AnnotatedSessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <beans:property name="dataSource" ref="dataSource" />
            <beans:property name="annotatedClasses">
                    <beans:list>
                            <beans:value>org.arpit.java2blog.model.Country</beans:value>
                    </beans:list>
            </beans:property>
            <beans:property name="hibernateProperties">
                    <beans:props>
                            <beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
                            </beans:prop>
                            <beans:prop key="hibernate.show_sql">true</beans:prop>
                    </beans:props>
            </beans:property>
    </beans:bean>

    <context:component-scan base-package="org.arpit.java2blog" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
</beans:beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
 <servlet-name>spring</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>spring</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>


问:
Allow video on landscape with only-portrait app
I have a UIWebView included in a UIViewController which is a descendant of UINavigationController. It looks like this:

The app is portrait only. When I play the video I want the user to be able to rotate the device and see the video in landscape mode. I use this code to allow it:

```<code>- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    id presentedViewController = [self topMostController];
    NSString *className = presentedViewController ? NSStringFromClass([presentedViewController class]) : nil;

    if ([className isEqualToString:@"MPInlineVideoFullscreenViewController"] ||
        [className isEqualToString:@"MPMoviePlayerViewController"] ||
        [className isEqualToString:@"AVFullScreenViewController"]) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }

    return UIInterfaceOrientationMaskPortrait;
}

- (UIViewController *)topMostController {
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}
</code>```

And then in my UINavigationController (so when the video finishes the view is not presented in landscape but only in portrait):

```<code>- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
</code>```

Everything works perfectly:

But then the video is done playing (or the user taps ‘Done’) and the screens return to the underlying view, this is what happens:

As you can see, the navigation bar slips under the status bar.
Additionally, I get a lot of auto-layout errors in the logs: http://pastebin.com/09xHzmgJ

Any idea about how to solve this?

答:
On iOS 11 accepted solution didn't work for me. Seems that navigation bar stops reflecting for frame changes. But there is a workaround. At first, we need to modify supportedInterfaceOrientationsForWindow method to return UIInterfaceOrientationMaskLandscape for video controllers instead of UIInterfaceOrientationMaskAllButUpsideDown. In my case when I tap on embedded YouTube video, system always opens AVFullScreenViewController, so I removed other checks from original example. Code:

```<code>- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    __kindof UIViewController *presentedViewController = [self topMostController];

    // Allow rotate videos
    NSString *className = presentedViewController ? NSStringFromClass([presentedViewController class]) : nil;
    if ([className isEqualToString:@"AVFullScreenViewController"]) {
        return UIInterfaceOrientationMaskLandscape;
    }

    return UIInterfaceOrientationMaskPortrait;
}
</code>```

This didn't changes behaviour of AVFullScreenViewController on iOS 10 and less, but fixes navigation bar on iOS 11, so there is no need to update frame (also there is a side-effect on iOS 11 that video rotates from landscape when starts playing, but it's a tradeoff). Next, we need to add check in UIWindowDidBecomeHiddenNotification method:

```<code>- (void)videoDidExitFullscreen {
    if (@available(iOS 11, *)) {
        // Fixes status bar on iPhone X
        [self setNeedsStatusBarAppearanceUpdate];
    } else {
        self.navigationController.navigationBar.frame = CGRectMake(0, 0, self.view.bounds.size.width, statusAndNavBarHeight);
    }
}
</code>```

Without setNeedsStatusBarAppearanceUpdate text in status bar will not appear on iPhone X, for other devices it's not needed.

Body:
I have a UIWebView included in a UIViewController which is a descendant of UINavigationController. It looks like this:

The app is portrait only. When I play the video I want the user to be able to rotate the device and see the video in landscape mode. I use this code to allow it:

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    id presentedViewController = [self topMostController];
    NSString *className = presentedViewController ? NSStringFromClass([presentedViewController class]) : nil;

    if ([className isEqualToString:@"MPInlineVideoFullscreenViewController"] ||
        [className isEqualToString:@"MPMoviePlayerViewController"] ||
        [className isEqualToString:@"AVFullScreenViewController"]) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }

    return UIInterfaceOrientationMaskPortrait;
}

- (UIViewController *)topMostController {
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

And then in my UINavigationController (so when the video finishes the view is not presented in landscape but only in portrait):

- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

Everything works perfectly:

But then the video is done playing (or the user taps ‘Done’) and the screens return to the underlying view, this is what happens:

As you can see, the navigation bar slips under the status bar.
Additionally, I get a lot of auto-layout errors in the logs: http://pastebin.com/09xHzmgJ

Any idea about how to solve this?

Body:
On iOS 11 accepted solution didn't work for me. Seems that navigation bar stops reflecting for frame changes. But there is a workaround. At first, we need to modify supportedInterfaceOrientationsForWindow method to return UIInterfaceOrientationMaskLandscape for video controllers instead of UIInterfaceOrientationMaskAllButUpsideDown. In my case when I tap on embedded YouTube video, system always opens AVFullScreenViewController, so I removed other checks from original example. Code:

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    __kindof UIViewController *presentedViewController = [self topMostController];

    // Allow rotate videos
    NSString *className = presentedViewController ? NSStringFromClass([presentedViewController class]) : nil;
    if ([className isEqualToString:@"AVFullScreenViewController"]) {
        return UIInterfaceOrientationMaskLandscape;
    }

    return UIInterfaceOrientationMaskPortrait;
}

This didn't changes behaviour of AVFullScreenViewController on iOS 10 and less, but fixes navigation bar on iOS 11, so there is no need to update frame (also there is a side-effect on iOS 11 that video rotates from landscape when starts playing, but it's a tradeoff). Next, we need to add check in UIWindowDidBecomeHiddenNotification method:

- (void)videoDidExitFullscreen {
    if (@available(iOS 11, *)) {
        // Fixes status bar on iPhone X
        [self setNeedsStatusBarAppearanceUpdate];
    } else {
        self.navigationController.navigationBar.frame = CGRectMake(0, 0, self.view.bounds.size.width, statusAndNavBarHeight);
    }
}

Without setNeedsStatusBarAppearanceUpdate text in status bar will not appear on iPhone X, for other devices it's not needed.


问:
How to convert ascii code to byte in golang?
As the title say, I can find the function to give me ascii code of bytes, but not the other way around</p>

答:
Golang string literals are UTF-8 and since ASCII is a subset of UTF-8, and each of its characters are only 7 bits, we can easily get them as bytes by casting (e.g. bytes := []byte(str):

```<code>package main

import "fmt"

func main() {
  asciiStr := "ABC"
  asciiBytes := []byte(asciiStr)

  fmt.Printf("OK: string=%v, bytes=%v\n", asciiStr, asciiBytes)
  fmt.Printf("OK: byte(A)=%v\n", asciiBytes[0])
}
// OK: string=ABC, bytes=[65 66 67]
// OK: byte(A)=65
</code>```

Body:
Golang string literals are UTF-8 and since ASCII is a subset of UTF-8, and each of its characters are only 7 bits, we can easily get them as bytes by casting (e.g. bytes := []byte(str):

package main

import "fmt"

func main() {
  asciiStr := "ABC"
  asciiBytes := []byte(asciiStr)

  fmt.Printf("OK: string=%v, bytes=%v\n", asciiStr, asciiBytes)
  fmt.Printf("OK: byte(A)=%v\n", asciiBytes[0])
}
// OK: string=ABC, bytes=[65 66 67]
// OK: byte(A)=65


问:
Adding a table tag via JavaScript with a dashed parameter
I am trying to add a Bootstrap Table table tag with Javascript. One of the parameters for the table tag is data-pagination. This method of adding it, is failing due to the -.

How can I work around this?

Desired Output:

```<code><table id="mytable" data-pagination="true" class="table table-striped"></table>
</code>```

My code:

```<code>var table_div = document.createElement('table');
table_div.id = 'mytable';
table_div.className = "table table-striped";
table_div.data-pagination = "true";
document.body.appendChild(table_div);
</code>```

Body:
I am trying to add a Bootstrap Table table tag with Javascript. One of the parameters for the table tag is data-pagination. This method of adding it, is failing due to the -.

How can I work around this?

Desired Output:

My code:

var table_div = document.createElement('table');
table_div.id = 'mytable';
table_div.className = "table table-striped";
table_div.data-pagination = "true";
document.body.appendChild(table_div);

Body: table_div.setAttribute('data-pagination', 'true')