function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def update_message_data_string(self): fuz_start = self.current_label_start fuz_end = self.current_label_end num_proto_bits = 10 num_fuz_bits = 16 proto_start = fuz_start - num_proto_bits preambel = "... " if proto_start <= 0: proto_start = 0 preambel = "" proto_end = fuz_end + num_proto_bits postambel = " ..." if proto_end >= len(self.message_data) - 1: proto_end = len(self.message_data) - 1 postambel = "" fuzamble = "" if fuz_end - fuz_start > num_fuz_bits: fuz_end = fuz_start + num_fuz_bits fuzamble = "..." self.ui.lPreBits.setText(preambel + self.message_data[proto_start:self.current_label_start]) self.ui.lFuzzedBits.setText(self.message_data[fuz_start:fuz_end] + fuzamble) self.ui.lPostBits.setText(self.message_data[self.current_label_end:proto_end] + postambel) self.set_add_spinboxes_maximum_on_label_change()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_fuzzing_start_changed(self, value: int): self.ui.spinBoxFuzzingEnd.setMinimum(self.ui.spinBoxFuzzingStart.value()) new_start = self.message.convert_index(value - 1, self.proto_view, 0, False)[0] self.current_label.start = new_start self.current_label.fuzz_values[:] = [] self.update_message_data_string() self.fuzz_table_model.update() self.ui.tblFuzzingValues.resize_me()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_fuzzing_end_changed(self, value: int): self.ui.spinBoxFuzzingStart.setMaximum(self.ui.spinBoxFuzzingEnd.value()) new_end = self.message.convert_index(value - 1, self.proto_view, 0, False)[1] + 1 self.current_label.end = new_end self.current_label.fuzz_values[:] = [] self.update_message_data_string() self.fuzz_table_model.update() self.ui.tblFuzzingValues.resize_me()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_combo_box_fuzzing_label_current_index_changed(self, index: int): self.fuzz_table_model.fuzzing_label = self.current_label self.fuzz_table_model.update() self.update_message_data_string() self.ui.tblFuzzingValues.resize_me() self.ui.spinBoxFuzzingStart.blockSignals(True) self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1) self.ui.spinBoxFuzzingStart.blockSignals(False) self.ui.spinBoxFuzzingEnd.blockSignals(True) self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end) self.ui.spinBoxFuzzingEnd.blockSignals(False)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_btn_add_row_clicked(self): self.current_label.add_fuzz_value() self.fuzz_table_model.update()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_btn_del_row_clicked(self): min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range() self.delete_lines(min_row, max_row)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def delete_lines(self, min_row, max_row): if min_row == -1: self.current_label.fuzz_values = self.current_label.fuzz_values[:-1] else: self.current_label.fuzz_values = self.current_label.fuzz_values[:min_row] + self.current_label.fuzz_values[ max_row + 1:] _ = self.current_label # if user deleted all, this will restore a fuzz value self.fuzz_table_model.update()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_remove_duplicates_state_changed(self): self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked() self.fuzz_table_model.update() self.remove_duplicates()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def set_add_spinboxes_maximum_on_label_change(self): nbits = self.current_label.end - self.current_label.start # Use Bit Start/End for maximum calc. if nbits >= 32: nbits = 31 max_val = 2 ** nbits - 1 self.ui.sBAddRangeStart.setMaximum(max_val - 1) self.ui.sBAddRangeEnd.setMaximum(max_val) self.ui.sBAddRangeEnd.setValue(max_val) self.ui.sBAddRangeStep.setMaximum(max_val) self.ui.spinBoxLowerBound.setMaximum(max_val - 1) self.ui.spinBoxUpperBound.setMaximum(max_val) self.ui.spinBoxUpperBound.setValue(max_val) self.ui.spinBoxBoundaryNumber.setMaximum(int(max_val / 2) + 1) self.ui.spinBoxRandomMinimum.setMaximum(max_val - 1) self.ui.spinBoxRandomMaximum.setMaximum(max_val) self.ui.spinBoxRandomMaximum.setValue(max_val)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_fuzzing_range_start_changed(self, value: int): self.ui.sBAddRangeEnd.setMinimum(value) self.ui.sBAddRangeStep.setMaximum(self.ui.sBAddRangeEnd.value() - value)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_fuzzing_range_end_changed(self, value: int): self.ui.sBAddRangeStart.setMaximum(value - 1) self.ui.sBAddRangeStep.setMaximum(value - self.ui.sBAddRangeStart.value())
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_lower_bound_checked_changed(self): if self.ui.checkBoxLowerBound.isChecked(): self.ui.spinBoxLowerBound.setEnabled(True) self.ui.spinBoxBoundaryNumber.setEnabled(True) elif not self.ui.checkBoxUpperBound.isChecked(): self.ui.spinBoxLowerBound.setEnabled(False) self.ui.spinBoxBoundaryNumber.setEnabled(False) else: self.ui.spinBoxLowerBound.setEnabled(False)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_upper_bound_checked_changed(self): if self.ui.checkBoxUpperBound.isChecked(): self.ui.spinBoxUpperBound.setEnabled(True) self.ui.spinBoxBoundaryNumber.setEnabled(True) elif not self.ui.checkBoxLowerBound.isChecked(): self.ui.spinBoxUpperBound.setEnabled(False) self.ui.spinBoxBoundaryNumber.setEnabled(False) else: self.ui.spinBoxUpperBound.setEnabled(False)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_lower_bound_changed(self): self.ui.spinBoxUpperBound.setMinimum(self.ui.spinBoxLowerBound.value()) self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value() - self.ui.spinBoxLowerBound.value()) / 2))
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_upper_bound_changed(self): self.ui.spinBoxLowerBound.setMaximum(self.ui.spinBoxUpperBound.value() - 1) self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value() - self.ui.spinBoxLowerBound.value()) / 2))
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_random_range_min_changed(self): self.ui.spinBoxRandomMaximum.setMinimum(self.ui.spinBoxRandomMinimum.value())
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_random_range_max_changed(self): self.ui.spinBoxRandomMinimum.setMaximum(self.ui.spinBoxRandomMaximum.value() - 1)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_btn_add_fuzzing_values_clicked(self): if self.ui.comboBoxStrategy.currentIndex() == 0: self.__add_fuzzing_range() elif self.ui.comboBoxStrategy.currentIndex() == 1: self.__add_fuzzing_boundaries() elif self.ui.comboBoxStrategy.currentIndex() == 2: self.__add_random_fuzzing_values()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def __add_fuzzing_boundaries(self): lower_bound = -1 if self.ui.spinBoxLowerBound.isEnabled(): lower_bound = self.ui.spinBoxLowerBound.value() upper_bound = -1 if self.ui.spinBoxUpperBound.isEnabled(): upper_bound = self.ui.spinBoxUpperBound.value() num_vals = self.ui.spinBoxBoundaryNumber.value() self.fuzz_table_model.add_boundaries(lower_bound, upper_bound, num_vals)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def remove_duplicates(self): if self.ui.chkBRemoveDuplicates.isChecked(): for lbl in self.message.message_type: seq = lbl.fuzz_values[:] seen = set() add_seen = seen.add lbl.fuzz_values = [l for l in seq if not (l in seen or add_seen(l))]
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def set_current_label_name(self): self.current_label.name = self.ui.comboBoxFuzzingLabel.currentText() self.ui.comboBoxFuzzingLabel.setItemText(self.ui.comboBoxFuzzingLabel.currentIndex(), self.current_label.name)
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def on_fuzz_msg_changed(self, index: int): self.ui.comboBoxFuzzingLabel.setDisabled(False) sel_label_ind = self.ui.comboBoxFuzzingLabel.currentIndex() self.ui.comboBoxFuzzingLabel.blockSignals(True) self.ui.comboBoxFuzzingLabel.clear() if len(self.message.message_type) == 0: self.ui.comboBoxFuzzingLabel.setDisabled(True) return self.ui.comboBoxFuzzingLabel.addItems([lbl.name for lbl in self.message.message_type]) self.ui.comboBoxFuzzingLabel.blockSignals(False) if sel_label_ind < self.ui.comboBoxFuzzingLabel.count(): self.ui.comboBoxFuzzingLabel.setCurrentIndex(sel_label_ind) else: self.ui.comboBoxFuzzingLabel.setCurrentIndex(0) self.fuzz_table_model.fuzzing_label = self.current_label self.fuzz_table_model.update() self.update_message_data_string()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def setUp(self): self.oFile = vhdlFile.vhdlFile(lFile) self.assertIsNone(eError) self.oFile.set_indent_map(dIndentMap)
jeremiah-c-leary/vhdl-style-guide
[ 129, 31, 129, 57, 1499106283 ]
def __init__(self, cs_bar_pin, clk_pin=1000000, mosi_pin=0, miso_pin=0, chip='MCP3208', channel_max=None, bit_length=None, single_ended=True): """Initialize the code and set the GPIO pins. The last argument, ch_max, is 2 for the MCP3202, 4 for the MCP3204 or 8 for the MCS3208.""" self._CLK = clk_pin self._MOSI = mosi_pin self._MISO = miso_pin self._CS_bar = cs_bar_pin chip_dictionary = { "MCP3202": (2, 12), "MCP3204": (4, 12), "MCP3208": (8, 12), "MCP3002": (2, 10), "MCP3004": (4, 10), "MCP3008": (8, 10) } if chip in chip_dictionary: self._ChannelMax = chip_dictionary[chip][0] self._BitLength = chip_dictionary[chip][1] elif chip is None and (channel_max is not None) and (bit_length is not None): self._ChannelMax = channel_max self._BitLength = bit_length else: print("Unknown chip: {} - Please re-initialize.") self._ChannelMax = 0 self._BitLength = 0 return self._SingleEnded = single_ended self._Vref = 3.3 self._values = MyValues(self.read_adc, self._ChannelMax) self._volts = MyValues(self.read_volts, self._ChannelMax) # This is used to speed up the SPIDEV communication. Send out MSB first. # control[0] - bit7-3: upper 5 bits 0, because we can only send 8 bit sequences. # - bit2 : Start bit - starts conversion in ADCs # - bit1 : Select single_ended=1 or differential=0 # - bit0 : D2 high bit of channel select. # control[1] - bit7 : D1 middle bit of channel select. # - bit6 : D0 low bit of channel select. # - bit5-0 : Don't care. if self._SingleEnded: self._control0 = [0b00000110, 0b00100000, 0] # Pre-compute part of the control word. else: self._control0 = [0b00000100, 0b00100000, 0] # Pre-compute part of the control word. if self._MOSI > 0: # Bing Bang mode assert self._MISO != 0 and self._CLK < 32 if GPIO.getmode() != 11: GPIO.setmode(GPIO.BCM) # Use the BCM numbering scheme GPIO.setup(self._CLK, GPIO.OUT) # Setup the ports for in and output GPIO.setup(self._MOSI, GPIO.OUT) GPIO.setup(self._MISO, GPIO.IN) GPIO.setup(self._CS_bar, GPIO.OUT) GPIO.output(self._CLK, 0) # Set the clock low. GPIO.output(self._MOSI, 0) # Set the Master Out low GPIO.output(self._CS_bar, 1) # Set the CS_bar high else: self._dev = spidev.SpiDev(0, self._CS_bar) # Start a SpiDev device self._dev.mode = 0 # Set SPI mode (phase) self._dev.max_speed_hz = self._CLK # Set the data rate self._dev.bits_per_word = 8 # Number of bit per word. ALWAYS 8
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def get_channel_max(self): """Return the maximum number of channels""" return self._ChannelMax
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def get_value_max(self): """Return the maximum value possible for an ADC read""" return 2 ** self._BitLength - 1
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def read_bit(self): """ Read a single bit from the ADC and pulse clock.""" if self._MOSI == 0: return 0 # # The output is going out on the falling edge of the clock, # and is to be read on the rising edge of the clock. # Clock should be already low, and data should already be set. GPIO.output(self._CLK, 1) # Set the clock high. Ready to read. bit = GPIO.input(self._MISO) # Read the bit. GPIO.output(self._CLK, 0) # Return clock low, next bit will be set. return bit
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def read_volts(self, channel): """Read the ADC value from channel and convert to volts, assuming that Vref is set correctly. """ return self._Vref * self.read_adc(channel) / self.get_value_max()
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def values(self): """ADC values presented as a list.""" return self._values
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def volts(self): """ADC voltages presented as a list""" return self._volts
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def accuracy(self): """The fractional voltage of the least significant bit. """ return self._Vref / float(self.get_value_max())
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def vref(self): """Reference voltage used by the chip. You need to set this. It defaults to 3.3V""" return self._Vref
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def vref(self, vr): self._Vref = vr
mholtrop/Phys605
[ 4, 9, 4, 1, 1477526719 ]
def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style)
arsenetar/dupeguru
[ 3476, 328, 3476, 328, 1371863263 ]
def show(self): super().show() self.inputLine.setFocus()
arsenetar/dupeguru
[ 3476, 328, 3476, 328, 1371863263 ]
def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear()
arsenetar/dupeguru
[ 3476, 328, 3476, 328, 1371863263 ]
def restoreDefaults(self): self.model.restore_defaults()
arsenetar/dupeguru
[ 3476, 328, 3476, 328, 1371863263 ]
def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False
arsenetar/dupeguru
[ 3476, 328, 3476, 328, 1371863263 ]
def display_help_message(self): self.app.show_message( tr( """\
arsenetar/dupeguru
[ 3476, 328, 3476, 328, 1371863263 ]
def last_two_digits(year): return year - ((year // 100) * 100)
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def swap_format_elements(format, first, second): # format is a DateFormat swapped = format.copy() elems = swapped.elements TYPE2CHAR = {DAY: 'd', MONTH: 'M', YEAR: 'y'} first_char = TYPE2CHAR[first] second_char = TYPE2CHAR[second] first_index = [i for i, x in enumerate(elems) if x.startswith(first_char)][0] second_index = [i for i, x in enumerate(elems) if x.startswith(second_char)][0] elems[first_index], elems[second_index] = elems[second_index], elems[first_index] return swapped
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def __init__(self, iwin, account, target_account, parsing_date_format): self.iwin = iwin self.account = account self._selected_target = target_account self.name = account.name entries = iwin.loader.accounts.entries_for_account(account) self.count = len(entries) self.matches = [] # [[ref, imported]] self.parsing_date_format = parsing_date_format self.max_day = 31 self.max_month = 12 self.max_year = 99 # 2 digits self._match_entries() self._swap_possibilities = set() self._compute_swap_possibilities()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def _match_entries(self): to_import = list(self.iwin.loader.accounts.entries_for_account(self.account)) reference2entry = {} for entry in (e for e in to_import if e.reference): reference2entry[entry.reference] = entry self.matches = [] if self.selected_target is not None: entries = self.iwin.document.accounts.entries_for_account(self.selected_target) for entry in entries: if entry.reference in reference2entry: other = reference2entry[entry.reference] if entry.reconciled: self.iwin.import_table.dont_import.add(other) to_import.remove(other) del reference2entry[entry.reference] else: other = None if other is not None or not entry.reconciled: self.matches.append([entry, other]) self.matches += [[None, entry] for entry in to_import] self._sort_matches()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def bind(self, existing, imported): [match1] = [m for m in self.matches if m[0] is existing] [match2] = [m for m in self.matches if m[1] is imported] assert match1[1] is None assert match2[0] is None match1[1] = match2[1] self.matches.remove(match2)
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def match_entries_by_date_and_amount(self, threshold): delta = datetime.timedelta(days=threshold) unmatched = ( to_import for ref, to_import in self.matches if ref is None) unmatched_refs = ( ref for ref, to_import in self.matches if to_import is None) amount2refs = defaultdict(list) for entry in unmatched_refs: amount2refs[entry.amount].append(entry) for entry in unmatched: if entry.amount not in amount2refs: continue potentials = amount2refs[entry.amount] for ref in potentials: if abs(ref.date - entry.date) <= delta: self.bind(ref, entry) potentials.remove(ref) self._sort_matches()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def selected_target(self): return self._selected_target
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def selected_target(self, value): self._selected_target = value self._match_entries()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def __init__(self, mainwindow, target_account=None): super().__init__() if not hasattr(mainwindow, 'loader'): raise ValueError("Nothing to import!") self.mainwindow = mainwindow self.document = mainwindow.document self.app = self.document.app self._selected_pane_index = 0 self._selected_target_index = 0 def setfunc(index): self.view.set_swap_button_enabled(self.can_perform_swap()) self.swap_type_list = LinkedSelectableList(items=[ "<placeholder> Day <--> Month", "<placeholder> Month <--> Year", "<placeholder> Day <--> Year", tr("Description <--> Payee"), tr("Invert Amounts"), ], setfunc=setfunc) self.swap_type_list.selected_index = SwapType.DayMonth self.panes = [] self.import_table = ImportTable(self) self.loader = self.mainwindow.loader self.target_accounts = [ a for a in self.document.accounts if a.is_balance_sheet_account()] self.target_accounts.sort(key=lambda a: a.name.lower()) accounts = [] for account in self.loader.accounts: if account.is_balance_sheet_account(): entries = self.loader.accounts.entries_for_account(account) if len(entries): new_name = self.document.accounts.new_name(account.name) if new_name != account.name: self.loader.accounts.rename_account(account, new_name) accounts.append(account) parsing_date_format = DateFormat.from_sysformat(self.loader.parsing_date_format) for account in accounts: target = target_account if target is None and account.reference: target = getfirst( t for t in self.target_accounts if t.reference == account.reference ) self.panes.append( AccountPane(self, account, target, parsing_date_format))
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def _can_swap_date_fields(self, first, second): # 'day', 'month', 'year' pane = self.selected_pane if pane is None: return False return pane.can_swap_date_fields(first, second)
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def _refresh_target_selection(self): if not self.panes: return target = self.selected_pane.selected_target self._selected_target_index = 0 if target is not None: try: self._selected_target_index = self.target_accounts.index(target) + 1 except ValueError: pass
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def _swap_date_fields(self, first, second, apply_to_all): # 'day', 'month', 'year' assert self._can_swap_date_fields(first, second) if apply_to_all: panes = [p for p in self.panes if p.can_swap_date_fields(first, second)] else: panes = [self.selected_pane] def switch_func(txn): txn.date = swapped_date(txn.date, first, second) self._swap_fields(panes, switch_func) # Now, lets' change the date format on these panes for pane in panes: basefmt = self.selected_pane.parsing_date_format swapped = swap_format_elements(basefmt, first, second) pane.parsing_date_format = swapped pane._sort_matches() self.import_table.refresh() self._refresh_swap_list_items()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def switch_func(txn): txn.description, txn.payee = txn.payee, txn.description
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def _swap_fields(self, panes, switch_func): seen = set() for pane in panes: entries = self.loader.accounts.entries_for_account(pane.account) txns = dedupe(e.transaction for e in entries) for txn in txns: if txn.affected_accounts() & seen: # We've already swapped this txn in a previous pane. continue switch_func(txn) seen.add(pane.account) self.import_table.refresh()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def _view_updated(self): if self.document.can_restore_from_prefs(): self.restore_view() # XXX Logically, we should call _update_selected_pane() but doing so # make tests fail. to investigate. self._refresh_target_selection() self.view.update_selected_pane() self._refresh_swap_list_items() self.import_table.refresh()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def can_perform_swap(self): index = self.swap_type_list.selected_index if index == SwapType.DayMonth: return self._can_swap_date_fields(DAY, MONTH) elif index == SwapType.MonthYear: return self._can_swap_date_fields(MONTH, YEAR) elif index == SwapType.DayYear: return self._can_swap_date_fields(DAY, YEAR) else: return True
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def import_selected_pane(self): pane = self.selected_pane matches = pane.matches matches = [ (e, ref) for ref, e in matches if e is not None and e not in self.import_table.dont_import] if pane.selected_target is not None: # We import in an existing account, adjust all the transactions accordingly target_account = pane.selected_target else: target_account = None self.document.import_entries(target_account, pane.account, matches) self.mainwindow.revalidate() self.close_pane(self.selected_pane_index) self.view.close_selected_tab()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def perform_swap(self, apply_to_all=False): index = self.swap_type_list.selected_index if index == SwapType.DayMonth: self._swap_date_fields(DAY, MONTH, apply_to_all=apply_to_all) elif index == SwapType.MonthYear: self._swap_date_fields(MONTH, YEAR, apply_to_all=apply_to_all) elif index == SwapType.DayYear: self._swap_date_fields(DAY, YEAR, apply_to_all=apply_to_all) elif index == SwapType.DescriptionPayee: self._swap_description_payee(apply_to_all=apply_to_all) elif index == SwapType.InvertAmount: self._invert_amounts(apply_to_all=apply_to_all)
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def selected_pane(self): return self.panes[self.selected_pane_index] if self.panes else None
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def selected_pane_index(self): return self._selected_pane_index
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def selected_pane_index(self, value): if value >= len(self.panes): return self._selected_pane_index = value self._refresh_target_selection() self._update_selected_pane()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def selected_target_account(self): return self.selected_pane.selected_target
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def selected_target_account_index(self): return self._selected_target_index
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def selected_target_account_index(self, value): target = self.target_accounts[value - 1] if value > 0 else None self.selected_pane.selected_target = target self._selected_target_index = value self.import_table.refresh()
hsoft/moneyguru
[ 155, 42, 155, 93, 1371911074 ]
def process(r1, r2, c1, c2): for i in range(r1, r2): for j in range(c1, c2): if 0 <= i < m and 0 <= j < n: if g[i][j] == None: s[i][j] = 0 elif i == 0 or j == 0: s[i][j] = 1 elif g[i-1][j] != g[i][j] and g[i][j-1] != g[i][j] and \ g[i-1][j-1] == g[i][j]: s[i][j] = 1 + min(s[i-1][j], s[i][j-1], s[i-1][j-1]) else: s[i][j] = 1 heappush(q, (-s[i][j], i, j))
KirarinSnow/Google-Code-Jam
[ 84, 38, 84, 1, 1276377660 ]
def __init__(self, language="en"): """ Constructor for the wordnet manager. It takes a main language. """ self.__language = language
domenicosolazzo/jroc
[ 6, 3, 6, 21, 1434733779 ]
def __nameToWordnetCode(self, name): """ It returns the wordnet code for a given language name """ if not self.__isLanguageAvailable(language_name=name): raise Exception("Wordnet code not found for the language name %s " % name) name = name.lower() languageShortCode = AVAILABLE_LANGUAGES_NAMES[name] wordnetCode = self.__shortCodeToWordnetCode(code=languageShortCode) return wordnetCode
domenicosolazzo/jroc
[ 6, 3, 6, 21, 1434733779 ]
def __getSynsets(self, word, wordNetCode): """ It returns the synsets given both word and language code """ from nltk.corpus import wordnet as wn synsets = wn.synsets(word, lang=wordNetCode) return synsets
domenicosolazzo/jroc
[ 6, 3, 6, 21, 1434733779 ]
def getSynonyms(self, words=[], language_code="en"): """ Get the synonyms from a list of words. :words: A list of words :language_code: the language for the synonyms. """ if words is None or not isinstance(words, list) or list(words) <= 0: return [] if not self.__isLanguageAvailable(code=language_code): return [] wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: result[word] = dict([('lemmas', self.getLemmas(word,languageCode=language_code))]) return result
domenicosolazzo/jroc
[ 6, 3, 6, 21, 1434733779 ]
def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup)
espressopp/espressopp
[ 38, 32, 38, 48, 1412685868 ]
def setup_class(cls): cls.K = nx.krackhardt_kite_graph() cls.P3 = nx.path_graph(3) cls.P4 = nx.path_graph(4) cls.K5 = nx.complete_graph(5) cls.C4 = nx.cycle_graph(4) cls.T = nx.balanced_tree(r=2, h=2) cls.Gb = nx.Graph() cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.florentine_families_graph() cls.F = F cls.LM = nx.les_miserables_graph() # Create random undirected, unweighted graph for testing incremental version cls.undirected_G = nx.fast_gnp_random_graph(n=100, p=0.6, seed=123) cls.undirected_G_cc = nx.closeness_centrality(cls.undirected_G)
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_digraph(self): G = nx.path_graph(3, create_using=nx.DiGraph()) c = nx.closeness_centrality(G) cr = nx.closeness_centrality(G.reverse()) d = {0: 0.0, 1: 0.500, 2: 0.667} dr = {0: 0.667, 1: 0.500, 2: 0.0} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3) assert almost_equal(cr[n], dr[n], places=3)
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_p3_closeness(self): c = nx.closeness_centrality(self.P3) d = {0: 0.667, 1: 1.000, 2: 0.667} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3)
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_florentine_families_closeness(self): c = nx.closeness_centrality(self.F) d = { "Acciaiuoli": 0.368, "Albizzi": 0.483, "Barbadori": 0.4375, "Bischeri": 0.400, "Castellani": 0.389, "Ginori": 0.333, "Guadagni": 0.467, "Lamberteschi": 0.326, "Medici": 0.560, "Pazzi": 0.286, "Peruzzi": 0.368, "Ridolfi": 0.500, "Salviati": 0.389, "Strozzi": 0.4375, "Tornabuoni": 0.483, } for n in sorted(self.F): assert almost_equal(c[n], d[n], places=3)
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_weighted_closeness(self): edges = [ ("s", "u", 10), ("s", "x", 5), ("u", "v", 1), ("u", "x", 2), ("v", "y", 1), ("x", "u", 3), ("x", "v", 5), ("x", "y", 2), ("y", "s", 7), ("y", "v", 6), ] XG = nx.Graph() XG.add_weighted_edges_from(edges) c = nx.closeness_centrality(XG, distance="weight") d = {"y": 0.200, "x": 0.286, "s": 0.138, "u": 0.235, "v": 0.200} for n in sorted(XG): assert almost_equal(c[n], d[n], places=3)
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def pick_add_edge(g): u = nx.utils.arbitrary_element(g) possible_nodes = set(g.nodes()) neighbors = list(g.neighbors(u)) + [u] possible_nodes.difference_update(neighbors) v = nx.utils.arbitrary_element(possible_nodes) return (u, v)
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def pick_remove_edge(g): u = nx.utils.arbitrary_element(g) possible_nodes = list(g.neighbors(u)) v = nx.utils.arbitrary_element(possible_nodes) return (u, v)
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_wrong_size_prev_cc_raises(self): with pytest.raises(nx.NetworkXError): G = self.undirected_G.copy() edge = self.pick_add_edge(G) insert = True prev_cc = self.undirected_G_cc.copy() prev_cc.pop(0) nx.incremental_closeness_centrality(G, edge, prev_cc, insert)
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def test_zero_centrality(self): G = nx.path_graph(3) prev_cc = nx.closeness_centrality(G) edge = self.pick_remove_edge(G) test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insertion=False) G.remove_edges_from([edge]) real_cc = nx.closeness_centrality(G) shared_items = set(test_cc.items()) & set(real_cc.items()) assert len(shared_items) == len(real_cc) assert 0 in test_cc.values()
SpaceGroupUCL/qgisSpaceSyntaxToolkit
[ 96, 34, 96, 65, 1403185627 ]
def forwards(self, orm): # Adding unique constraint on 'Vendeur', fields ['code_permanent'] db.create_unique(u'encefal_vendeur', ['code_permanent'])
nilovna/EnceFAL
[ 6, 11, 6, 1, 1310319432 ]
def __init__ (self, canvas, objects): self.canvas = canvas self.objects = objects
clearclaw/xxpaper
[ 25, 6, 25, 1, 1376260497 ]
def __init__(self, p_str): TodoBase.__init__(self, p_str) self.attributes = {}
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def start_date(self): """ Returns a date object of the todo's start date. """ return self.get_date(config().tag_start())
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def is_active(self): """ Returns True when the start date is today or in the past and the task has not yet been completed. """ start = self.start_date() return not self.is_completed() and (not start or start <= date.today())
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def days_till_due(self): """ Returns the number of days till the due date. Returns a negative number of days when the due date is in the past. Returns 0 when the task has no due date. """ due = self.due_date() if due: diff = due - date.today() return diff.days return 0
bram85/topydo
[ 653, 78, 653, 61, 1413726583 ]
def _get_datasets_settings(self): return { "nipa-section1-10101-a": { 'dataset_code': 'nipa-section1-10101-a', 'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually', 'last_update': None, 'metadata': { 'filename': 'nipa-section1.xls.zip', 'sheet_name': '10101 Ann', 'url': 'http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2' }, } }
Widukind/dlstats
[ 13, 15, 13, 1, 1365761108 ]
def _load_files(self, dataset_code): url = "http://www.bea.gov/national/nipaweb/GetCSV.asp?GetWhat=SS_Data/Section1All_xls.zip&Section=2" self.register_url(url, self.DATASETS[dataset_code]["filepath"])
Widukind/dlstats
[ 13, 15, 13, 1, 1365761108 ]
def test_load_datasets_first(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsFirst([dataset_code])
Widukind/dlstats
[ 13, 15, 13, 1, 1365761108 ]
def test_load_datasets_update(self): dataset_code = "nipa-section1-10101-a" self._load_files(dataset_code) self.assertLoadDatasetsUpdate([dataset_code])
Widukind/dlstats
[ 13, 15, 13, 1, 1365761108 ]
def test_build_data_tree(self): dataset_code = "nipa-section1-10101-a" self.assertDataTree(dataset_code)
Widukind/dlstats
[ 13, 15, 13, 1, 1365761108 ]
def test_upsert_dataset_10101(self): # nosetests -s -v dlstats.tests.fetchers.test_bea:FetcherTestCase.test_upsert_dataset_10101
Widukind/dlstats
[ 13, 15, 13, 1, 1365761108 ]
def make_arg_parser(): parser = argparse.ArgumentParser(description='This is the commandline interface for shi7_learning', usage='shi7_learning v{version}\nshi7_learning.py -i <input> -o <output> ...'.format(version=__version__)) parser.add_argument('-i', '--input', help='Set the directory path of the fastq directory OR oligos.txt if splitting', required=True) parser.add_argument('-o', '--output', help='Set the directory path of the output (default: cwd)', default=os.getcwd()) parser.add_argument('--debug', help='Retain all intermediate files (default: Disabled)', dest='debug', action='store_true') parser.add_argument('-t', '--threads', help='Set the number of threads (default: %(default)s)', default=min(multiprocessing.cpu_count(), 16)) parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__) parser.set_defaults() return parser
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def limit_fastq(fastq_gen, num_sequences=1000): for i in range(num_sequences): try: yield next(fastq_gen) except StopIteration: return
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def count_num_lines(path): with open(path) as path_inf: return sum(1 for line in path_inf)
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def check_sequence_name(path_R1, path_R2): with open(path_R1) as path_inf_R1, open(path_R2) as path_inf_R2: fastq_gen_R1 = read_fastq(path_inf_R1) fastq_gen_R2 = read_fastq(path_inf_R2) for gen_R1, gen_R2 in zip(fastq_gen_R1,fastq_gen_R2): title_R1, title_R2 = gen_R1[0], gen_R2[0] if len(title_R1) != len(title_R2): return False diff_idx = [i for i in range(len(title_R1)) if title_R1[i] != title_R2[i]] if len(diff_idx) != 1: return False if int(title_R2[diff_idx[0]]) - int(title_R1[diff_idx[0]]) != 1: return False return True
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def get_directory_size(path): return sum([get_file_size(os.path.join(path, fastq)) for fastq in os.listdir(path)])
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def choose_axe_adaptors(path_subsampled_fastqs, paired_end, output_path, threads): adapters = ['TruSeq2', 'TruSeq3', 'TruSeq3-2', 'Nextera'] threads = min(threads, multiprocessing.cpu_count(), 16) original_size = get_directory_size(os.path.dirname(path_subsampled_fastqs[0])) logging.info('Original size of the subsampled_fastqs = ' + str(original_size)) best_size = original_size best_adap = None for adapter in adapters: if paired_end: axe_adaptors_paired_end(path_subsampled_fastqs, output_path, adapter, threads, shell=False) else: axe_adaptors_single_end(path_subsampled_fastqs, output_path, adapter, threads, shell=False) fastqs_path_size = get_directory_size(output_path) logging.info("Adapters: {adapter}\tFile Size: {filesize}".format(adapter=adapter, filesize=fastqs_path_size)) if fastqs_path_size <= best_size: best_size = fastqs_path_size best_adap = adapter if best_size < 0.995*original_size: # Actually write the best files again for use in later steps logging.info("Best Adapters: {adapter}\tFile Size: {filesize}".format(adapter=best_adap, filesize=best_size)) if paired_end: files = axe_adaptors_paired_end(path_subsampled_fastqs, output_path, best_adap, threads, shell=False) else: files = axe_adaptors_single_end(path_subsampled_fastqs, output_path, best_adap, threads, shell=False) return best_adap, best_size, files else: return None, original_size, path_subsampled_fastqs
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def flash_check_cv(flash_output_path): hist_files = [os.path.join(flash_output_path, f) for f in os.listdir(flash_output_path) if f.endswith('.hist')] total_cv = total_mean = 0 for f in hist_files: with open(f) as inf: csv_inf = csv.reader(inf, delimiter="\t") x2f = 0 sum = 0 cnt = 0 for row in csv_inf: row = [int(r) for r in row] cnt = cnt + row[1] sum = sum + row[0] * row[1] x2f = x2f + row[0] * row[0] * row[1] mean = sum/cnt std = math.sqrt((x2f - sum*sum/cnt)/(cnt-1)) cv = std/mean total_cv = total_cv + cv total_mean = total_mean + mean total_files = len(hist_files) return total_cv/total_files, total_mean/total_files
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def template_input(input): input = os.path.abspath(input) # input, input_cmd return "input\t{}".format(input), ["--input", input]
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def template_trim(filt_q, trim_q): return "filt_q: %d, trim_q: %d" % (filt_q, trim_q), ["--filter_qual", str(filt_q), "--trim_qual", str(trim_q)]
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]
def template_output(output): # output, output_cmd output = os.path.abspath(output) return "output\t{}".format(output), ["--output", output]
knights-lab/shi7
[ 17, 7, 17, 9, 1471630281 ]