Exemple #1
0
    def displayPrepare(self, env):
        '''
        准备数据
        :param env: 当前环境
        :return: 
        '''
        self.env = env
        if not self.cf.isReady():
            print(Fore.RED + '配置项尚未初始化!')
        else:
            self.boxParams = VBox()
            self.boxParams.layout = Layout(flex_flow = 'column', display = 'flex')
            self.packageWidgets()
            display(self.boxParams)

            self.gdParamValue = qgrid.show_grid(pd.DataFrame([]),
                                                grid_options = {'filterable': False, 'autoHeight': True,
                                                                'editable': False})
            self.gdParamValue.layout = Layout(width = '90%')
            self.packageParams()
            self.txtBodyValue = Textarea(value = self.data if self.data is not None else '')
            self.txtBodyValue.layout = Layout(width = '90%', height = '200px', margin = '6px 2px 2px 2px')

            boxRequest = Box([
                VBox([Label(value = '请求参数值:'), self.gdParamValue],
                     layout = Layout(flex = '1 1 0%', width = 'auto')),
                VBox([Label(value = '请求体参数值:'), self.txtBodyValue],
                     layout = Layout(flex = '1 1 0%', width = 'auto'))],
                layout = Layout(flex_flow = 'row', display = 'flex'))
            acRef = Accordion(children = [boxRequest])
            acRef.set_title(0, '输入参考')
            toggleRefDisplay(acRef)
            display(acRef)
            ref.append(acRef)
Exemple #2
0
    def __init__(self):
        self.setting = self.create_settings()
        self.keyword = Textarea(
            value='',
            placeholder='Search dictionary and press enter',
            description='',
            disabled=False,
            rows=1,
            layout=Layout(width='50%'))
        self.search_button = self.create_button('search')
        self.save_button = self.create_button('save file')
        self.out = Output()
        self.results = {}

        self.search_button.on_click(self.search)
        self.save_button.on_click(self.save_file)
        self.keyword.observe(self.adjust_keyword_size, 'value')
Exemple #3
0
    def packageWidgets(self):
        '''
        打包组件
        :return: 
        '''
        debug.out('package request widgets')
        self.paramWidgets = {}
        self.txtBody = None
        for param, ptype in self.interface['params'].items():
            value = self.cf.readConf(self.default['interface'], param)
            if ptype == 'int':
                pw = IntText(description = param + ':',
                             value = value if value is not None else 0,
                             layout = Layout(width = '90%'))
            elif ptype == 'date':
                pw = DatePicker(description = param + ':',
                                value = value if value is not None else '',
                                layout = Layout(width = '90%'))
            elif ptype == 'companyId':
                pw = Text(description = param + ':',
                          value = value if value is not None else self.env.tester['companyId'],
                          layout = Layout(width = '90%'))
            elif ptype == 'openId':
                pw = Text(description = param + ':',
                          value = value if value is not None else self.env.tester['openId'],
                          layout = Layout(width = '90%'))
            else:
                pw = Text(description = param + ':',
                          value = value if value is not None else '',
                          layout = Layout(width = '90%'))
            pw.observe(self.on_param_change)
            self.paramWidgets[param] = pw

        self.txtBody = Textarea(description = 'body data:', value = '')
        self.txtBody.layout = Layout(display = 'none')

        debug.out(self.interface.get('body', False))
        if self.interface.get('body', False) != False:
            debug.out('interface have body data to package widget')
            value = self.cf.readConf(self.default['interface'], 'body')
            self.txtBody.value = value if value is not None else ''
            self.txtBody.layout = Layout(width = '90%', height = '200px')

        tmpWds = [wd for wd in self.paramWidgets.values()]
        tmpWds.append(self.txtBody)
        self.boxParams.children = tmpWds
Exemple #4
0
def run_gromacs(simulation, directory, clean=False):
    if clean is False and os.path.exists(directory):
        raise ValueError(
            'Cannot override {}, use option clean=True'.format(directory))
    else:
        shutil.rmtree(directory, ignore_errors=True)
        os.mkdir(directory)

    # Parameter file
    mdpfile = to_mdp(simulation)
    with open(os.path.join(directory, 'grompp.mdp'), 'w') as fd:
        fd.write(mdpfile)

    # Topology file
    topfile = to_top(simulation.system, simulation.potential)
    with open(os.path.join(directory, 'topol.top'), 'w') as fd:
        fd.write(topfile)

    # Simulation file
    datafile(os.path.join(directory, 'conf.gro'),
             'w').write('system', simulation.system)

    process = subprocess.Popen(
        'cd {} && grompp_d && exec mdrun_d -v'.format(directory),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True)

    output_box = Textarea()
    output_box.height = '200px'
    output_box.font_family = 'monospace'
    output_box.color = '#AAAAAA'
    output_box.background_color = 'black'
    output_box.width = '800px'
    display(output_box)

    def output_function(text, output_box=output_box):
        output_box.value += text.decode('utf8')
        output_box.scroll_to_bottom()

    return AsyncCalculation(process, simulation, directory, output_function)
