query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
how to make the checkbox checked
python
def assert_checked_checkbox(self, value): """Assert the checkbox with label (recommended), name or id is checked.""" check_box = find_field(world.browser, 'checkbox', value) assert check_box, "Cannot find checkbox '{}'.".format(value) assert check_box.is_selected(), "Check box should be selected."
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L564-L568
how to make the checkbox checked
python
def checkbox_check(self, force_check=False): """ Wrapper to check a checkbox """ if not self.get_attribute('checked'): self.click(force_click=force_check)
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L655-L660
how to make the checkbox checked
python
def check_checkbox(self, value): """Check the checkbox with label (recommended), name or id.""" check_box = find_field(world.browser, 'checkbox', value) assert check_box, "Cannot find checkbox '{}'.".format(value) if not check_box.is_selected(): check_box.click()
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L542-L547
how to make the checkbox checked
python
def set_checkbox(self, data, uncheck_other_boxes=True): """Set the *checked*-attribute of input elements of type "checkbox" specified by ``data`` (i.e. check boxes). :param data: Dict of ``{name: value, ...}``. In the family of checkboxes whose *name*-attribute is ``name``, check the box whose *value*-attribute is ``value``. All boxes in the family can be checked (unchecked) if ``value`` is True (False). To check multiple specific boxes, let ``value`` be a tuple or list. :param uncheck_other_boxes: If True (default), before checking any boxes specified by ``data``, uncheck the entire checkbox family. Consider setting to False if some boxes are checked by default when the HTML is served. """ for (name, value) in data.items(): # Case-insensitive search for type=checkbox checkboxes = self.find_by_type("input", "checkbox", {'name': name}) if not checkboxes: raise InvalidFormMethod("No input checkbox named " + name) # uncheck if requested if uncheck_other_boxes: self.uncheck_all(name) # Wrap individual values (e.g. int, str) in a 1-element tuple. if not isinstance(value, list) and not isinstance(value, tuple): value = (value,) # Check or uncheck one or more boxes for choice in value: choice_str = str(choice) # Allow for example literal numbers for checkbox in checkboxes: if checkbox.attrs.get("value", "on") == choice_str: checkbox["checked"] = "" break # Allow specifying True or False to check/uncheck elif choice is True: checkbox["checked"] = "" break elif choice is False: if "checked" in checkbox.attrs: del checkbox.attrs["checked"] break else: raise LinkNotFoundError( "No input checkbox named %s with choice %s" % (name, choice) )
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L99-L146
how to make the checkbox checked
python
def checkbox_uncheck(self, force_check=False): """ Wrapper to uncheck a checkbox """ if self.get_attribute('checked'): self.click(force_click=force_check)
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L662-L667
how to make the checkbox checked
python
def set_checkbox_value(w, value): """ Sets a checkbox's "checked" property + signal blocking + value tolerance Args: w: QCheckBox instance value: something that can be converted to a bool """ save = w.blockSignals(True) try: w.setChecked(bool(value)) finally: w.blockSignals(save)
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/xmisc.py#L558-L570
how to make the checkbox checked
python
def check(self, locator=None, allow_label_click=None, **kwargs): """ Find a check box and mark it as checked. The check box can be found via name, id, or label text. :: page.check("German") Args: locator (str, optional): Which check box to check. allow_label_click (bool, optional): Attempt to click the label to toggle state if element is non-visible. Defaults to :data:`capybara.automatic_label_click`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ self._check_with_label( "checkbox", True, locator=locator, allow_label_click=allow_label_click, **kwargs)
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L44-L59
how to make the checkbox checked
python
def set_checked(self, value=True, block_events=False): """ This will set whether the button is checked. Setting block_events=True will temporarily disable signals from the button when setting the value. """ if block_events: self._widget.blockSignals(True) self._widget.setChecked(value) if block_events: self._widget.blockSignals(False) return self
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L915-L926
how to make the checkbox checked
python
def check(self, data): """For backwards compatibility, this method handles checkboxes and radio buttons in a single call. It will not uncheck any checkboxes unless explicitly specified by ``data``, in contrast with the default behavior of :func:`~Form.set_checkbox`. """ for (name, value) in data.items(): try: self.set_checkbox({name: value}, uncheck_other_boxes=False) continue except InvalidFormMethod: pass try: self.set_radio({name: value}) continue except InvalidFormMethod: pass raise LinkNotFoundError("No input checkbox/radio named " + name)
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L80-L97
how to make the checkbox checked
python
def setCheckable( self, state ): """ Sets whether or not this combobox stores checkable items. :param state | <bool> """ self._checkable = state # need to be editable to be checkable edit = self.lineEdit() if state: self.setEditable(True) edit.setReadOnly(True) # create connections model = self.model() model.rowsInserted.connect(self.adjustCheckState) model.dataChanged.connect(self.updateCheckedText) elif edit: edit.setReadOnly(False) self.updateCheckState() self.updateCheckedText()
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L395-L418
how to make the checkbox checked
python
def create_checkbox(self, name, margin=10): """ Function creates a checkbox with his name """ chk_btn = Gtk.CheckButton(name) chk_btn.set_margin_right(margin) return chk_btn
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L113-L119
how to make the checkbox checked
python
def action_checkbox(self, obj): """ A list_display column containing a checkbox widget. """ if self.check_concurrent_action: return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text("%s,%s" % (obj.pk, get_revision_of_object(obj)))) else: # pragma: no cover return super(ConcurrencyActionMixin, self).action_checkbox(obj)
https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/admin.py#L35-L44
how to make the checkbox checked
python
def check(self): """ Basic checks that don't depend on any context. Adapted from Bicoin Code: main.cpp """ self._check_tx_inout_count() self._check_txs_out() self._check_txs_in() # Size limits self._check_size_limit()
https://github.com/richardkiss/pycoin/blob/1e8d0d9fe20ce0347b97847bb529cd1bd84c7442/pycoin/coins/bitcoin/Tx.py#L268-L277
how to make the checkbox checked
python
def setChecked(src, ids=[], dpth = 0, key = ''): """ Recursively find checked item.""" #tabs = lambda n: ' ' * n * 4 # or 2 or 8 or... #brace = lambda s, n: '%s%s%s' % ('['*n, s, ']'*n) if isinstance(src, dict): for key, value in src.iteritems(): setChecked(value, ids, dpth + 1, key) elif isinstance(src, list): for litem in src: if isinstance(litem, types.DictType): if "id" in litem and litem["id"] in ids: litem["checked"] = True litem["select"] = True setChecked(litem, ids, dpth + 2)
https://github.com/joeferraro/mm/blob/43dce48a2249faab4d872c228ada9fbdbeec147b/mm/crawlJson.py#L70-L84
how to make the checkbox checked
python
def checkbox(self, model_view, id_, attr, value): """endpoint for checking/unchecking any boolean in a sqla model""" modelview_to_model = { '{}ColumnInlineView'.format(name.capitalize()): source.column_class for name, source in ConnectorRegistry.sources.items() } model = modelview_to_model[model_view] col = db.session.query(model).filter_by(id=id_).first() checked = value == 'true' if col: setattr(col, attr, checked) if checked: metrics = col.get_metrics().values() col.datasource.add_missing_metrics(metrics) db.session.commit() return json_success('OK')
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L1517-L1532
how to make the checkbox checked
python
def input_check(self, name, label, multi_line=False): """ {% if multiple_choice_1 %} {% set checked = "checked" %} {% else %} {% set checked = "" %} {% endif %} <input type="checkbox" name="multiple_choice_1" value="multiple_choice_1" {{checked}}> multiple_choice_1 """ lines = list() lines.append('{%% if %s %%}' % name) lines.append(self.tab + '{% set checked = "checked" %}') lines.append('{% else %}') lines.append(self.tab + '{% set checked = "" %}') lines.append('{% endif %}') if multi_line: line_break = "<br>" else: line_break = "" lines.append('<input type="checkbox" name="%s" value="%s" {{checked}}> %s %s' % (name, name, label, line_break)) return "\n".join(lines)
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/markup/html.py#L85-L105
how to make the checkbox checked
python
def setChecked(self, tocheck): """Sets the attributes *tocheck* as checked :param tocheck: attributes names to check :type tocheck: list<str> """ layout = self.layout() for i in range(layout.count()): w = layout.itemAt(i).widget() if w.text() in tocheck: w.setChecked(True)
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/component_detail.py#L153-L163
how to make the checkbox checked
python
def checkbox(message: Text, choices: List[Union[Text, Choice, Dict[Text, Any]]], default: Optional[Text] = None, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Ask the user to select from a list of items. This is a multiselect, the user can choose one, none or many of the items. Args: message: Question text choices: Items shown in the selection, this can contain `Choice` or or `Separator` objects or simple items as strings. Passing `Choice` objects, allows you to configure the item more (e.g. preselecting it or disabeling it). default: Default return value (single value). If you want to preselect multiple items, use `Choice("foo", checked=True)` instead. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """ merged_style = merge_styles([DEFAULT_STYLE, style]) ic = InquirerControl(choices, default) def get_prompt_tokens(): tokens = [] tokens.append(("class:qmark", qmark)) tokens.append(("class:question", ' {} '.format(message))) if ic.is_answered: nbr_selected = len(ic.selected_options) if nbr_selected == 0: tokens.append(("class:answer", ' done')) elif nbr_selected == 1: tokens.append(("class:answer", ' [{}]'.format( ic.get_selected_values()[0].title))) else: tokens.append(("class:answer", ' done ({} selections)'.format( nbr_selected))) else: tokens.append(("class:instruction", ' (Use arrow keys to move, ' '<space> to select, ' '<a> to toggle, ' '<i> to invert)')) return tokens layout = common.create_inquirer_layout(ic, get_prompt_tokens, **kwargs) bindings = KeyBindings() @bindings.add(Keys.ControlQ, eager=True) @bindings.add(Keys.ControlC, eager=True) def _(event): event.app.exit(exception=KeyboardInterrupt, style='class:aborting') @bindings.add(' ', eager=True) def toggle(event): pointed_choice = ic.get_pointed_at().value if pointed_choice in ic.selected_options: ic.selected_options.remove(pointed_choice) else: ic.selected_options.append(pointed_choice) @bindings.add('i', eager=True) def invert(event): inverted_selection = [c.value for c in ic.choices if not isinstance(c, Separator) and c.value not in ic.selected_options and not c.disabled] ic.selected_options = inverted_selection @bindings.add('a', eager=True) def all(event): all_selected = True # all choices have been selected for c in ic.choices: if (not isinstance(c, Separator) and c.value not in ic.selected_options and not c.disabled): # add missing ones ic.selected_options.append(c.value) all_selected = False if all_selected: ic.selected_options = [] @bindings.add(Keys.Down, eager=True) @bindings.add("j", eager=True) def move_cursor_down(event): ic.select_next() while not ic.is_selection_valid(): ic.select_next() @bindings.add(Keys.Up, eager=True) @bindings.add("k", eager=True) def move_cursor_up(event): ic.select_previous() while not ic.is_selection_valid(): ic.select_previous() @bindings.add(Keys.ControlM, eager=True) def set_answer(event): ic.is_answered = True event.app.exit(result=[c.value for c in ic.get_selected_values()]) @bindings.add(Keys.Any) def other(event): """Disallow inserting other text. """ pass return Question(Application( layout=layout, key_bindings=bindings, style=merged_style, **kwargs ))
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/checkbox.py#L23-L150
how to make the checkbox checked
python
def OnSecondaryCheckbox(self, event): """Top Checkbox event handler""" self.attrs["top"] = event.IsChecked() self.attrs["right"] = event.IsChecked() post_command_event(self, self.DrawChartMsg)
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_chart_dialog.py#L639-L645
how to make the checkbox checked
python
def has_checked_field(self, locator, **kwargs): """ Checks if the page or current node has a radio button or checkbox with the given label, value, or id, that is currently checked. Args: locator (str): The label, name, or id of a checked field. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: bool: Whether it exists. """ kwargs["checked"] = True return self.has_selector("field", locator, **kwargs)
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L614-L628
how to make the checkbox checked
python
def add_check(self, check): """Add a check into the scheduler checks list :param check: check to add :type check: alignak.check.Check :return: None """ if check is None: return if check.uuid in self.checks: logger.debug("Already existing check: %s", check) return logger.debug("Adding a check: %s", check) # Add a new check to the scheduler checks list self.checks[check.uuid] = check self.nb_checks += 1 # Raise a brok to inform about a next check is to come ... # but only for items that are actively checked item = self.find_item_by_id(check.ref) if item.active_checks_enabled: self.add(item.get_next_schedule_brok())
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L522-L544
how to make the checkbox checked
python
def _check_box_toggled(self, widget, data=None): """ Function manipulates with entries and buttons. """ active = widget.get_active() arg_name = data if 'entry' in self.args[arg_name]: self.args[arg_name]['entry'].set_sensitive(active) if 'browse_btn' in self.args[arg_name]: self.args[arg_name]['browse_btn'].set_sensitive(active) self.path_window.show_all()
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L238-L250
how to make the checkbox checked
python
def _check_with_label(self, selector, checked, locator=None, allow_label_click=None, visible=None, wait=None, **kwargs): """ Args: selector (str): The selector for the type of element that should be checked/unchecked. checked (bool): Whether the element should be checked. locator (str, optional): Which element to check. allow_label_click (bool, optional): Attempt to click the label to toggle state if element is non-visible. Defaults to :data:`capybara.automatic_label_click`. visible (bool | str, optional): The desired element visibility. Defaults to :data:`capybara.ignore_hidden_elements`. wait (int | float, optional): The number of seconds to wait to check the element. Defaults to :data:`capybara.default_max_wait_time`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ if allow_label_click is None: allow_label_click = capybara.automatic_label_click @self.synchronize(wait=BaseQuery.normalize_wait(wait)) def check_with_label(): element = None try: element = self.find(selector, locator, visible=visible, **kwargs) element.set(checked) except Exception as e: if not allow_label_click or not self._should_catch_error(e): raise try: if not element: element = self.find(selector, locator, visible="all", **kwargs) label = self.find("label", field=element, visible=True) if element.checked != checked: label.click() except Exception: raise e check_with_label()
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L197-L234
how to make the checkbox checked
python
def mark_checked(self, institute, case, user, link, unmark=False): """Mark a case as checked from an analysis point of view. Arguments: institute (dict): A Institute object case (dict): Case object user (dict): A User object link (str): The url to be used in the event unmark (bool): If case should ve unmarked Return: updated_case """ LOG.info("Updating checked status of {}" .format(case['display_name'])) status = 'not checked' if unmark else 'checked' self.create_event( institute=institute, case=case, user=user, link=link, category='case', verb='check_case', subject=status ) LOG.info("Updating {0}'s checked status {1}" .format(case['display_name'], status)) analysis_checked = False if unmark else True updated_case = self.case_collection.find_one_and_update( {'_id': case['_id']}, { '$set': {'analysis_checked': analysis_checked} }, return_document=pymongo.ReturnDocument.AFTER ) LOG.debug("Case updated") return updated_case
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/case_events.py#L482-L522
how to make the checkbox checked
python
def is_checked(self) -> bool: """One task ran (checked).""" if not self.redis_key_checked: return False value = self._red.get(self.redis_key_checked) if not value: return False return True
https://github.com/polyaxon/polyaxon/blob/e1724f0756b1a42f9e7aa08a976584a84ef7f016/polyaxon/db/redis/group_check.py#L37-L46
how to make the checkbox checked
python
def check(definition, data, *args, **kwargs): """Checks if the input follows the definition""" checker = checker_factory(definition) return checker(data, *args, **kwargs)
https://github.com/nesaro/pydsl/blob/00b4fffd72036b80335e1a44a888fac57917ab41/pydsl/check.py#L29-L32
how to make the checkbox checked
python
def checkbutton_with_label(self, description): """ The function creates a checkbutton with label """ act_btn = Gtk.CheckButton(description) align = self.create_alignment() act_btn.add(align) return align
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L97-L104
how to make the checkbox checked
python
def _check_inputs(self): ''' make some basic checks on the inputs to make sure they are valid''' try: _ = self._inputs[0] except TypeError: raise RuntimeError( "inputs should be iterable but found type='{0}', value=" "'{1}'".format(type(self._inputs), str(self._inputs))) from melody.inputs import Input for check_input in self._inputs: if not isinstance(check_input, Input): raise RuntimeError( "input should be a subclass of the Input class but " "found type='{0}', value='{1}'".format(type(check_input), str(check_input)))
https://github.com/rupertford/melody/blob/d50459880a87fdd1802c6893f6e12b52d51b3b91/src/melody/search.py#L49-L63
how to make the checkbox checked
python
def _validate_check_with(self, checks, field, value): """ {'oneof': [ {'type': 'callable'}, {'type': 'list', 'schema': {'oneof': [{'type': 'callable'}, {'type': 'string'}]}}, {'type': 'string'} ]} """ if isinstance(checks, _str_type): try: value_checker = self.__get_rule_handler('check_with', checks) # TODO remove on next major release except RuntimeError: value_checker = self.__get_rule_handler('validator', checks) warn( "The 'validator' rule was renamed to 'check_with'. Please update " "your schema and method names accordingly.", DeprecationWarning, ) value_checker(field, value) elif isinstance(checks, Iterable): for v in checks: self._validate_check_with(v, field, value) else: checks(field, value, self._error)
https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L1094-L1118
how to make the checkbox checked
python
def assure_check(fnc): """ Converts an checkID passed as the check to a CloudMonitorCheck object. """ @wraps(fnc) def _wrapped(self, check, *args, **kwargs): if not isinstance(check, CloudMonitorCheck): # Must be the ID check = self._check_manager.get(check) return fnc(self, check, *args, **kwargs) return _wrapped
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L42-L52
how to make the checkbox checked
python
def checkedItems( self ): """ Returns the checked items for this combobox. :return [<str>, ..] """ if not self.isCheckable(): return [] return [nativestring(self.itemText(i)) for i in self.checkedIndexes()]
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L167-L176
how to make the checkbox checked
python
def setCheckable(self, state): """ Sets whether or not the actions within this button should be checkable. :param state | <bool> """ self._checkable = state for act in self._actionGroup.actions(): act.setCheckable(state)
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsplitbutton.py#L461-L469
how to make the checkbox checked
python
def validate_check_configs(cls, config): """ Config validation specific to the health check options. Verifies that checks are defined along with an interval, and calls out to the `Check` class to make sure each individual check's config is valid. """ if "checks" not in config: raise ValueError("No checks defined.") if "interval" not in config["checks"]: raise ValueError("No check interval defined.") for check_name, check_config in six.iteritems(config["checks"]): if check_name == "interval": continue Check.from_config(check_name, check_config)
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/service.py#L53-L70
how to make the checkbox checked
python
def set_checked(self, checked): """ Properly check the correct radio button. """ if not checked: self.widget.clearCheck() else: #: Checked is a reference to the radio declaration #: so we need to get the ID of it rb = checked.proxy.widget if not rb: return self.widget.check(rb.getId())
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_radio_group.py#L89-L101
how to make the checkbox checked
python
def _checkBool(inputvalue, description='inputvalue'): """Check that the given inputvalue is a boolean. Args: * inputvalue (boolean): The value to be checked. * description (string): Used in error messages for the checked inputvalue. Raises: TypeError, ValueError """ _checkString(description, minlength=1, description='description string') if not isinstance(inputvalue, bool): raise TypeError('The {0} must be boolean. Given: {1!r}'.format(description, inputvalue))
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2325-L2338
how to make the checkbox checked
python
def widgetSubCheckBoxRect(widget, option): """ Returns the rectangle of a check box drawn as a sub element of widget """ opt = QtWidgets.QStyleOption() opt.initFrom(widget) style = widget.style() return style.subElementRect(QtWidgets.QStyle.SE_ViewItemCheckIndicator, opt, widget)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L286-L292
how to make the checkbox checked
python
def _check_disabled(self): """Check if health check is disabled. It logs a message if health check is disabled and it also adds an item to the action queue based on 'on_disabled' setting. Returns: True if check is disabled otherwise False. """ if self.config['check_disabled']: if self.config['on_disabled'] == 'withdraw': self.log.info("Check is disabled and ip_prefix will be " "withdrawn") self.log.info("adding %s in the queue", self.ip_with_prefixlen) self.action.put(self.del_operation) self.log.info("Check is now permanently disabled") elif self.config['on_disabled'] == 'advertise': self.log.info("check is disabled, ip_prefix wont be withdrawn") self.log.info("adding %s in the queue", self.ip_with_prefixlen) self.action.put(self.add_operation) self.log.info('check is now permanently disabled') return True return False
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L195-L220
how to make the checkbox checked
python
def get_check(self, check): """ Returns a check. """ data = self._request('GET', '/checks/{}'.format(check)) return data.json()
https://github.com/sangoma/pysensu/blob/dc6799edbf2635247aec61fcf45b04ddec1beb49/pysensu/api.py#L158-L163
how to make the checkbox checked
python
def style_checkboxes(widget): """ Iterates over widget children to change checkboxes stylesheet. The default rendering of checkboxes does not allow to tell a focused one from an unfocused one. """ ww = widget.findChildren(QCheckBox) for w in ww: w.setStyleSheet("QCheckBox:focus {border: 1px solid #000000;}")
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/xmisc.py#L57-L67
how to make the checkbox checked
python
def get_check(self, check): """ Returns an instance of the specified check. """ chk = self._check_manager.get(check) chk.set_entity(self) return chk
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L89-L95
how to make the checkbox checked
python
def checkCursor(self): 'override Sheet.checkCursor' if self.cursorBox: if self.cursorBox.h < self.canvasCharHeight: self.cursorBox.h = self.canvasCharHeight*3/4 if self.cursorBox.w < self.canvasCharWidth: self.cursorBox.w = self.canvasCharWidth*3/4 return False
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L534-L542
how to make the checkbox checked
python
def _check(self, calc_dict, changes=None): ''' cplan._check(calc_dict) should be called only by the calc_dict object itself. The check method makes sure that all of the proactive methods on the calc_dict are run; if the optional keyword argument changes is given, then checks are only run for the list of changes given. ''' if changes is None: changes = self.afferents # run the zero-reqs for req in self.initializers: calc_dict._run_node(req) else: # invalidate these data if needed dpts = set(dpt for aff in changes for dpt in self.dependants[aff]) for dpt in dpts: del calc_dict[dpt] # now, make sure that proactive dependants get run proactives = set(node for change in changes for node in self.proactive_dependants[change]) for node in proactives: calc_dict._run_node(node)
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/calculation.py#L329-L348
how to make the checkbox checked
python
def check_bbox(bbox): """Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums""" for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]): if not 0 <= value <= 1: raise ValueError( 'Expected {name} for bbox {bbox} ' 'to be in the range [0.0, 1.0], got {value}.'.format( bbox=bbox, name=name, value=value, ) ) x_min, y_min, x_max, y_max = bbox[:4] if x_max <= x_min: raise ValueError('x_max is less than or equal to x_min for bbox {bbox}.'.format( bbox=bbox, )) if y_max <= y_min: raise ValueError('y_max is less than or equal to y_min for bbox {bbox}.'.format( bbox=bbox, ))
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L175-L195
how to make the checkbox checked
python
def on_unicode_checkbox(self, w=None, state=False): """Enable smooth edges if utf-8 is supported""" logging.debug("unicode State is %s", state) # Update the controller to the state of the checkbox self.controller.smooth_graph_mode = state if state: self.hline = urwid.AttrWrap( urwid.SolidFill(u'\N{LOWER ONE QUARTER BLOCK}'), 'line') else: self.hline = urwid.AttrWrap(urwid.SolidFill(u' '), 'line') for graph in self.graphs.values(): graph.set_smooth_colors(state) self.show_graphs()
https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/s_tui.py#L362-L377
how to make the checkbox checked
python
def action_checkbox(self, obj): """Renders checkboxes. Disable checkbox for parent item navigation link. """ if getattr(obj, Hierarchy.UPPER_LEVEL_MODEL_ATTR, False): return '' return super(HierarchicalModelAdmin, self).action_checkbox(obj)
https://github.com/idlesign/django-admirarchy/blob/723e4fd212fdebcc156492cb16b9d65356f5ca73/admirarchy/utils.py#L45-L54
how to make the checkbox checked
python
def _box_click(self, event): """Check or uncheck box when clicked.""" x, y, widget = event.x, event.y, event.widget elem = widget.identify("element", x, y) if "image" in elem: # a box was clicked item = self.identify_row(y) if self.tag_has("unchecked", item) or self.tag_has("tristate", item): self._check_ancestor(item) self._check_descendant(item) else: self._uncheck_descendant(item) self._uncheck_ancestor(item)
https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/checkboxtreeview.py#L255-L267
how to make the checkbox checked
python
def uncheckButton(self): """Removes the checked stated of all buttons in this widget. This method is also a slot. """ #for button in self.buttons[1:]: for button in self.buttons: # supress editButtons toggled event button.blockSignals(True) if button.isChecked(): button.setChecked(False) button.blockSignals(False)
https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/DataTableView.py#L205-L217
how to make the checkbox checked
python
def _check_cb(cb_): ''' If the callback is None or is not callable, return a lambda that returns the value passed. ''' if cb_ is not None: if hasattr(cb_, '__call__'): return cb_ else: log.error('log_callback is not callable, ignoring') return lambda x: x
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cmdmod.py#L79-L89
how to make the checkbox checked
python
def checks(self): '''Return the list of all check methods.''' condition = lambda a: a.startswith('check_') return (getattr(self, a) for a in dir(self) if condition(a))
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/checker.py#L43-L46
how to make the checkbox checked
python
def get_checkcode(cls, id_number_str): """ 计算身份证号码的校验位; :param: * id_number_str: (string) 身份证号的前17位,比如 3201241987010100 :returns: * 返回类型 (tuple) * flag: (bool) 如果身份证号格式正确,返回 True;格式错误,返回 False * checkcode: 计算身份证前17位的校验码 举例如下:: from fishbase.fish_data import * print('--- fish_data get_checkcode demo ---') # id number id1 = '32012419870101001' print(id1, IdCard.get_checkcode(id1)[1]) # id number id2 = '13052219840731647' print(id2, IdCard.get_checkcode(id2)[1]) print('---') 输出结果:: --- fish_data get_checkcode demo --- 32012419870101001 5 13052219840731647 1 --- """ # 判断长度,如果不是 17 位,直接返回失败 if len(id_number_str) != 17: return False, -1 id_regex = '[1-9][0-9]{14}([0-9]{2}[0-9X])?' if not re.match(id_regex, id_number_str): return False, -1 items = [int(item) for item in id_number_str] # 加权因子表 factors = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2) # 计算17位数字各位数字与对应的加权因子的乘积 copulas = sum([a * b for a, b in zip(factors, items)]) # 校验码表 check_codes = ('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2') checkcode = check_codes[copulas % 11].upper() return True, checkcode
https://github.com/chinapnr/fishbase/blob/23c5147a6bc0d8ed36409e55352ffb2c5b0edc82/fishbase/fish_data.py#L76-L134
how to make the checkbox checked
python
def check_by_selector(self, selector): """Check the checkbox matching the CSS selector.""" elem = find_element_by_jquery(world.browser, selector) if not elem.is_selected(): elem.click()
https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/css.py#L198-L202
how to make the checkbox checked
python
def draw(self): """Draws the checkbox.""" if not self.visible: return # Blit the current checkbox's image. if self.isEnabled: if self.mouseIsDown and self.lastMouseDownOverButton and self.mouseOverButton: if self.value: self.window.blit(self.surfaceOnDown, self.loc) else: self.window.blit(self.surfaceOffDown, self.loc) else: if self.value: self.window.blit(self.surfaceOn, self.loc) else: self.window.blit(self.surfaceOff, self.loc) else: if self.value: self.window.blit(self.surfaceOnDisabled, self.loc) else: self.window.blit(self.surfaceOffDisabled, self.loc)
https://github.com/IrvKalb/pygwidgets/blob/a830d8885d4d209e471cb53816277d30db56273c/pygwidgets/pygwidgets.py#L839-L863
how to make the checkbox checked
python
def _do_check(self, obj, check_module, check_str): '''Run a check function on obj''' opts = self._config['options'] if check_str in opts: fargs = opts[check_str] if isinstance(fargs, list): out = check_wrapper(getattr(check_module, check_str))(obj, *fargs) else: out = check_wrapper(getattr(check_module, check_str))(obj, fargs) else: out = check_wrapper(getattr(check_module, check_str))(obj) try: if out.info: L.debug('%s: %d failing ids detected: %s', out.title, len(out.info), out.info) except TypeError: # pragma: no cover pass return out
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/runner.py#L73-L92
how to make the checkbox checked
python
def check(predicate): r"""A decorator that adds a check to the :class:`.Command` or its subclasses. These checks could be accessed via :attr:`.Command.checks`. These checks should be predicates that take in a single parameter taking a :class:`.Context`. If the check returns a ``False``\-like value then during invocation a :exc:`.CheckFailure` exception is raised and sent to the :func:`.on_command_error` event. If an exception should be thrown in the predicate then it should be a subclass of :exc:`.CommandError`. Any exception not subclassed from it will be propagated while those subclassed will be sent to :func:`.on_command_error`. .. note:: These functions can either be regular functions or coroutines. Examples --------- Creating a basic check to see if the command invoker is you. .. code-block:: python3 def check_if_it_is_me(ctx): return ctx.message.author.id == 85309593344815104 @bot.command() @commands.check(check_if_it_is_me) async def only_for_me(ctx): await ctx.send('I know you!') Transforming common checks into its own decorator: .. code-block:: python3 def is_me(): def predicate(ctx): return ctx.message.author.id == 85309593344815104 return commands.check(predicate) @bot.command() @is_me() async def only_me(ctx): await ctx.send('Only you!') Parameters ----------- predicate: Callable[:class:`Context`, :class:`bool`] The predicate to check if the command should be invoked. """ def decorator(func): if isinstance(func, Command): func.checks.append(predicate) else: if not hasattr(func, '__commands_checks__'): func.__commands_checks__ = [] func.__commands_checks__.append(predicate) return func return decorator
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1253-L1316
how to make the checkbox checked
python
def scopes_multi_checkbox(field, **kwargs): """Render multi checkbox widget.""" kwargs.setdefault('type', 'checkbox') field_id = kwargs.pop('id', field.id) html = [u'<div class="row">'] for value, label, checked in field.iter_choices(): choice_id = u'%s-%s' % (field_id, value) options = dict( kwargs, name=field.name, value=value, id=choice_id, class_=' ', ) if checked: options['checked'] = 'checked' html.append(u'<div class="col-md-3">') html.append(u'<label for="{0}" class="checkbox-inline">'.format( choice_id )) html.append(u'<input {0} /> '.format(widgets.html_params(**options))) html.append(u'{0} <br/><small class="text-muted">{1}</small>'.format( value, label.help_text )) html.append(u'</label></div>') html.append(u'</div>') return HTMLString(u''.join(html))
https://github.com/inveniosoftware/invenio-oauth2server/blob/7033d3495c1a2b830e101e43918e92a37bbb49f2/invenio_oauth2server/forms.py#L26-L58
how to make the checkbox checked
python
def check(self, check, member, missing=False): """A dummy check method, always returns the value unchanged.""" if missing: raise self.baseErrorClass() return member
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2389-L2393
how to make the checkbox checked
python
def _checks(self, do_checks=False, do_actions=False, poller_tags=None, reactionner_tags=None, worker_name='none', module_types=None): """Get checks from scheduler, used by poller or reactionner when they are in active mode (passive = False) This function is not intended for external use. Let the poller and reactionner manage all this stuff by themselves ;) :param do_checks: used for poller to get checks :type do_checks: bool :param do_actions: used for reactionner to get actions :type do_actions: bool :param poller_tags: poller tags to filter on this poller :type poller_tags: list :param reactionner_tags: reactionner tags to filter on this reactionner :type reactionner_tags: list :param worker_name: Worker name asking (so that the scheduler add it to actions objects) :type worker_name: str :param module_types: Module type to filter actions/checks :type module_types: list :return: serialized check/action list :rtype: str """ if poller_tags is None: poller_tags = ['None'] if reactionner_tags is None: reactionner_tags = ['None'] if module_types is None: module_types = ['fork'] do_checks = (do_checks == 'True') do_actions = (do_actions == 'True') res = self.app.sched.get_to_run_checks(do_checks, do_actions, poller_tags, reactionner_tags, worker_name, module_types) return serialize(res, True)
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/scheduler_interface.py#L414-L448
how to make the checkbox checked
python
def setCheckedItems(self, items): """ Returns the checked items for this combobox. :return items | [<str>, ..] """ if not self.isCheckable(): return model = self.model() for i in range(self.count()): item_text = self.itemText(i) if not item_text: continue if nativestring(item_text) in items: state = Qt.Checked else: state = Qt.Unchecked model.item(i).setCheckState(state)
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L373-L393
how to make the checkbox checked
python
def getChecked(self): """Gets the checked attributes :returns: list<str> -- checked attribute names """ attrs = [] layout = self.layout() for i in range(layout.count()): w = layout.itemAt(i).widget() if w.isChecked(): attrs.append(str(w.text())) return attrs
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/component_detail.py#L165-L176
how to make the checkbox checked
python
def checkCursor(self): 'Keep cursor in bounds of data and screen.' # keep cursor within actual available rowset if self.nRows == 0 or self.cursorRowIndex <= 0: self.cursorRowIndex = 0 elif self.cursorRowIndex >= self.nRows: self.cursorRowIndex = self.nRows-1 if self.cursorVisibleColIndex <= 0: self.cursorVisibleColIndex = 0 elif self.cursorVisibleColIndex >= self.nVisibleCols: self.cursorVisibleColIndex = self.nVisibleCols-1 if self.topRowIndex <= 0: self.topRowIndex = 0 elif self.topRowIndex > self.nRows-1: self.topRowIndex = self.nRows-1 # (x,y) is relative cell within screen viewport x = self.cursorVisibleColIndex - self.leftVisibleColIndex y = self.cursorRowIndex - self.topRowIndex + 1 # header # check bounds, scroll if necessary if y < 1: self.topRowIndex = self.cursorRowIndex elif y > self.nVisibleRows: self.topRowIndex = self.cursorRowIndex-self.nVisibleRows+1 if x <= 0: self.leftVisibleColIndex = self.cursorVisibleColIndex else: while True: if self.leftVisibleColIndex == self.cursorVisibleColIndex: # not much more we can do break self.calcColLayout() mincolidx, maxcolidx = min(self.visibleColLayout.keys()), max(self.visibleColLayout.keys()) if self.cursorVisibleColIndex < mincolidx: self.leftVisibleColIndex -= max((self.cursorVisibleColIndex - mincolid)//2, 1) continue elif self.cursorVisibleColIndex > maxcolidx: self.leftVisibleColIndex += max((maxcolidx - self.cursorVisibleColIndex)//2, 1) continue cur_x, cur_w = self.visibleColLayout[self.cursorVisibleColIndex] if cur_x+cur_w < self.vd.windowWidth: # current columns fit entirely on screen break self.leftVisibleColIndex += 1
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1651-L1697
how to make the checkbox checked
python
def check(self, F): """Rough sanity checks on the input function. """ assert F.ndim == 1, "checker only supports 1D" f = self.xfac * F fabs = np.abs(f) iQ1, iQ3 = np.searchsorted(fabs.cumsum(), np.array([0.25, 0.75]) * fabs.sum()) assert 0 != iQ1 != iQ3 != self.Nin, "checker giving up" fabs_l = fabs[:iQ1].mean() fabs_m = fabs[iQ1:iQ3].mean() fabs_r = fabs[iQ3:].mean() if fabs_l > fabs_m: warnings.warn("left wing seems heavy: {:.2g} vs {:.2g}, " "change tilt and mind convergence".format(fabs_l, fabs_m), RuntimeWarning) if fabs_m < fabs_r: warnings.warn("right wing seems heavy: {:.2g} vs {:.2g}, " "change tilt and mind convergence".format(fabs_m, fabs_r), RuntimeWarning) if fabs[0] > fabs[1]: warnings.warn("left tail may blow up: {:.2g} vs {:.2g}, " "change tilt or avoid extrapolation".format(f[0], f[1]), RuntimeWarning) if fabs[-2] < fabs[-1]: warnings.warn("right tail may blow up: {:.2g} vs {:.2g}, " "change tilt or avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning) if f[0]*f[1] <= 0: warnings.warn("left tail looks wiggly: {:.2g} vs {:.2g}, " "avoid extrapolation".format(f[0], f[1]), RuntimeWarning) if f[-2]*f[-1] <= 0: warnings.warn("right tail looks wiggly: {:.2g} vs {:.2g}, " "avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning)
https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L423-L457
how to make the checkbox checked
python
def get_checked(self): """Return the list of checked items that do not have any child.""" checked = [] def get_checked_children(item): if not self.tag_has("unchecked", item): ch = self.get_children(item) if not ch and self.tag_has("checked", item): checked.append(item) else: for c in ch: get_checked_children(c) ch = self.get_children("") for c in ch: get_checked_children(c) return checked
https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/checkboxtreeview.py#L179-L195
how to make the checkbox checked
python
def type_check_cmd(self, args, range=None): """Sets the flag to begin buffering typecheck notes & clears any stale notes before requesting a typecheck from the server""" self.log.debug('type_check_cmd: in') self.start_typechecking() self.type_check("") self.editor.message('typechecking')
https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L336-L342
how to make the checkbox checked
python
def GetCheckButtonSelect(selectList, title="Select", msg=""): """ Get selected check button options title: Window name mag: Label of the check button return selected dictionary {'sample b': False, 'sample c': False, 'sample a': False} """ root = tkinter.Tk() root.title(title) label = tkinter.Label(root, text=msg) label.pack() optList = [] for item in selectList: opt = tkinter.BooleanVar() opt.set(False) tkinter.Checkbutton(root, text=item, variable=opt).pack() optList.append(opt) tkinter.Button(root, text="OK", fg="black", command=root.quit).pack() root.mainloop() root.destroy() result = {} for (opt, select) in zip(optList, selectList): result[select] = opt.get() print(result) return result
https://github.com/AtsushiSakai/SimpleTkGUIKit/blob/e7cbb06ff32afb165cdaa4fe396ca2f172c66ff0/SimpleTkGUIKit/SimpleTkGUIKit.py#L99-L131
how to make the checkbox checked
python
def _conversion_checks(item, keys, box_config, check_only=False, pre_check=False): """ Internal use for checking if a duplicate safe attribute already exists :param item: Item to see if a dup exists :param keys: Keys to check against :param box_config: Easier to pass in than ask for specfic items :param check_only: Don't bother doing the conversion work :param pre_check: Need to add the item to the list of keys to check :return: the original unmodified key, if exists and not check_only """ if box_config['box_duplicates'] != 'ignore': if pre_check: keys = list(keys) + [item] key_list = [(k, _safe_attr(k, camel_killer=box_config['camel_killer_box'], replacement_char=box_config['box_safe_prefix'] )) for k in keys] if len(key_list) > len(set(x[1] for x in key_list)): seen = set() dups = set() for x in key_list: if x[1] in seen: dups.add("{0}({1})".format(x[0], x[1])) seen.add(x[1]) if box_config['box_duplicates'].startswith("warn"): warnings.warn('Duplicate conversion attributes exist: ' '{0}'.format(dups)) else: raise BoxError('Duplicate conversion attributes exist: ' '{0}'.format(dups)) if check_only: return # This way will be slower for warnings, as it will have double work # But faster for the default 'ignore' for k in keys: if item == _safe_attr(k, camel_killer=box_config['camel_killer_box'], replacement_char=box_config['box_safe_prefix']): return k
https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L196-L236
how to make the checkbox checked
python
def pformat_check(success, checker, message): """Pretty print a check result :param success: `True` if the check was successful, `False` otherwise. :param checker: The checker dict that was executed :param message: The label for the check :returns: A string representation of the check """ # TODO: Make this prettier. return "[{}] {}: {}".format("✓" if success else "✗", checker["checker"], message)
https://github.com/humangeo/preflyt/blob/3174e6b8fc851ba5bd6c7fcf9becf36a6f6f6d93/preflyt/utils.py#L3-L13
how to make the checkbox checked
python
def has_unchecked_field(self, locator, **kwargs): """ Checks if the page or current node has a radio button or checkbox with the given label, value, or id, that is currently unchecked. Args: locator (str): The label, name, or id of an unchecked field. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: bool: Whether it exists. """ kwargs["checked"] = False return self.has_selector("field", locator, **kwargs)
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L784-L798
how to make the checkbox checked
python
def check_number(cls, id_number): """ 检查身份证号码是否符合校验规则; :param: * id_number: (string) 身份证号,比如 32012419870101001 :returns: * 返回类型 (tuple),当前有一个值,第一个为 flag,以后第二个值会返回具体校验不通过的详细错误 * flag: (bool) 如果身份证号码校验通过,返回 True;如果身份证校验不通过,返回 False 举例如下:: from fishbase.fish_data import * print('--- fish_data check_number demo ---') # id number false id1 = '320124198701010012' print(id1, IdCard.check_number(id1)[0]) # id number true id2 = '130522198407316471' print(id2, IdCard.check_number(id2)[0]) print('---') 输出结果:: --- fish_data check_number demo --- 320124198701010012 False 130522198407316471 True --- """ if isinstance(id_number, int): id_number = str(id_number) # 调用函数计算身份证前面17位的 checkcode result = IdCard.get_checkcode(id_number[0:17]) # 返回第一个 flag 是错误的话,表示身份证格式错误,直接透传返回,第二个为获得的校验码 flag = result[0] checkcode = result[1] if not flag: return flag, # 判断校验码是否正确 return checkcode == id_number[-1].upper(),
https://github.com/chinapnr/fishbase/blob/23c5147a6bc0d8ed36409e55352ffb2c5b0edc82/fishbase/fish_data.py#L143-L191
how to make the checkbox checked
python
def uncheck(self, locator=None, allow_label_click=None, **kwargs): """ Find a check box and uncheck it. The check box can be found via name, id, or label text. :: page.uncheck("German") Args: locator (str, optional): Which check box to uncheck. allow_label_click (bool, optional): Attempt to click the label to toggle state if element is non-visible. Defaults to :data:`capybara.automatic_label_click`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ self._check_with_label( "checkbox", False, locator=locator, allow_label_click=allow_label_click, **kwargs)
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L162-L176
how to make the checkbox checked
python
def on_checked_changed(self, group, checked_id): """ Set the checked property based on the checked state of all the children """ d = self.declaration if checked_id < 0: with self.widget.clearCheck.suppressed(): d.checked = None return else: for c in self.children(): if c.widget.getId() == checked_id: with self.widget.check.suppressed(): d.checked = c.declaration return
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_radio_group.py#L69-L84
how to make the checkbox checked
python
def generate_checks(fact): """Given a fact, generate a list of Check objects for checking it.""" yield TypeCheck(type(fact)) fact_captured = False for key, value in fact.items(): if (isinstance(key, str) and key.startswith('__') and key.endswith('__')): # Special fact feature if key == '__bind__': yield FactCapture(value) fact_captured = True else: # pragma: no cover yield FeatureCheck(key, value) else: yield FeatureCheck(key, value) # Assign the matching fact to the context if not fact_captured: yield FactCapture("__pattern_%s__" % id(fact))
https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/utils.py#L83-L104
how to make the checkbox checked
python
def checkin(self): """Checks in an anonymous user in.""" self._query_instance.checkin(self.place_id, self._query_instance.sensor)
https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L1006-L1009
how to make the checkbox checked
python
def callback_checkbox(attr, old, new): '''Update visible data from parameters selectin in the CheckboxSelect''' import numpy for i in range(len(lines)): lines[i].visible = i in param_checkbox.active scats[i].visible = i in param_checkbox.active return None
https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L179-L187
how to make the checkbox checked
python
def check_action_type(self, value): """Set the value for the CheckActionType, validating input""" if value is not None: if not isinstance(value, ActionType): raise AttributeError("Invalid check action %s" % value) self._check_action_type = value
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/metadata.py#L2180-L2185
how to make the checkbox checked
python
def handleImplicitCheck(self): """ Checkboxes are hidden when inside of a RadioGroup as a selection of the Radio button is an implicit selection of the Checkbox. As such, we have to manually "check" any checkbox as needed. """ for button, widget in zip(self.radioButtons, self.widgets): if isinstance(widget, CheckBox): if button.GetValue(): # checked widget.setValue(True) else: widget.setValue(False)
https://github.com/chriskiehl/Gooey/blob/e598573c6519b953e0ccfc1f3663f827f8cd7e22/gooey/gui/components/widgets/radio_group.py#L108-L119
how to make the checkbox checked
python
def set_checked(self, state): """ Sets the Widget checked state. :param state: New check state. :type state: bool :return: Method success. :rtype: bool """ if not self.__checkable: return False if state: self.__checked = True self.setPixmap(self.__active_pixmap) else: self.__checked = False self.setPixmap(self.__default_pixmap) self.toggled.emit(state) return True
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/active_QLabel.py#L386-L406
how to make the checkbox checked
python
def html_for_check(self, check) -> str: """Return HTML string for complete single check.""" check["logs"].sort(key=lambda c: LOGLEVELS.index(c["status"])) logs = "<ul>" + "".join([self.log_html(log) for log in check["logs"]]) + "</ul>" return logs
https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/reporters/html.py#L104-L108
how to make the checkbox checked
python
def satisfied_by_checked(self, req): """ Check if requirement is already satisfied by what was previously checked :param Requirement req: Requirement to check """ req_man = RequirementsManager([req]) return any(req_man.check(*checked) for checked in self.checked)
https://github.com/maxzheng/bumper-lib/blob/32a9dec5448673825bb2d7d92fa68882b597f794/bumper/cars.py#L193-L201
how to make the checkbox checked
python
def has_no_checked_field(self, locator, **kwargs): """ Checks if the page or current node has no radio button or checkbox with the given label, value, or id that is currently checked. Args: locator (str): The label, name, or id of a checked field. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: bool: Whether it doesn't exist. """ kwargs["checked"] = True return self.has_no_selector("field", locator, **kwargs)
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L630-L644
how to make the checkbox checked
python
def _check_result(self, result): """ Check that the check returned a well formed result: a tuple (<Status>, message) A boolean Status is allowd and will be transformed to: True <Status: PASS>, False <Status: FAIL> Checks will be implemented by other parties. This is to help implementors creating good checks, to spot erroneous implementations early and to make it easier to handle the results tuple. """ if not isinstance(result, tuple): return (FAIL, APIViolationError( 'Result must be a tuple but ' 'it is {}.'.format(type(result)), result)) if len(result) != 2: return (FAIL, APIViolationError( 'Result must have 2 items, but it ' 'has {}.'.format(len(result)), result)) status, message = result # Allow booleans, but there's no way to issue a WARNING if isinstance(status, bool): # normalize status = PASS if status else FAIL result = (status, message) if not isinstance(status, Status): return (FAIL, APIViolationError( 'Result item `status` must be an instance of ' 'Status, but it is {} a {}.'.format(status, type(status)), result)) return result
https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/checkrunner.py#L282-L316
how to make the checkbox checked
python
def post_check(self, check): """ :param check: Check to post to Metricly :type check: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) url = self.checkurl + '/' \ + check.name + '/' \ + check.elementId + '/' \ + str(check.ttl) headers = {'User-Agent': self.agent} try: request = urllib2.Request( url, data='', headers=headers) resp = self._repeat_request(request, self.connection_timeout) logging.debug("Response code: %d", resp.getcode()) resp.close() return(True) except urllib2.HTTPError as e: logging.debug("Response code: %d", e.code) if e.code in self.kill_codes: self.disabled = True logging.exception('Posting has been disabled.' 'See previous errors for details.') else: logging.exception( 'HTTPError posting payload to api ingest endpoint' + ' (%s): %s', url, e)
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/client.py#L159-L195
how to make the checkbox checked
python
def check(text): """Check the text.""" err = "security.credit_card" msg = u"Don't put credit card numbers in plain text." credit_card_numbers = [ "4\d{15}", "5[1-5]\d{14}", "3[4,7]\d{13}", "3[0,6,8]\d{12}", "6011\d{12}", ] return existence_check(text, credit_card_numbers, err, msg)
https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/security/credit_card.py#L20-L33
how to make the checkbox checked
python
def db_check( block_id, opcode, op, txid, vtxindex, checked, db_state=None ): """ Given the block ID and a parsed operation, check to see if this is a *valid* operation for the purposes of this virtual chain's database. Return True if so; False if not. """ print "\nreference implementation of db_check\n" return False
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/impl_ref/reference.py#L104-L112
how to make the checkbox checked
python
def _get_valid_checkers(self, ds, checker_names): """ Returns a filtered list of 2-tuples: (name, valid checker) based on the ds object's type and the user selected names. """ assert len(self.checkers) > 0, "No checkers could be found." if len(checker_names) == 0: checker_names = list(self.checkers.keys()) args = [(name, self.checkers[name]) for name in checker_names if name in self.checkers] valid = [] all_checked = set([a[1] for a in args]) # only class types checker_queue = set(args) while len(checker_queue): name, a = checker_queue.pop() # is the current dataset type in the supported filetypes # for the checker class? if type(ds) in a().supported_ds: valid.append((name, a)) # add any subclasses of the checker class for subc in a.__subclasses__(): if subc not in all_checked: all_checked.add(subc) checker_queue.add((name, subc)) return valid
https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/suite.py#L183-L212
how to make the checkbox checked
python
def init_check(self, check, obj): """ Adds a given check callback with the provided object to the list of checks. Useful for built-ins but also advanced custom checks. """ self.logger.info('Adding extension check %s' % check.__name__) check = functools.wraps(check)(functools.partial(check, obj)) self.check(func=check)
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L135-L142
how to make the checkbox checked
python
def get_checks(options): """Extract the checks.""" sys.path.append(proselint_path) checks = [] check_names = [key for (key, val) in list(options["checks"].items()) if val] for check_name in check_names: module = importlib.import_module("checks." + check_name) for d in dir(module): if re.match("check", d): checks.append(getattr(module, d)) return checks
https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L150-L163
how to make the checkbox checked
python
def _toggle_checkable_action(self, checked, editorstack_method, conf_name): """Handle the toogle of a checkable action. Update editorstacks and the configuration. Args: checked (bool): State of the action. editorstack_method (str): name of EditorStack class that will be used to update the changes in each editorstack. conf_name (str): configuration setting associated with the action. """ if self.editorstacks: for editorstack in self.editorstacks: try: editorstack.__getattribute__(editorstack_method)(checked) except AttributeError as e: logger.error(e, exc_info=True) # Run code analysis when `set_pep8_enabled` is toggled if editorstack_method == 'set_pep8_enabled': # TODO: Connect this to the LSP #for finfo in editorstack.data: # finfo.run_code_analysis( # self.get_option('code_analysis/pyflakes'), # checked) pass CONF.set('editor', conf_name, checked)
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/plugin.py#L993-L1018
how to make the checkbox checked
python
def check_checksum_mismatch(self): ''' Checking for a checksum that doesn't match the generated checksum ''' if self.pefile_handle.OPTIONAL_HEADER: if self.pefile_handle.OPTIONAL_HEADER.CheckSum != self.pefile_handle.generate_checksum(): return {'description': 'Reported Checksum does not match actual checksum', 'severity': 2, 'category': 'MALFORMED'} return None
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_indicators.py#L94-L100
how to make the checkbox checked
python
def check_physical(self, line): """Run all physical checks on a raw input line.""" self.physical_line = line for name, check, argument_names in self._physical_checks: self.init_checker_state(name, argument_names) result = self.run_check(check, argument_names) if result is not None: (offset, text) = result self.report_error(self.line_number, offset, text, check) if text[:4] == 'E101': self.indent_char = line[0]
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1597-L1607
how to make the checkbox checked
python
def create_check(self, label=None, name=None, check_type=None, details=None, disabled=False, metadata=None, monitoring_zones_poll=None, timeout=None, period=None, target_alias=None, target_hostname=None, target_receiver=None, test_only=False, include_debug=False): """ Creates a check on the entity with the specified attributes. The 'details' parameter should be a dict with the keys as the option name, and the value as the desired setting. If the 'test_only' parameter is True, then the check is not created; instead, the check is run and the results of the test run returned. If 'include_debug' is True, additional debug information is returned. According to the current Cloud Monitoring docs: "Currently debug information is only available for the remote.http check and includes the response body." """ if details is None: raise exc.MissingMonitoringCheckDetails("The required 'details' " "parameter was not passed to the create_check() method.") ctype = utils.get_id(check_type) is_remote = ctype.startswith("remote") monitoring_zones_poll = utils.coerce_to_list(monitoring_zones_poll) monitoring_zones_poll = [utils.get_id(mzp) for mzp in monitoring_zones_poll] # only require monitoring_zones and targets for remote checks if is_remote: if not monitoring_zones_poll: raise exc.MonitoringZonesPollMissing("You must specify the " "'monitoring_zones_poll' parameter for remote checks.") if not (target_alias or target_hostname): raise exc.MonitoringCheckTargetNotSpecified("You must " "specify either the 'target_alias' or 'target_hostname' " "when creating a remote check.") body = {"label": label or name, "details": details, "disabled": disabled, "type": utils.get_id(check_type), } params = ("monitoring_zones_poll", "timeout", "period", "target_alias", "target_hostname", "target_receiver") body = _params_to_dict(params, body, locals()) if test_only: uri = "/%s/test-check" % self.uri_base if include_debug: uri = "%s?debug=true" % uri else: uri = "/%s" % self.uri_base try: resp = self.api.method_post(uri, body=body)[0] except exc.BadRequest as e: msg = e.message dtls = e.details match = _invalid_key_pat.match(msg) if match: missing = match.groups()[0].replace("details.", "") if missing in details: errmsg = "".join(["The value passed for '%s' in the ", "details parameter is not valid."]) % missing else: errmsg = "".join(["The required value for the '%s' ", "setting is missing from the 'details' ", "parameter."]) % missing utils.update_exc(e, errmsg) raise e else: if msg == "Validation error": # Info is in the 'details' raise exc.InvalidMonitoringCheckDetails("Validation " "failed. Error: '%s'." % dtls) # its something other than validation error; probably # limits exceeded, but raise it instead of failing silently raise e else: if resp.status_code == 201: check_id = resp.headers["x-object-id"] return self.get(check_id) # don't fail silently here either; raise an error # if we get an unexpected response code raise exc.ClientException("Unknown response code creating check;" " expected 201, got %s" % resp.status_code)
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L546-L626
how to make the checkbox checked
python
def make_checksum_validation_script(stats_list): """Make batch files required for checking checksums from another machine.""" if not os.path.exists('./hash_check'): os.mkdir('./hash_check') with open('./hash_check/curl.sh', 'w') as curl_f, open( './hash_check/md5.txt', 'w' ) as md5_f, open('./hash_check/sha1.txt', 'w') as sha1_f: curl_f.write('#!/usr/bin/env bash\n\n') for stats_dict in stats_list: for sysmeta_xml in stats_dict['largest_sysmeta_xml']: print(sysmeta_xml) sysmeta_pyxb = d1_common.types.dataoneTypes_v1_2.CreateFromDocument( sysmeta_xml ) pid = sysmeta_pyxb.identifier.value().encode('utf-8') file_name = re.sub('\W+', '_', pid) size = sysmeta_pyxb.size base_url = stats_dict['gmn_dict']['base_url'] if size > 100 * 1024 * 1024: logging.info('Ignored large object. size={} pid={}') curl_f.write('# {} {}\n'.format(size, pid)) curl_f.write( 'curl -o obj/{} {}/v1/object/{}\n'.format( file_name, base_url, d1_common.url.encodePathElement(pid) ) ) if sysmeta_pyxb.checksum.algorithm == 'MD5': md5_f.write( '{} obj/{}\n'.format(sysmeta_pyxb.checksum.value(), file_name) ) else: sha1_f.write( '{} obj/{}\n'.format(sysmeta_pyxb.checksum.value(), file_name) ) with open('./hash_check/check.sh', 'w') as f: f.write('#!/usr/bin/env bash\n\n') f.write('mkdir -p obj\n') f.write('./curl.sh\n') f.write('sha1sum -c sha1.txt\n') f.write('md5sum -c md5.txt\n')
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/utilities/src/d1_util/check_object_checksums.py#L113-L160
how to make the checkbox checked
python
def check_input(self, obj): """ Performs checks on the input object. Raises an exception if unsupported. :param obj: the object to check :type obj: object """ if isinstance(obj, str): return if isinstance(obj, unicode): return raise Exception("Unsupported class: " + self._input.__class__.__name__)
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/conversion.py#L207-L218
how to make the checkbox checked
python
def _can_refresh_check(self, check_id): """ Determine if the given check_id can be refreshed yet. :param check_id: the Trusted Advisor check ID :type check_id: str :return: whether or not the check can be refreshed yet :rtype: bool """ try: refresh_status = \ self.conn.describe_trusted_advisor_check_refresh_statuses( checkIds=[check_id] ) logger.debug("TA Check %s refresh status: %s", check_id, refresh_status['statuses'][0]) ms = refresh_status['statuses'][0]['millisUntilNextRefreshable'] if ms > 0: logger.warning("Trusted Advisor check cannot be refreshed for " "another %d milliseconds; skipping refresh and " "getting check results now", ms) return False return True except Exception: logger.warning("Could not get refresh status for TA check %s", check_id, exc_info=True) # default to True if we don't know... return True
https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/awslimitchecker/trustedadvisor.py#L336-L363
how to make the checkbox checked
python
def _create_checkable_action(self, text, conf_name, editorstack_method): """Helper function to create a checkable action. Args: text (str): Text to be displayed in the action. conf_name (str): configuration setting associated with the action editorstack_method (str): name of EditorStack class that will be used to update the changes in each editorstack. """ def toogle(checked): self.switch_to_plugin() self._toggle_checkable_action(checked, editorstack_method, conf_name) action = create_action(self, text, toggled=toogle) action.setChecked(CONF.get('editor', conf_name)) return action
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/plugin.py#L975-L990
how to make the checkbox checked
python
def checkconfig(): ''' returns the output of lxc-checkconfig ''' cmd = ['lxc-checkconfig'] return subprocess.check_output(cmd).replace('[1;32m', '').replace('[1;33m', '').replace('[0;39m', '').replace('[1;32m', '').replace(' ', '').split('\n')
https://github.com/cloud9ers/pylxc/blob/588961dd37ce6e14fd7c1cc76d1970e48fccba34/lxc/__init__.py#L300-L305
how to make the checkbox checked
python
def set_checks(self, checks, position=None): """Sets the checks at the position.""" if position is None: position = self.position self.checkdefs[position][0] = checks
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/matching.py#L137-L141
how to make the checkbox checked
python
def uncheck_all(self, name): """Remove the *checked*-attribute of all input elements with a *name*-attribute given by ``name``. """ for option in self.form.find_all("input", {"name": name}): if "checked" in option.attrs: del option.attrs["checked"]
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L72-L78
how to make the checkbox checked
python
def setChecked(self, column, state): """ Sets the check state of the inputed column based on the given bool state. This is a convenience method on top of the setCheckState method. :param column | <int> state | <bool> """ self.setCheckState(column, QtCore.Qt.Checked if state else QtCore.Qt.Unchecked)
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetitem.py#L341-L350
how to make the checkbox checked
python
def check(self): """ Run the setting checker against the setting raw value. Raises: AttributeError: if the setting is missing and required. ValueError: if the raw value is invalid. """ try: value = self.raw_value except (AttributeError, KeyError) as err: self._reraise_if_required(err) else: if self.checker: self.checker(self.full_name, value) try: self.validate(value) self.run_validators(value) except ValidationError as error: raise ValueError("Setting {} has an invalid value: {}".format(self.full_name, error))
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L533-L552
how to make the checkbox checked
python
def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths): """ Print the checks. """ if ruleset and ruleset_file: raise click.BadOptionUsage( "Options '--ruleset' and '--file-ruleset' cannot be used together.") try: if not debug: logging.basicConfig(stream=six.StringIO()) log_level = _get_log_level(debug=debug, verbose=verbose) checks = get_checks(ruleset_name=ruleset, ruleset_file=ruleset_file, logging_level=log_level, tags=tag, checks_paths=checks_paths, skips=skip) _print_checks(checks=checks) if json: AbstractCheck.save_checks_to_json(file=json, checks=checks) except ColinException as ex: logger.error("An error occurred: %r", ex) if debug: raise else: raise click.ClickException(str(ex)) except Exception as ex: logger.error("An error occurred: %r", ex) if debug: raise else: raise click.ClickException(str(ex))
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/cli/colin.py#L158-L193