code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
fmt,plot='svg',0 if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-sav' in sys.argv: plot=1 if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-f' in sys.argv: # ask for filename ind...
def main()
NAME qqplot.py DESCRIPTION makes qq plot of input data against a Normal distribution. INPUT FORMAT takes real numbers in single column SYNTAX qqplot.py [-h][-i][-f FILE] OPTIONS -f FILE, specify file on command line -fmt [png,svg,jpg,eps] set...
3.695779
3.633422
1.017162
keycode = event.GetKeyCode() meta_down = event.MetaDown() or event.GetCmdDown() if keycode == 86 and meta_down: # treat it as if it were a wx.EVT_TEXT_SIZE self.do_fit(event)
def on_key_down(self, event)
If user does command v, re-size window in case pasting has changed the content size.
6.863647
5.940163
1.155464
#self.grid.ShowScrollbars(wx.SHOW_SB_NEVER, wx.SHOW_SB_NEVER) if event: event.Skip() self.main_sizer.Fit(self) disp_size = wx.GetDisplaySize() actual_size = self.GetSize() # if there isn't enough room to display new content # resize the frame ...
def do_fit(self, event, min_size=None)
Re-fit the window to the size of the content.
2.825481
2.777517
1.017269
# if mode == 'open', show no matter what. # if mode == 'close', close. otherwise, change state btn = self.toggle_help_btn shown = self.help_msg_boxsizer.GetStaticBox().IsShown() # if mode is specified, do that mode if mode == 'open': self.help_msg_bo...
def toggle_help(self, event, mode=None)
Show/hide help message on help button click.
2.999309
2.857282
1.049707
btn = event.GetEventObject() if btn.Label == 'Show method codes': self.code_msg_boxsizer.ShowItems(True) btn.SetLabel('Hide method codes') else: self.code_msg_boxsizer.ShowItems(False) btn.SetLabel('Show method codes') self.do_fit(...
def toggle_codes(self, event)
Show/hide method code explanation widget on button click
3.354722
2.891415
1.160235
if event: col = event.GetCol() if not col: return label = self.grid.GetColLabelValue(col) if '**' in label: label = label.strip('**') elif '^^' in label: label = label.strip('^^') if label in self.reqd_headers: ...
def remove_col_label(self, event=None, col=None)
check to see if column is required if it is not, delete it from grid
5.201548
4.889103
1.063906
col_labels = self.grid.col_labels dia = pw.ChooseOne(self, yes="Add single columns", no="Add groups") result1 = dia.ShowModal() if result1 == wx.ID_CANCEL: return elif result1 == wx.ID_YES: items = sorted([col_name for col_name in self.dm.index if...
def on_add_cols(self, event)
Show simple dialog that allows user to add a new column name
4.433463
4.457085
0.9947
already_present = [] for group in groups: col_names = self.dm[self.dm['group'] == group].index for col in col_names: if col not in self.grid.col_labels: col_number = self.grid.add_col(col) # add to appropriate heade...
def add_new_header_groups(self, groups)
compile list of all headers belonging to all specified groups eliminate all headers that are already included add any req'd drop-down menus return errors
3.42226
3.25112
1.05264
already_present = [] for name in new_headers: if name: if name not in self.grid.col_labels: col_number = self.grid.add_col(name) # add to appropriate headers list # add drop down menus for user-added column ...
def add_new_grid_headers(self, new_headers)
Add in all user-added headers. If those new headers depend on other headers, add the other headers too.
3.575727
3.438666
1.039859
num_rows = self.rows_spin_ctrl.GetValue() #last_row = self.grid.GetNumberRows() for row in range(num_rows): self.grid.add_row() #if not self.grid.changes: # self.grid.changes = set([]) #self.grid.changes.add(last_row) #last_...
def on_add_rows(self, event)
add rows to grid
3.522084
3.290507
1.070377
text = "Are you sure? If you select delete you won't be able to retrieve these rows..." dia = pw.ChooseOne(self, "Yes, delete rows", "Leave rows for now", text) dia.Centre() result = dia.ShowModal() if result == wx.ID_NO: return default = (255, 255, ...
def on_remove_row(self, event, row_num=-1)
Remove specified grid row. If no row number is given, remove the last row.
3.450295
3.470762
0.994103
if event.Col == -1 and event.Row == -1: pass if event.Row < 0: if self.remove_cols_mode: self.remove_col_label(event) else: self.drop_down_menu.on_label_click(event) else: if event.Col < 0 and self.grid_typ...
def onLeftClickLabel(self, event)
When user clicks on a grid label, determine if it is a row label or a col label. Pass along the event to the appropriate function. (It will either highlight a column for editing all values, or highlight a row for deletion).
5.457751
4.836177
1.128526
if self.grid.changes: print("-W- Your changes will be overwritten...") wind = pw.ChooseOne(self, "Import file anyway", "Save grid first", "-W- Your grid has unsaved changes which will be overwritten if you import a file now...") wind.C...
def onImport(self, event)
Import a MagIC-format file
4.224576
4.1271
1.023619
if self.grid.changes: dlg1 = wx.MessageDialog(self, caption="Message:", message="Are you sure you want to exit this grid?\nYour changes will not be saved.\n ", style=wx.OK|wx.CANCEL) result = dlg1.ShowModal(...
def onCancelButton(self, event)
Quit grid with warning if unsaved changes present
3.30761
2.824442
1.171066
# tidy up drop_down menu if self.drop_down_menu: self.drop_down_menu.clean_up() # then save actual data self.grid_builder.save_grid_data() if not event and not alert: return # then alert user wx.MessageBox('Saved!', 'Info', ...
def onSave(self, event, alert=False, destroy=True)
Save grid data
5.236491
4.679697
1.118981
if self.grid.GetSelectionBlockTopLeft(): #top_left = self.grid.GetSelectionBlockTopLeft() #bottom_right = self.grid.GetSelectionBlockBottomRight() # awkward hack to fix wxPhoenix memory problem, (Github issue #221) bottom_right = eval(repr(self.grid.GetSe...
def onDragSelection(self, event)
Set self.df_slice based on user's selection
3.253
3.007522
1.081621
if event.CmdDown() or event.ControlDown(): if event.GetKeyCode() == 67: self.onCopySelection(None)
def onKey(self, event)
Copy selection if control down and 'c'
5.228439
3.644622
1.434563
# do clean up here!!! if self.drop_down_menu: self.drop_down_menu.clean_up() # save all grid data self.grid_builder.save_grid_data() df = self.contribution.tables[self.grid_type].df # write df to clipboard for pasting # header arg determines w...
def onSelectAll(self, event)
Selects full grid and copies it to the Clipboard
11.362897
10.514751
1.080662
if self.df_slice is not None: pd.DataFrame.to_clipboard(self.df_slice, header=False, index=False) self.grid.ClearSelection() self.df_slice = None print('-I- You have copied the selected cells. You may paste them into a text document or spreadsheet using ...
def onCopySelection(self, event)
Copies self.df_slice to the Clipboard if slice exists
9.071151
7.221694
1.256097
changes = None # if there is a MagicDataFrame, extract data from it if isinstance(self.magic_dataframe, cb.MagicDataFrame): # get columns and reorder slightly col_labels = list(self.magic_dataframe.df.columns) for ex_col in self.exclude_cols: ...
def make_grid(self)
return grid
2.816108
2.812181
1.001397
if isinstance(self.magic_dataframe, cb.MagicDataFrame): for col in ['age', 'age_unit']: if col not in self.grid.col_labels: self.grid.add_col(col) for level in ['locations', 'sites', 'samples', 'specimens']: if level in self.co...
def add_age_defaults(self)
Add columns as needed: age, age_unit, specimen, sample, site, location.
5.023109
3.827202
1.312475
empty = True # df IS empty if there are no rows if not any(self.magic_dataframe.df.index): empty = True # df is NOT empty if there are at least two rows elif len(self.grid.row_labels) > 1: empty = False # if there is one row, df MIGHT be e...
def current_grid_empty(self)
Check to see if grid is empty except for default values
5.083438
4.912947
1.034702
if not self.grid.changes: print('-I- No changes to save') return starred_cols = self.grid.remove_starred_labels() # locks in value in cell currently edited self.grid.SaveEditControlValue() # changes is a dict with key values == row number ...
def save_grid_data(self)
Save grid data in the data object
6.876109
6.84423
1.004658
defaults = {'result_quality': 'g', 'result_type': 'i', 'orientation_quality': 'g', 'citations': 'This study'} for col_name in defaults: if col_name in self.grid.col_labels: # try to grab existing values from...
def fill_defaults(self)
Fill in self.grid with default values in certain columns. Only fill in new values if grid is missing those values.
3.754047
3.52992
1.063494
specimens, samples, sites, locations = "", "", "", "" children = {'specimen': specimens, 'sample': samples, 'site': sites, 'location': locations} for dtype in children: header_name = 'er_' + dtype + '_names' if result_data[header_name]: ...
def get_result_children(self, result_data)
takes in dict in form of {'er_specimen_names': 'name1:name2:name3'} and so forth. returns lists of specimens, samples, sites, and locations
3.542925
2.73432
1.295725
# extract arguments from sys.argv if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg("-WD", default_val=".") input_dir_path = pmag.get_named_arg('-ID', '') if not input_dir_path: input_dir_path = dir_path in_file = pmag.get_named_arg("-...
def main()
NAME eqarea_magic.py DESCRIPTION makes equal area projections from declination/inclination data SYNTAX eqarea_magic.py [command line options] INPUT takes magic formatted sites, samples, specimens, or measurements OPTIONS -h prints help message and quits ...
2.539676
1.972078
1.287817
#self.grid.ShowScrollbars(wx.SHOW_SB_NEVER, wx.SHOW_SB_NEVER) if event: event.Skip() self.main_sizer.Fit(self) disp_size = wx.GetDisplaySize() actual_size = self.GetSize() rows = self.grid.GetNumberRows() # if there isn't enough room to displa...
def do_fit(self, event)
Re-fit the window to the size of the content.
3.974355
3.790308
1.048557
if self.grid.changes: self.onSave(None) label = event.GetEventObject().Label self.er_magic.age_type = label self.grid.Destroy() # normally grid_frame is reset to None when grid is destroyed # in this case we are simply replacing the grid, so we nee...
def toggle_ages(self, event)
Switch the type of grid between site/sample (Users may add ages at either level)
4.728818
4.594127
1.029318
er_possible_headers = self.grid_headers[self.grid_type]['er'][2] pmag_possible_headers = self.grid_headers[self.grid_type]['pmag'][2] er_actual_headers = self.grid_headers[self.grid_type]['er'][0] pmag_actual_headers = self.grid_headers[self.grid_type]['pmag'][0] col = e...
def remove_col_label(self, event):#, include_pmag=True)
check to see if column is required if it is not, delete it from grid
3.02886
2.953706
1.025444
col_labels = self.grid.col_labels # do not list headers that are already column labels in the grid er_items = [head for head in self.grid_headers[self.grid_type]['er'][2] if head not in col_labels] # remove unneeded headers er_items = builder.remove_list_headers(er_items...
def on_add_cols(self, event)
Show simple dialog that allows user to add a new column name
4.546682
4.5315
1.00335
def add_pmag_reqd_headers(): if self.grid_type == 'result': return [] add_in = [] col_labels = self.grid.col_labels for reqd_head in self.grid_headers[self.grid_type]['pmag'][1]: if reqd_head in self.er_magic.double: ...
def add_new_grid_headers(self, new_headers, er_items, pmag_items)
Add in all user-added headers. If those new headers depend on other headers, add the other headers too.
3.093278
3.044289
1.016092
# open the help message self.toggle_help(event=None, mode='open') # first unselect any selected cols/cells self.remove_cols_mode = True self.grid.ClearSelection() self.remove_cols_button.SetLabel("end delete column mode") # change button to exit the delet...
def on_remove_cols(self, event)
enter 'remove columns' mode
4.807821
4.603715
1.044335
if row_num == -1: default = (255, 255, 255, 255) # unhighlight any selected rows: for row in self.selected_rows: attr = wx.grid.GridCellAttr() attr.SetBackgroundColour(default) self.grid.SetRowAttr(row, attr) ...
def on_remove_row(self, event, row_num=-1)
Remove specified grid row. If no row number is given, remove the last row.
3.441136
3.461353
0.994159
# close help messge self.toggle_help(event=None, mode='close') # update mode self.remove_cols_mode = False # re-enable all buttons for btn in [self.add_cols_button, self.remove_row_button, self.add_many_rows_button]: btn.Enable() # unbind gri...
def exit_col_remove_mode(self, event)
go back from 'remove cols' mode to normal
4.188779
4.060575
1.031573
if incl_pmag and self.grid_type in self.er_magic.incl_pmag_data: incl_pmag = True else: incl_pmag = False er_header = self.grid_headers[self.grid_type]['er'][0] if incl_pmag: pmag_header = self.grid_headers[self.grid_type]['pmag'][0] e...
def make_grid(self, incl_pmag=True)
return grid
3.426454
3.420084
1.001863
# # get command line arguments # args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg("-WD", ".") user = pmag.get_named_arg("-usr", "") labfield = pmag.get_named_arg("-dc", '0.5') meas_file = pmag.get_named_arg("-F", "measurements.tx...
def main()
NAME mst_magic.py DESCRIPTION converts MsT data (T,M) to measurements format files SYNTAX mst_magic.py [command line options] OPTIONS -h: prints the help message and quits. -usr USER: identify user, default is "" -f FILE: specify T,M format input file, r...
3.246791
2.39075
1.358063
infile = 'magic_measurements.txt' sitefile = "" specout = "er_specimens.txt" instout = "magic_instruments.txt" # get command line stuff if "-h" in sys.argv: print(main.__doc__) sys.exit() if '-f' in sys.argv: ind = sys.argv.index("-f") infile = sys.argv[ind +...
def main()
NAME parse_measurements.py DESCRIPTION takes measurments file and creates specimen and instrument files SYNTAX parse_measurements.py [command line options] OPTIONS -h prints help message and quits -f FILE magic_measurements input file, default is "magic_measurement...
2.492892
1.897644
1.313677
os.chdir(self.WD) options = {} HUJI_file = self.bSizer0.return_value() if not HUJI_file: pw.simple_warning("You must select a HUJI format file") return False options['magfile'] = HUJI_file magicoutfile=os.path.split(HUJI_file)[1]+".magic" ...
def on_okButton(self, event)
grab user input values, format them, and run huji_magic.py with the appropriate flags
2.834388
2.696018
1.051324
os.chdir(self.WD) options_dict = {} wd = self.WD options_dict['dir_path'] = wd full_file = self.bSizer0.return_value() if not full_file: pw.simple_warning('You must provide a Utrecht format file') return False input_directory, Utre...
def on_okButton(self, event)
Complies information input in GUI into a kwargs dictionary which can be passed into the utrecht_magic script and run to output magic files
3.14523
2.984625
1.053811
''' This fucntion does exactly what the 'import orientation' fuction does in MagIC.py after some dialog boxes the function calls orientation_magic.py ''' # first see if demag_orient.txt self.on_m_save_file(None) orient_convention_dia = orient_convention(None) ...
def on_m_calc_orient(self,event)
This fucntion does exactly what the 'import orientation' fuction does in MagIC.py after some dialog boxes the function calls orientation_magic.py
3.20803
2.839883
1.129634
file="" if '-h' in sys.argv: print(main.__doc__) sys.exit() elif '-i' in sys.argv: file=input("Enter eigenparameters data file name: ") elif '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] if file!="": f=open(file,'r') data=f.re...
def main()
NAME eigs_s.py DESCRIPTION converts eigenparamters format data to s format SYNTAX eigs_s.py [-h][-i][command line options][<filename] OPTIONS -h prints help message and quits -i allows interactive file name entry -f FILE, specifies input file name -F FILE, specifies...
3.657728
3.185416
1.148273
if ndarray is not FakeObject: # NumPy is available import numpy as np if isinstance(obj, np.generic) or isinstance(obj, np.ndarray): # Numpy scalars all inherit from np.generic. # Numpy arrays all inherit from np.ndarray. # If we check that we are certain we have...
def get_numpy_dtype(obj)
Return NumPy data type associated to obj Return None if NumPy is not available or if obj is not a NumPy array or scalar
7.747027
7.774215
0.996503
return "<%s @ %s>" % (obj.__class__.__name__, hex(id(obj)).upper().replace('X', 'x'))
def address(obj)
Return object address as a string: '<classname @ address>
5.217271
3.767188
1.384925
if isinstance(item, (list, set, tuple, dict)): return len(item) elif isinstance(item, (ndarray, MaskedArray)): return item.shape elif isinstance(item, Image): return item.size if isinstance(item, (DataFrame, Index, Series)): return item.shape else: return...
def get_size(item)
Return size of an item of arbitrary type
2.870868
2.646468
1.084792
attrs = [k for k in dir(obj) if not k.startswith('__')] if not attrs: attrs = dir(obj) return attrs
def get_object_attrs(obj)
Get the attributes of an object using dir. This filters protected attributes
2.901624
3.536953
0.820374
m = re.match(r'^(?:(?:datetime\.)?timedelta)?' r'\(?' r'([^)]*)' r'\)?$', value) if not m: raise ValueError('Invalid string for datetime.timedelta') args = [int(a.strip()) for a in m.group(1).split(',')] return datetime.timedelta(*args)
def str_to_timedelta(value)
Convert a string to a datetime.timedelta value. The following strings are accepted: - 'datetime.timedelta(1, 5, 12345)' - 'timedelta(1, 5, 12345)' - '(1, 5, 12345)' - '1, 5, 12345' - '1' if there are less then three parameters, the missing parameters are assumed to...
3.708518
3.497791
1.060246
if not is_known_type(value): return CUSTOM_TYPE_COLOR for typ, name in list(COLORS.items()): if isinstance(value, typ): return name else: np_dtype = get_numpy_dtype(value) if np_dtype is None or not hasattr(value, 'size'): return UNSUPPORTED_COLOR...
def get_color_name(value)
Return color name depending on value type
3.880356
3.674377
1.056058
try: return [item for _, item in sorted(zip(list2, list1), key=lambda x: x[0], reverse=reverse)] except: return list1
def sort_against(list1, list2, reverse=False)
Arrange items of list1 in the same order as sorted(list2). In other words, apply to list1 the permutation which takes list2 to sorted(list2, reverse).
2.753498
2.707296
1.017066
object_type = type(value) try: name = object_type.__name__ module = object_type.__module__ if with_module: return name + ' object of ' + module + ' module' else: return name except: type_str = to_text_string(object_type) return typ...
def default_display(value, with_module=True)
Default display for unknown objects.
2.977007
2.949689
1.009261
is_dict = isinstance(value, dict) is_set = isinstance(value, set) # Get elements if is_dict: elements = iteritems(value) else: elements = value # Truncate values truncate = False if level == 1 and len(value) > 10: elements = islice(elements, 10) if is_dict ...
def collections_display(value, level)
Display for collections (i.e. list, set, tuple and dict).
2.174235
2.10969
1.030594
from qtpy.compat import from_qvariant value = from_qvariant(value, to_text_string) try: np_dtype = get_numpy_dtype(default_value) if isinstance(default_value, bool): # We must test for boolean before NumPy data types # because `bool` class derives from `int` clas...
def display_to_value(value, default_value, ignore_errors=True)
Convert back to value
2.323314
2.315202
1.003504
if isinstance(item, DataFrame): return "DataFrame" if isinstance(item, Index): return type(item).__name__ if isinstance(item, Series): return "Series" found = re.findall(r"<(?:type|class) '(\S*)'>", to_text_string(type(item))) if found: ret...
def get_type_string(item)
Return type string of an object.
3.528458
3.31424
1.064636
if isinstance(item, (ndarray, MaskedArray)): return item.dtype.name elif isinstance(item, Image): return "Image" else: text = get_type_string(item) if text is None: text = to_text_string('unknown') else: return text[text.find('.')+1:]
def get_human_readable_type(item)
Return human-readable type string of an item
4.471699
4.271468
1.046876
assert filters is not None if value is None: return True if not is_editable_type(value): return False elif not isinstance(value, filters): return False elif iterate: if isinstance(value, (list, tuple, set)): valid_count = 0 for val in valu...
def is_supported(value, check_all=False, filters=None, iterate=False)
Return True if the value is supported, False otherwise
2.238632
2.247565
0.996026
output_dict = {} for key, value in list(input_dict.items()): excluded = (exclude_private and key.startswith('_')) or \ (exclude_capitalized and key[0].isupper()) or \ (exclude_uppercase and key.isupper() and len(key) > 1 and not key[1:].isdi...
def globalsfilter(input_dict, check_all=False, filters=None, exclude_private=None, exclude_capitalized=None, exclude_uppercase=None, exclude_unsupported=None, excluded_names=None)
Keep only objects that can be pickled
1.985909
1.99222
0.996832
from datetime import date, timedelta editable_types = [int, float, complex, list, set, dict, tuple, date, timedelta] + list(TEXT_TYPES) + list(INT_TYPES) try: from numpy import ndarray, matrix, generic editable_types += [ndarray, matrix, generic] except: ...
def get_supported_types()
Return a dictionnary containing types lists supported by the namespace browser. Note: If you update this list, don't forget to update variablexplorer.rst in spyder-docs
3.578651
3.759381
0.951926
supported_types = get_supported_types() assert mode in list(supported_types.keys()) excluded_names = settings['excluded_names'] if more_excluded_names is not None: excluded_names += more_excluded_names return globalsfilter(data, check_all=settings['check_all'], ...
def get_remote_data(data, settings, mode, more_excluded_names=None)
Return globals according to filter described in *settings*: * data: data to be filtered (dictionary) * settings: variable explorer settings (dictionary) * mode (string): 'editable' or 'picklable' * more_excluded_names: additional excluded names (list)
3.492516
3.336998
1.046604
data = get_remote_data(data, settings, mode='editable', more_excluded_names=more_excluded_names) remote = {} for key, value in list(data.items()): view = value_to_display(value, minmax=settings['minmax']) remote[key] = {'type': get_human_readable_type(value),...
def make_remote_view(data, settings, more_excluded_names=None)
Make a remote view of dictionary *data* -> globals explorer
4.256175
4.400013
0.96731
if self._pdb_obj is not None and self._pdb_obj.curframe is not None: return self._pdb_obj.curframe
def _pdb_frame(self)
Return current Pdb frame if there is any
3.502031
2.845018
1.230935
from spyder_kernels.utils.nsview import make_remote_view settings = self.namespace_view_settings if settings: ns = self._get_current_namespace() view = repr(make_remote_view(ns, settings, EXCLUDED_NAMES)) return view else: return ...
def get_namespace_view(self)
Return the namespace view This is a dictionary with the following structure {'a': {'color': '#800000', 'size': 1, 'type': 'str', 'view': '1'}} Here: * 'a' is the variable name * 'color' is the color used to show it * 'size' and 'type' are self-evident * and'vie...
6.669168
7.401915
0.901006
from spyder_kernels.utils.nsview import get_remote_data settings = self.namespace_view_settings if settings: ns = self._get_current_namespace() data = get_remote_data(ns, settings, mode='editable', more_excluded_names=EXCLUDED_...
def get_var_properties(self)
Get some properties of the variables in the current namespace
3.428009
3.373716
1.016093
import cloudpickle if content is None: content = {} content['spyder_msg_type'] = spyder_msg_type msg = self.session.send( self.iopub_socket, 'spyder_msg', content=content, buffers=[cloudpickle.dumps(data, protocol=PICK...
def send_spyder_msg(self, spyder_msg_type, content=None, data=None)
Publish custom messages to the Spyder frontend. Parameters ---------- spyder_msg_type: str The spyder message type content: dict The (JSONable) content of the message data: any Any object that is serializable by cloudpickle (should be most ...
3.525323
3.17798
1.109297
ns = self._get_current_namespace() value = ns[name] try: self.send_spyder_msg('data', data=value) except: # * There is no need to inform users about # these errors. # * value = None makes Spyder to ignore # petition...
def get_value(self, name)
Get the value of a variable
10.263248
10.385018
0.988274
import cloudpickle ns = self._get_reference_namespace(name) # We send serialized values in a list of one element # from Spyder to the kernel, to be able to send them # at all in Python 2 svalue = value[0] # We need to convert svalue to bytes if the fron...
def set_value(self, name, value, PY2_frontend)
Set the value of a variable
6.640599
6.946514
0.955961
ns = self._get_reference_namespace(name) ns.pop(name)
def remove_value(self, name)
Remove a variable
10.287585
11.331714
0.907858
ns = self._get_reference_namespace(orig_name) ns[new_name] = ns[orig_name]
def copy_value(self, orig_name, new_name)
Copy a variable
5.075315
5.369645
0.945186
from spyder_kernels.utils.iofuncs import iofunctions from spyder_kernels.utils.misc import fix_reference_name glbs = self._mglobals() load_func = iofunctions.load_funcs[ext] data, error_message = load_func(filename) if error_message: return error_m...
def load_data(self, filename, ext)
Load data from filename
3.918907
3.969607
0.987228
from spyder_kernels.utils.nsview import get_remote_data from spyder_kernels.utils.iofuncs import iofunctions ns = self._get_current_namespace() settings = self.namespace_view_settings data = get_remote_data(ns, settings, mode='picklable', ...
def save_namespace(self, filename)
Save namespace into filename
7.439115
7.4331
1.000809
if self._pdb_obj and self._do_publish_pdb_state: state = dict(namespace_view = self.get_namespace_view(), var_properties = self.get_var_properties(), step = self._pdb_step) self.send_spyder_msg('pdb_state', content={'pdb_state': ...
def publish_pdb_state(self)
Publish Variable Explorer state and Pdb step through send_spyder_msg.
5.546028
4.127784
1.343585
from spyder_kernels.utils.dochelpers import isdefined ns = self._get_current_namespace(with_magics=True) return isdefined(obj, force_import=force_import, namespace=ns)
def is_defined(self, obj, force_import=False)
Return True if object is defined in current namespace
6.290189
5.431157
1.158167
try: import matplotlib matplotlib.rcParams['docstring.hardcopy'] = True except: pass from spyder_kernels.utils.dochelpers import getdoc obj, valid = self._eval(objtxt) if valid: return getdoc(obj)
def get_doc(self, objtxt)
Get object documentation dictionary
7.571845
7.09606
1.067049
from spyder_kernels.utils.dochelpers import getsource obj, valid = self._eval(objtxt) if valid: return getsource(obj)
def get_source(self, objtxt)
Get object source
8.463636
7.526487
1.124514
ns = {} glbs = self._mglobals() if self._pdb_frame is None: ns.update(glbs) else: ns.update(glbs) ns.update(self._pdb_locals) # Add magics to ns so we can show help about them on the Help # plugin if with_magics: ...
def _get_current_namespace(self, with_magics=False)
Return current namespace This is globals() if not debugging, or a dictionary containing both locals() and globals() for current frame when debugging
3.682627
3.511369
1.048772
glbs = self._mglobals() if self._pdb_frame is None: return glbs else: lcls = self._pdb_locals if name in lcls: return lcls else: return glbs
def _get_reference_namespace(self, name)
Return namespace where reference name is defined It returns the globals() if reference has not yet been defined
6.904901
5.73631
1.203718
if self._pdb_frame is not None: return self._pdb_frame.f_globals else: return self.shell.user_ns
def _mglobals(self)
Return current globals -- handles Pdb frames
5.023277
3.146452
1.596489
try: from PIL import Image return isinstance(var, Image.Image) except: return False
def _is_image(self, var)
Return True if variable is a PIL.Image image
3.476019
2.759713
1.259558
if not self._pdb_obj: return # Breakpoints come serialized from Spyder. We send them # in a list of one element to be able to send them at all # in Python 2 serialized_breakpoints = breakpoints[0] breakpoints = pickle.loads(serialized_breakpoints) ...
def _set_spyder_breakpoints(self, breakpoints)
Set all Spyder breakpoints in an active pdb session
7.193348
6.305001
1.140896
from spyder_kernels.py3compat import is_text_string assert is_text_string(text) ns = self._get_current_namespace(with_magics=True) try: return eval(text, ns), True except: return None, False
def _eval(self, text)
Evaluate text and return (obj, valid) where *obj* is the object represented by *text* and *valid* is True if object evaluation did not raise any exception
5.175825
4.766314
1.085918
import traceback from IPython.core.getipython import get_ipython generic_error = ( "\n" + "="*73 + "\n" "NOTE: The following error appeared when setting " "your Matplotlib backend!!\n" + "="*73 + "\n\n" "{0}" ) magic = 'p...
def _set_mpl_backend(self, backend, pylab=False)
Set a backend for Matplotlib. backend: A parameter that can be passed to %matplotlib (e.g. 'inline' or 'tk').
5.108315
5.150647
0.991781
from IPython.core.getipython import get_ipython try: get_ipython().run_line_magic('reload_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') except Exception: pass
def _load_autoreload_magic(self)
Load %autoreload magic.
2.535362
2.259899
1.121892
# Wurlitzer has no effect on Windows if not os.name == 'nt': from IPython.core.getipython import get_ipython # Enclose this in a try/except because if it fails the # console will be totally unusable. # Fixes spyder-ide/spyder#8668 try:...
def _load_wurlitzer(self)
Load wurlitzer extension.
5.037004
4.782699
1.053172
here = osp.dirname(__file__) parent = osp.dirname(here) customize_dir = osp.join(parent, 'customize') # Remove current directory from sys.path to prevent kernel # crashes when people name Python files or modules with # the same name as standard library modules. # See spyder-ide/spyder#...
def import_spydercustomize()
Import our customizations into the kernel.
4.097641
3.847428
1.065034
ip = get_ipython() #analysis:ignore funcname, name = line.split() try: import guiqwt.pyplot as pyplot except: import matplotlib.pyplot as pyplot __fig__ = pyplot.figure(); __items__ = getattr(pyplot, funcname[2:])(ip.user_ns[name]) pyplot.show() del __fig__, __...
def varexp(line)
Spyder's variable explorer magic Used to generate plots, histograms and images of the variables displayed on it.
7.410586
6.993644
1.059617
name = "".join(re.split(r'[^0-9a-zA-Z_]', name)) while name and not re.match(r'([a-zA-Z]+[0-9a-zA-Z_]*)$', name): if not re.match(r'[a-zA-Z]', name[0]): name = name[1:] continue name = str(name) if not name: name = "data" if blacklist is not None and name...
def fix_reference_name(name, blacklist=None)
Return a syntax-valid Python reference name from an arbitrary name
2.707836
2.654731
1.020004
# This is useful when debugging in an active interpreter (otherwise, # the debugger will stop before reaching the target file) if self._wait_for_mainpyfile: if (self.mainpyfile != self.canonic(frame.f_code.co_filename) or frame.f_lineno<= 0): return self._wait_fo...
def user_return(self, frame, return_value)
This function is called when a return trap is set here.
6.388863
6.264694
1.01982
clear_post_mortem() ipython_shell = get_ipython() ipython_shell.showtraceback((type, value, tb)) p = pdb.Pdb(ipython_shell.colors) if not type == SyntaxError: # wait for stderr to print (stderr.flush does not work in this case) time.sleep(0.1) _print('*' * 40) _...
def post_mortem_excepthook(type, value, tb)
For post mortem exception handling, print a banner and enable post mortem debugging.
4.735547
4.606833
1.02794
def ipython_post_mortem_debug(shell, etype, evalue, tb, tb_offset=None): post_mortem_excepthook(etype, evalue, tb) ipython_shell = get_ipython() ipython_shell.set_custom_exc((Exception,), ipython_post_mortem_debug)
def set_post_mortem()
Enable the post mortem debugging excepthook.
3.464378
3.198006
1.083293
try: filename = filename.decode('utf-8') except (UnicodeError, TypeError, AttributeError): # UnicodeError, TypeError --> eventually raised in Python 2 # AttributeError --> systematically raised in Python 3 pass if __umr__.enabled: __umr__.run() if args is not...
def runfile(filename, args=None, wdir=None, namespace=None, post_mortem=False)
Run filename args: command line arguments (string) wdir: working directory post_mortem: boolean, whether to enter post-mortem mode on error
3.274054
3.338141
0.980801
try: filename = filename.decode('utf-8') except (UnicodeError, TypeError, AttributeError): # UnicodeError, TypeError --> eventually raised in Python 2 # AttributeError --> systematically raised in Python 3 pass ipython_shell = get_ipython() namespace = _get_globals()...
def runcell(cellname, filename)
Run a code cell from an editor as a file. Currently looks for code in an `ipython` property called `cell_code`. This property must be set by the editor prior to calling this function. This function deletes the contents of `cell_code` upon completion. Parameters ---------- cellname : str ...
7.011564
6.387506
1.0977
debugger = pdb.Pdb() filename = debugger.canonic(filename) debugger._wait_for_mainpyfile = 1 debugger.mainpyfile = filename debugger._user_requested_quit = 0 if os.name == 'nt': filename = filename.replace('\\', '/') debugger.run("runfile(%r, args=%r, wdir=%r)" % (filename, args...
def debugfile(filename, args=None, wdir=None, post_mortem=False)
Debug filename args: command line arguments (string) wdir: working directory post_mortem: boolean, included for compatiblity with runfile
3.812342
4.054632
0.940244
# Get standard installation paths try: paths = sysconfig.get_paths() standard_paths = [paths['stdlib'], paths['purelib'], paths['scripts'], paths['data']] except Exception: ...
def create_pathlist(self, initial_pathlist)
Add to pathlist Python library paths to be skipped from module reloading.
3.853182
3.621359
1.064015
if self.has_cython: # Don't return cached inline compiled .PYX files return False else: if (self.is_module_in_pathlist(module) or self.is_module_in_namelist(modname)): return False else: return T...
def is_module_reloadable(self, module, modname)
Decide if a module is reloadable or not.
6.870707
6.712466
1.023574
modpath = getattr(module, '__file__', None) # Skip module according to different criteria if modpath is None: # *module* is a C module that is statically linked into the # interpreter. There is no way to know its path, so we # choose to ignore it. ...
def is_module_in_pathlist(self, module)
Decide if a module can be reloaded or not according to its path.
5.345763
5.179714
1.032057
run_cython = os.environ.get("SPY_RUN_CYTHON") == "True" if run_cython: try: __import__('Cython') self.has_cython = True except Exception: pass if self.has_cython: # Import pyximport to enable C...
def activate_cython(self)
Activate Cython support. We need to run this here because if the support is active, we don't to run the UMR at all.
3.669233
3.644566
1.006768
self.modnames_to_reload = [] for modname, module in list(sys.modules.items()): if modname not in self.previous_modules: # Decide if a module can be reloaded or not if self.is_module_reloadable(module, modname): self.modnames_to_rel...
def run(self)
Delete user modules to force Python to deeply reload them Do not del modules which are considered as system modules, i.e. modules installed in subdirectories of Python interpreter's binary Do not del C modules
3.62501
3.382074
1.071831
import numpy as np # Extract each item of a list. if isinstance(val, list): return [get_matlab_value(v) for v in val] # Ignore leaf objects. if not isinstance(val, np.ndarray): return val # Convert user defined classes. if hasattr(val, 'classname'): out = dict...
def get_matlab_value(val)
Extract a value from a Matlab file From the oct2py project, see https://pythonhosted.org/oct2py/conversions.html
2.90379
2.987105
0.972109
try: if pd: return pd.read_pickle(filename), None else: with open(filename, 'rb') as fid: data = pickle.load(fid) return data, None except Exception as err: return None, str(err)
def load_pickle(filename)
Load a pickle file as a dictionary
2.701074
2.841034
0.950736
try: if PY2: args = 'rb' else: args = 'r' with open(filename, args) as fid: data = json.load(fid) return data, None except Exception as err: return None, str(err)
def load_json(filename)
Load a json file as a dictionary
3.006442
3.105153
0.968211
filename = osp.abspath(filename) old_cwd = getcwd() os.chdir(osp.dirname(filename)) error_message = None skipped_keys = [] data_copy = {} try: # Copy dictionary before modifying it to fix #6689 for obj_name, obj_value in data.items(): # Skip modules, since t...
def save_dictionary(data, filename)
Save dictionary in a single file .spydata file
3.383953
3.37447
1.00281
filename = osp.abspath(filename) old_cwd = getcwd() tmp_folder = tempfile.mkdtemp() os.chdir(tmp_folder) data = None error_message = None try: with tarfile.open(filename, "r") as tar: tar.extractall() pickle_filename = glob.glob('*.pickle')[0] # 'New'...
def load_dictionary(filename)
Load dictionary from .spydata file
3.956274
3.825374
1.034219