Exemple #5
0
 def __init__(self, qNo):
     self.qNo = qNo
     self.qOut = Output()
     self.queryArea = Textarea(
         value='',
         placeholder='Type your Query here',
         description='',
         disabled=False,
         #layout = Layout(max_width='30%')
     )
     self.execute = Button(
         description='Execute',
         disabled=False,
         button_style='',  # 'success', 'info', 'warning', 'danger' or ''
         tooltip='Execute',
         #layout = Layout(max_width='20%')
     )
     self.resultMessage = Output()
     self.execute.on_click(self.executeQuery)
     self.yourOutput = Output(layout=Layout())
     self.expectedOutput = Output(layout=Layout())
     self.yourOut = Output()
     self.expectOut = Output()
     with self.yourOut:
         display(HTML('<b>Your Ouput:</b>'))
     with self.expectOut:
         display(HTML('<b>Expected Ouput:</b>'))
     self.disPlayWindow = VBox([HBox([self.qOut,self.queryArea,self.execute,self.resultMessage]),\
     VBox([VBox([self.expectOut,self.expectedOutput]\
                ),VBox([self.yourOut,self.yourOutput])])]\
                               ,layout = Layout(width='80%'))
     self.qset = pd.read_csv('questions.csv')
     self.questionData = self.qset.loc[self.qset.qNo == self.qNo]
     expected = self.getExpected()
     with self.expectedOutput:
         display(expected)
     with self.qOut:
         print(self.questionData.question.values[0])
Exemple #6
0
def run_gromacs(simulation, directory, clean=False):
    if clean is False and os.path.exists(directory):
        raise ValueError("Cannot override {}, use option clean=True".format(directory))
    else:
        shutil.rmtree(directory, ignore_errors=True)
        os.mkdir(directory)

    # Parameter file
    mdpfile = to_mdp(simulation)
    with open(os.path.join(directory, "grompp.mdp"), "w") as fd:
        fd.write(mdpfile)

    # Topology file
    topfile = to_top(simulation.system, simulation.potential)
    with open(os.path.join(directory, "topol.top"), "w") as fd:
        fd.write(topfile)

    # Simulation file
    datafile(os.path.join(directory, "conf.gro"), "w").write("system", simulation.system)

    process = subprocess.Popen(
        "cd {} && grompp_d && exec mdrun_d -v".format(directory),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
    )

    output_box = Textarea()
    output_box.height = "200px"
    output_box.font_family = "monospace"
    output_box.color = "#AAAAAA"
    output_box.background_color = "black"
    output_box.width = "800px"
    display(output_box)

    def output_function(text, output_box=output_box):
        output_box.value += text.decode("utf8")
        output_box.scroll_to_bottom()

    return AsyncCalculation(process, simulation, directory, output_function)
Exemple #7
0
def RGB_colourspace_models_transformation_matrix_widget():

    title_Label = Label('RGB Colourspace Models Transformation Matrix')
    title_Label.add_class('widget-title')

    default_layout = {'flex': '1 1 auto', 'width': 'auto'}
    input_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    output_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    chromatic_adaptation_transforms_Dropdown = Dropdown(
        options=sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS),
        layout=default_layout)

    formatter_Dropdown = Dropdown(
        options=['str', 'repr', 'Nuke'], layout=default_layout)

    decimals_IntSlider = IntSlider(value=10, max=15, layout=default_layout)

    RGB_to_RGB_matrix_Textarea = Textarea(rows=3, layout=default_layout)
    RGB_to_RGB_matrix_Textarea.add_class('widget-output-textarea')

    def set_RGB_to_RGB_matrix_Textarea():
        M = colour.RGB_to_RGB_matrix(
            colour.RGB_COLOURSPACES[input_colourspace_Dropdown.value],
            colour.RGB_COLOURSPACES[output_colourspace_Dropdown.value],
            chromatic_adaptation_transforms_Dropdown.value)

        with colour.utilities.numpy_print_options(
                formatter={
                    'float':
                    ('{{:0.{0}f}}'.format(decimals_IntSlider.value)).format
                },
                threshold=np.nan):
            if formatter_Dropdown.value == 'str':
                M = str(M)
            elif formatter_Dropdown.value == 'repr':
                M = repr(M)
            else:
                M = NUKE_COLORMATRIX_NODE_TEMPLATE.format(
                    nuke_format_matrix(M, decimals_IntSlider.value),
                    '{0}_to_{1}'.format(
                        input_colourspace_Dropdown.value.replace(' ', '_'),
                        output_colourspace_Dropdown.value.replace(' ', '_')))

            RGB_to_RGB_matrix_Textarea.rows = len(M.split('\n'))
            RGB_to_RGB_matrix_Textarea.value = M

    def on_input_change(change):
        if change['type'] == 'change' and change['name'] == 'value':
            set_RGB_to_RGB_matrix_Textarea()

    input_colourspace_Dropdown.observe(on_input_change)
    output_colourspace_Dropdown.observe(on_input_change)
    chromatic_adaptation_transforms_Dropdown.observe(on_input_change)
    formatter_Dropdown.observe(on_input_change)
    decimals_IntSlider.observe(on_input_change)

    set_RGB_to_RGB_matrix_Textarea()

    widget = Box([
        VBox(
            [
                title_Label,
                Textarea(
                    'This widget computes the colour transformation '
                    'matrix from the Input RGB Colourspace to the '
                    'Output RGB Colourspace using the given '
                    'Chromatic Adaptation Transform.',
                    rows=2,
                    layout=default_layout),
                Label('Input RGB Colourspace'),
                input_colourspace_Dropdown,
                Label('Output RGB Colourspace'),
                output_colourspace_Dropdown,
                Label('Chromatic Adaptation Transform'),
                chromatic_adaptation_transforms_Dropdown,
                Label('Formatter'),
                formatter_Dropdown,
                HBox([Label('Decimals:'), decimals_IntSlider]),
                Label('RGB Transformation Matrix'),
                RGB_to_RGB_matrix_Textarea,
            ],
            layout={
                'border': 'solid 2px',
                'width': '55%'
            })
    ])

    return widget
Exemple #8
0
def RGB_colourspace_models_chromatically_adapted_primaries_widget():

    title_Label = Label(
        'RGB Colourspace Models Chromatically Adapted Primaries')
    title_Label.add_class('widget-title')

    default_layout = {'flex': '1 1 auto', 'width': 'auto'}
    input_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    illuminant_Dropdown = Dropdown(
        options=sorted(
            colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']),
        layout=default_layout)

    chromatic_adaptation_transforms_Dropdown = Dropdown(
        options=sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS),
        layout=default_layout)

    formatter_Dropdown = Dropdown(
        options=['str', 'repr'], layout=default_layout)

    decimals_IntSlider = IntSlider(value=10, max=15, layout=default_layout)

    primaries_Textarea = Textarea(rows=3, layout=default_layout)
    primaries_Textarea.add_class('widget-output-textarea')

    def set_primaries_Textarea():
        input_colourspace = colour.RGB_COLOURSPACES[
            input_colourspace_Dropdown.value]

        P = colour.chromatically_adapted_primaries(
            input_colourspace.primaries, input_colourspace.whitepoint,
            colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][
                illuminant_Dropdown.value],
            chromatic_adaptation_transforms_Dropdown.value)

        with colour.utilities.numpy_print_options(
                formatter={
                    'float':
                    ('{{:0.{0}f}}'.format(decimals_IntSlider.value)).format
                },
                threshold=np.nan):
            if formatter_Dropdown.value == 'str':
                P = str(P)
            elif formatter_Dropdown.value == 'repr':
                P = repr(P)

            primaries_Textarea.rows = len(P.split('\n'))
            primaries_Textarea.value = P

    def on_input_change(change):
        if change['type'] == 'change' and change['name'] == 'value':
            set_primaries_Textarea()

    input_colourspace_Dropdown.observe(on_input_change)
    illuminant_Dropdown.observe(on_input_change)
    chromatic_adaptation_transforms_Dropdown.observe(on_input_change)
    formatter_Dropdown.observe(on_input_change)
    decimals_IntSlider.observe(on_input_change)

    set_primaries_Textarea()

    widget = Box([
        VBox(
            [
                title_Label,
                Textarea(
                    'This widget computes the Chromatically Adapted Primaries '
                    'of the given RGB Colourspace Model to the given '
                    'Illuminant using the '
                    'given Chromatic Adaptation Transform.',
                    rows=3,
                    layout=default_layout),
                Label('Input RGB Colourspace'),
                input_colourspace_Dropdown,
                Label('Illuminant'),
                illuminant_Dropdown,
                Label('Chromatic Adaptation Transform'),
                chromatic_adaptation_transforms_Dropdown,
                Label('Formatter'),
                formatter_Dropdown,
                HBox([Label('Decimals:'), decimals_IntSlider]),
                Label('RGB Transformation Matrix'),
                primaries_Textarea,
            ],
            layout={
                'border': 'solid 2px',
                'width': '55%'
            })
    ])

    return widget
Exemple #9
0
class UI:
    def __init__(self):
        self.setting = self.create_settings()
        self.keyword = Textarea(
            value='',
            placeholder='Search dictionary and press enter',
            description='',
            disabled=False,
            rows=1,
            layout=Layout(width='50%'))
        self.search_button = self.create_button('search')
        self.save_button = self.create_button('save file')
        self.out = Output()
        self.results = {}

        self.search_button.on_click(self.search)
        self.save_button.on_click(self.save_file)
        self.keyword.observe(self.adjust_keyword_size, 'value')

    def adjust_keyword_size(self, event):
        self.keyword.rows = self.keyword.value.count('\n') + 1

    def save_file(self, event):
        filename = 'result.txt'
        with open(filename, 'w') as fp:
            self.show_result(file=fp)
        self.out.clear_output()

    def get_config(self):
        return {
            'dictionary': [
                dict_name.description
                for dict_name in self.setting[1, 1].children if dict_name.value
            ],
            'fields': {
                'Cambridge': {
                    'word': {
                        dict_name.description: dict_name.value
                        for dict_name in self.setting[3, 1].children
                    },
                    'phrase': {
                        dict_name.description: dict_name.value
                        for dict_name in self.setting[4, 1].children
                    }
                },
                'Merriam': {
                    dict_name.description: dict_name.value
                    for dict_name in self.setting[5, 1].children
                },
                'Etymology': {
                    dict_name.description: dict_name.value
                    for dict_name in self.setting[6, 1].children
                },
                'translate': {
                    dict_name.description: dict_name.value
                    for dict_name in self.setting[7, 1].children
                }
            }
        }

    def show_result(self, event=None, file=sys.stdout):
        if not self.results:
            return
        self.out.clear_output()
        fields = self.get_config()['fields']
        word_field = fields['Cambridge']['word']
        phrase_field = fields['Cambridge']['phrase']
        translate = fields['translate']['requirment']
        with self.out:
            for keyword, result in self.results.items():
                myprint(keyword + ':', end='\n', file=file)
                myprint('*' * 10, end='\n', file=file)
                for word in result.get('Cambridge', []):
                    myprint(word['text'], head=4, file=file)
                    myprint('(part-of-speech: {})'.format(word['pos'])
                            if word_field['pos'] else '',
                            end='\n',
                            file=file)

                    defines = word['defines'] if word_field['define'] else []
                    for idx, define in enumerate(defines):
                        grammar = define.get('grammar',
                                             word.get('grammar', None))
                        myprint('define {}: {}'.format(
                            idx, define['define']['text']),
                                head=8,
                                file=file)
                        myprint('({})'.format(define['define']['translate']) if
                                translate and define['define']['text'] else '',
                                head=1,
                                file=file)
                        myprint('[{}]'.format(grammar)
                                if word_field['grammar'] else '',
                                end='\n',
                                head=1,
                                file=file)

                        examples = define['examples'] if word_field[
                            'examples'] else []
                        for ex_idx, example in enumerate(examples):
                            myprint('- example {}: {}'.format(
                                ex_idx, example['text']),
                                    head=12,
                                    file=file)
                            myprint('({})'.format(example['translate'])
                                    if translate and example['text'] else '',
                                    end='\n',
                                    head=1,
                                    file=file)

                        phrases = define['phrases'] if phrase_field[
                            'text'] else []
                        for ph_idx, phrase in enumerate(phrases):
                            myprint('* phrase {}: {}'.format(
                                ph_idx, phrase['phrase']),
                                    head=12,
                                    end='\n',
                                    file=file)
                            myprint('define: {}'.format(
                                phrase['define']['text']
                                if phrase_field['define'] else ''),
                                    head=16,
                                    file=file)
                            myprint(
                                '({})'.format(phrase['define']['translate']) if
                                translate and phrase_field['define'] else '',
                                end='\n',
                                head=1,
                                file=file)

                            examples = phrase['examples'] if phrase_field[
                                'examples'] else []
                            for ex_idx, example in enumerate(examples):
                                myprint('- example {}: {}'.format(
                                    ex_idx, example['text']),
                                        head=20,
                                        file=file)
                                myprint('({})'.format(
                                    example['translate']
                                    if translate and example['text'] else ''),
                                        end='\n',
                                        head=1,
                                        file=file)
                    myprint(end='\n', file=file)

                merriam_field = fields['Merriam']
                if result.get('Merriam') and (merriam_field['first use']
                                              or merriam_field['etymology']):
                    myprint('In Merriam webster:', end='\n', head=4, file=file)
                    if merriam_field['first use']:
                        myprint('First known use:',
                                head=8,
                                end='\n',
                                file=file)
                        self.print_merriam(
                            result['Merriam']['first_known_use'], file=file)

                    if merriam_field['etymology']:
                        myprint('Etymology:', head=8, end='\n', file=file)
                        self.print_merriam(result['Merriam']['etymology'],
                                           file=file)

                etymology_field = fields['Etymology']
                if result.get('Etymology') and (
                        etymology_field['description']
                        or etymology_field['image(if any)']):
                    myprint('In etymology online:',
                            end='\n',
                            head=4,
                            file=file)
                    if etymology_field['description']:
                        myprint('Description:', head=8, end='\n', file=file)
                        data = result['Etymology']['text']
                        myprint(data if data else 'No data',
                                head=12,
                                end='\n',
                                file=file)
                    if etymology_field['image(if any)'] and result[
                            'Etymology']['image_url']:
                        display(
                            Image(
                                requests.get(
                                    result['Etymology']['image_url']).content))
                        myprint(end='\n', file=file)
                myprint('=' * 75, end='\n', file=file)

    def print_merriam(self, data, file=sys.stdout):
        if data:
            for d in data:
                if d['type']:
                    myprint('part-of-speech: {}'.format(d['type']),
                            head=12,
                            end='\n',
                            file=file)
                myprint(d['text'], head=12, end='\n', file=file)
                myprint(file=file)
        else:
            myprint(data if data else 'No data', head=8, end='\n', file=file)

    def search(self, event):
        self.out.clear_output()
        config = self.get_config()
        dict_names = config['dictionary']
        engine = {
            'Cambridge':
            CamBridge('chinese-traditional' if config['fields']['translate']
                      ['requirment'] else None),
            'Merriam':
            MerriamWebster(),
            'Etymology':
            OnlineEtymology()
        }
        if self.keyword.value:
            self.results = {}
            with self.out:
                for keyword in self.keyword.value.split('\n'):
                    print('search {}...'.format(keyword))
                    self.results[keyword] = {
                        dict_name: engine[dict_name].search(keyword.strip())
                        for dict_name in dict_names
                    }
                self.show_result()
        else:
            with self.out:
                print('The keyword in search bar is required.')

    def create_settings(self):
        word = self.create_checkbox('define', 'pos', 'grammar', 'examples')
        phrase = self.create_checkbox('text', 'define', 'examples')
        dictionary = self.create_checkbox('Cambridge', 'Merriam', 'Etymology')
        merriam = self.create_checkbox('first use', 'etymology')
        etymology = self.create_checkbox('description', 'image(if any)')
        translate = self.create_checkbox('requirment')

        setting = GridspecLayout(8, 6)
        setting[0, 2] = Label('settings')
        setting[1, 1:len(dictionary) + 1] = Box(dictionary)
        setting[1, 0] = Label('dictionary')
        setting[2, 2] = Label('output')
        setting[3, 0] = Label('word')
        setting[3, 1:len(word) + 1] = Box(word)
        setting[4, 0] = Label('phrase')
        setting[4, 1:len(phrase) + 1] = Box(phrase)
        setting[5, 0] = Label('Merriam')
        setting[5, 1:len(merriam) + 1] = Box(merriam)
        setting[6, 0] = Label('Etymology')
        setting[6, 1:len(etymology) + 1] = Box(etymology)
        setting[7, 0] = Label('Translate')
        setting[7, 1:len(translate) + 1] = Box(translate)
        return setting

    def create_checkbox(self, *options, default=True):
        box = [
            Checkbox(value=default,
                     description=dict_name,
                     disabled=False,
                     indent=False) for dict_name in options
        ]
        for c in box:
            c.observe(self.show_result)
        return box

    def create_button(self, name):
        button = Button(description=name,
                        disabled=False,
                        button_style='info',
                        tooltip='Click me',
                        icon='')
        return button

    def run(self):
        display(self.keyword)
        display(self.search_button)
        display(self.setting)
        display(self.save_button)
        display(self.out)

        style = """
            <style>
            .jupyter-widgets-output-area .output_scroll {
                height: unset !important;
                border-radius: unset !important;
                -webkit-box-shadow: unset !important;
                box-shadow: unset !important;
            }
            .jupyter-widgets-output-area  {
                  height: auto !important;
            }
         </style>
        """
        display(HTML(style))