repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
hover2pi/svo_filters
svo_filters/svo.py
Filter.bin
def bin(self, n_bins=1, pixels_per_bin=None, wave_min=None, wave_max=None): """ Break the filter up into bins and apply a throughput to each bin, useful for G141, G102, and other grisms Parameters ---------- n_bins: int The number of bins to dice the throughput curve into pixels_per_bin: int (optional) The number of channels per bin, which will be used to calculate n_bins wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (optional) The maximum wavelength to use """ # Get wavelength limits if wave_min is not None: self.wave_min = wave_min if wave_max is not None: self.wave_max = wave_max # Trim the wavelength by the given min and max raw_wave = self.raw[0] whr = np.logical_and(raw_wave * q.AA >= self.wave_min, raw_wave * q.AA <= self.wave_max) self.wave = (raw_wave[whr] * q.AA).to(self.wave_units) self.throughput = self.raw[1][whr] print('Bandpass trimmed to', '{} - {}'.format(self.wave_min, self.wave_max)) # Calculate the number of bins and channels pts = len(self.wave) if isinstance(pixels_per_bin, int): self.pixels_per_bin = pixels_per_bin self.n_bins = int(pts/self.pixels_per_bin) elif isinstance(n_bins, int): self.n_bins = n_bins self.pixels_per_bin = int(pts/self.n_bins) else: raise ValueError("Please specify 'n_bins' OR 'pixels_per_bin' as integers.") print('{} bins of {} pixels each.'.format(self.n_bins, self.pixels_per_bin)) # Trim throughput edges so that there are an integer number of bins new_len = self.n_bins * self.pixels_per_bin start = (pts - new_len) // 2 self.wave = self.wave[start:new_len+start].reshape(self.n_bins, self.pixels_per_bin) self.throughput = self.throughput[start:new_len+start].reshape(self.n_bins, self.pixels_per_bin)
python
def bin(self, n_bins=1, pixels_per_bin=None, wave_min=None, wave_max=None): """ Break the filter up into bins and apply a throughput to each bin, useful for G141, G102, and other grisms Parameters ---------- n_bins: int The number of bins to dice the throughput curve into pixels_per_bin: int (optional) The number of channels per bin, which will be used to calculate n_bins wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (optional) The maximum wavelength to use """ # Get wavelength limits if wave_min is not None: self.wave_min = wave_min if wave_max is not None: self.wave_max = wave_max # Trim the wavelength by the given min and max raw_wave = self.raw[0] whr = np.logical_and(raw_wave * q.AA >= self.wave_min, raw_wave * q.AA <= self.wave_max) self.wave = (raw_wave[whr] * q.AA).to(self.wave_units) self.throughput = self.raw[1][whr] print('Bandpass trimmed to', '{} - {}'.format(self.wave_min, self.wave_max)) # Calculate the number of bins and channels pts = len(self.wave) if isinstance(pixels_per_bin, int): self.pixels_per_bin = pixels_per_bin self.n_bins = int(pts/self.pixels_per_bin) elif isinstance(n_bins, int): self.n_bins = n_bins self.pixels_per_bin = int(pts/self.n_bins) else: raise ValueError("Please specify 'n_bins' OR 'pixels_per_bin' as integers.") print('{} bins of {} pixels each.'.format(self.n_bins, self.pixels_per_bin)) # Trim throughput edges so that there are an integer number of bins new_len = self.n_bins * self.pixels_per_bin start = (pts - new_len) // 2 self.wave = self.wave[start:new_len+start].reshape(self.n_bins, self.pixels_per_bin) self.throughput = self.throughput[start:new_len+start].reshape(self.n_bins, self.pixels_per_bin)
[ "def", "bin", "(", "self", ",", "n_bins", "=", "1", ",", "pixels_per_bin", "=", "None", ",", "wave_min", "=", "None", ",", "wave_max", "=", "None", ")", ":", "# Get wavelength limits", "if", "wave_min", "is", "not", "None", ":", "self", ".", "wave_min", "=", "wave_min", "if", "wave_max", "is", "not", "None", ":", "self", ".", "wave_max", "=", "wave_max", "# Trim the wavelength by the given min and max", "raw_wave", "=", "self", ".", "raw", "[", "0", "]", "whr", "=", "np", ".", "logical_and", "(", "raw_wave", "*", "q", ".", "AA", ">=", "self", ".", "wave_min", ",", "raw_wave", "*", "q", ".", "AA", "<=", "self", ".", "wave_max", ")", "self", ".", "wave", "=", "(", "raw_wave", "[", "whr", "]", "*", "q", ".", "AA", ")", ".", "to", "(", "self", ".", "wave_units", ")", "self", ".", "throughput", "=", "self", ".", "raw", "[", "1", "]", "[", "whr", "]", "print", "(", "'Bandpass trimmed to'", ",", "'{} - {}'", ".", "format", "(", "self", ".", "wave_min", ",", "self", ".", "wave_max", ")", ")", "# Calculate the number of bins and channels", "pts", "=", "len", "(", "self", ".", "wave", ")", "if", "isinstance", "(", "pixels_per_bin", ",", "int", ")", ":", "self", ".", "pixels_per_bin", "=", "pixels_per_bin", "self", ".", "n_bins", "=", "int", "(", "pts", "/", "self", ".", "pixels_per_bin", ")", "elif", "isinstance", "(", "n_bins", ",", "int", ")", ":", "self", ".", "n_bins", "=", "n_bins", "self", ".", "pixels_per_bin", "=", "int", "(", "pts", "/", "self", ".", "n_bins", ")", "else", ":", "raise", "ValueError", "(", "\"Please specify 'n_bins' OR 'pixels_per_bin' as integers.\"", ")", "print", "(", "'{} bins of {} pixels each.'", ".", "format", "(", "self", ".", "n_bins", ",", "self", ".", "pixels_per_bin", ")", ")", "# Trim throughput edges so that there are an integer number of bins", "new_len", "=", "self", ".", "n_bins", "*", "self", ".", "pixels_per_bin", "start", "=", "(", "pts", "-", "new_len", ")", "//", "2", "self", ".", "wave", "=", "self", ".", "wave", "[", "start", ":", "new_len", "+", "start", "]", ".", "reshape", "(", "self", ".", "n_bins", ",", "self", ".", "pixels_per_bin", ")", "self", ".", "throughput", "=", "self", ".", "throughput", "[", "start", ":", "new_len", "+", "start", "]", ".", "reshape", "(", "self", ".", "n_bins", ",", "self", ".", "pixels_per_bin", ")" ]
Break the filter up into bins and apply a throughput to each bin, useful for G141, G102, and other grisms Parameters ---------- n_bins: int The number of bins to dice the throughput curve into pixels_per_bin: int (optional) The number of channels per bin, which will be used to calculate n_bins wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (optional) The maximum wavelength to use
[ "Break", "the", "filter", "up", "into", "bins", "and", "apply", "a", "throughput", "to", "each", "bin", "useful", "for", "G141", "G102", "and", "other", "grisms" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L326-L376
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.centers
def centers(self): """A getter for the wavelength bin centers and average fluxes""" # Get the bin centers w_cen = np.nanmean(self.wave.value, axis=1) f_cen = np.nanmean(self.throughput, axis=1) return np.asarray([w_cen, f_cen])
python
def centers(self): """A getter for the wavelength bin centers and average fluxes""" # Get the bin centers w_cen = np.nanmean(self.wave.value, axis=1) f_cen = np.nanmean(self.throughput, axis=1) return np.asarray([w_cen, f_cen])
[ "def", "centers", "(", "self", ")", ":", "# Get the bin centers", "w_cen", "=", "np", ".", "nanmean", "(", "self", ".", "wave", ".", "value", ",", "axis", "=", "1", ")", "f_cen", "=", "np", ".", "nanmean", "(", "self", ".", "throughput", ",", "axis", "=", "1", ")", "return", "np", ".", "asarray", "(", "[", "w_cen", ",", "f_cen", "]", ")" ]
A getter for the wavelength bin centers and average fluxes
[ "A", "getter", "for", "the", "wavelength", "bin", "centers", "and", "average", "fluxes" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L379-L385
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.flux_units
def flux_units(self, units): """ A setter for the flux units Parameters ---------- units: str, astropy.units.core.PrefixUnit The desired units of the zeropoint flux density """ # Check that the units are valid dtypes = (q.core.PrefixUnit, q.quantity.Quantity, q.core.CompositeUnit) if not isinstance(units, dtypes): raise ValueError(units, "units not understood.") # Check that the units changed if units != self.flux_units: # Convert to new units sfd = q.spectral_density(self.wave_eff) self.zp = self.zp.to(units, equivalencies=sfd) # Store new units self._flux_units = units
python
def flux_units(self, units): """ A setter for the flux units Parameters ---------- units: str, astropy.units.core.PrefixUnit The desired units of the zeropoint flux density """ # Check that the units are valid dtypes = (q.core.PrefixUnit, q.quantity.Quantity, q.core.CompositeUnit) if not isinstance(units, dtypes): raise ValueError(units, "units not understood.") # Check that the units changed if units != self.flux_units: # Convert to new units sfd = q.spectral_density(self.wave_eff) self.zp = self.zp.to(units, equivalencies=sfd) # Store new units self._flux_units = units
[ "def", "flux_units", "(", "self", ",", "units", ")", ":", "# Check that the units are valid", "dtypes", "=", "(", "q", ".", "core", ".", "PrefixUnit", ",", "q", ".", "quantity", ".", "Quantity", ",", "q", ".", "core", ".", "CompositeUnit", ")", "if", "not", "isinstance", "(", "units", ",", "dtypes", ")", ":", "raise", "ValueError", "(", "units", ",", "\"units not understood.\"", ")", "# Check that the units changed", "if", "units", "!=", "self", ".", "flux_units", ":", "# Convert to new units", "sfd", "=", "q", ".", "spectral_density", "(", "self", ".", "wave_eff", ")", "self", ".", "zp", "=", "self", ".", "zp", ".", "to", "(", "units", ",", "equivalencies", "=", "sfd", ")", "# Store new units", "self", ".", "_flux_units", "=", "units" ]
A setter for the flux units Parameters ---------- units: str, astropy.units.core.PrefixUnit The desired units of the zeropoint flux density
[ "A", "setter", "for", "the", "flux", "units" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L393-L415
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.info
def info(self, fetch=False): """ Print a table of info about the current filter """ # Get the info from the class tp = (int, bytes, bool, str, float, tuple, list, np.ndarray) info = [[k, str(v)] for k, v in vars(self).items() if isinstance(v, tp) and k not in ['rsr', 'raw', 'centers'] and not k.startswith('_')] # Make the table table = at.Table(np.asarray(info).reshape(len(info), 2), names=['Attributes', 'Values']) # Sort and print table.sort('Attributes') if fetch: return table else: table.pprint(max_width=-1, max_lines=-1, align=['>', '<'])
python
def info(self, fetch=False): """ Print a table of info about the current filter """ # Get the info from the class tp = (int, bytes, bool, str, float, tuple, list, np.ndarray) info = [[k, str(v)] for k, v in vars(self).items() if isinstance(v, tp) and k not in ['rsr', 'raw', 'centers'] and not k.startswith('_')] # Make the table table = at.Table(np.asarray(info).reshape(len(info), 2), names=['Attributes', 'Values']) # Sort and print table.sort('Attributes') if fetch: return table else: table.pprint(max_width=-1, max_lines=-1, align=['>', '<'])
[ "def", "info", "(", "self", ",", "fetch", "=", "False", ")", ":", "# Get the info from the class", "tp", "=", "(", "int", ",", "bytes", ",", "bool", ",", "str", ",", "float", ",", "tuple", ",", "list", ",", "np", ".", "ndarray", ")", "info", "=", "[", "[", "k", ",", "str", "(", "v", ")", "]", "for", "k", ",", "v", "in", "vars", "(", "self", ")", ".", "items", "(", ")", "if", "isinstance", "(", "v", ",", "tp", ")", "and", "k", "not", "in", "[", "'rsr'", ",", "'raw'", ",", "'centers'", "]", "and", "not", "k", ".", "startswith", "(", "'_'", ")", "]", "# Make the table", "table", "=", "at", ".", "Table", "(", "np", ".", "asarray", "(", "info", ")", ".", "reshape", "(", "len", "(", "info", ")", ",", "2", ")", ",", "names", "=", "[", "'Attributes'", ",", "'Values'", "]", ")", "# Sort and print", "table", ".", "sort", "(", "'Attributes'", ")", "if", "fetch", ":", "return", "table", "else", ":", "table", ".", "pprint", "(", "max_width", "=", "-", "1", ",", "max_lines", "=", "-", "1", ",", "align", "=", "[", "'>'", ",", "'<'", "]", ")" ]
Print a table of info about the current filter
[ "Print", "a", "table", "of", "info", "about", "the", "current", "filter" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L417-L436
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.load_TopHat
def load_TopHat(self, wave_min, wave_max, pixels_per_bin=100): """ Loads a top hat filter given wavelength min and max values Parameters ---------- wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (optional) The maximum wavelength to use n_pixels: int The number of pixels for the filter """ # Get min, max, effective wavelengths and width self.pixels_per_bin = pixels_per_bin self.n_bins = 1 self._wave_units = q.AA wave_min = wave_min.to(self.wave_units) wave_max = wave_max.to(self.wave_units) # Create the RSR curve self._wave = np.linspace(wave_min, wave_max, pixels_per_bin) self._throughput = np.ones_like(self.wave) self.raw = np.array([self.wave.value, self.throughput]) # Calculate the effective wavelength wave_eff = ((wave_min + wave_max) / 2.).value width = (wave_max - wave_min).value # Add the attributes self.path = '' self.refs = '' self.Band = 'Top Hat' self.CalibrationReference = '' self.FWHM = width self.Facility = '-' self.FilterProfileService = '-' self.MagSys = '-' self.PhotCalID = '' self.PhotSystem = '' self.ProfileReference = '' self.WavelengthMin = wave_min.value self.WavelengthMax = wave_max.value self.WavelengthCen = wave_eff self.WavelengthEff = wave_eff self.WavelengthMean = wave_eff self.WavelengthPeak = wave_eff self.WavelengthPhot = wave_eff self.WavelengthPivot = wave_eff self.WavelengthUCD = '' self.WidthEff = width self.ZeroPoint = 0 self.ZeroPointType = '' self.ZeroPointUnit = 'Jy' self.filterID = 'Top Hat'
python
def load_TopHat(self, wave_min, wave_max, pixels_per_bin=100): """ Loads a top hat filter given wavelength min and max values Parameters ---------- wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (optional) The maximum wavelength to use n_pixels: int The number of pixels for the filter """ # Get min, max, effective wavelengths and width self.pixels_per_bin = pixels_per_bin self.n_bins = 1 self._wave_units = q.AA wave_min = wave_min.to(self.wave_units) wave_max = wave_max.to(self.wave_units) # Create the RSR curve self._wave = np.linspace(wave_min, wave_max, pixels_per_bin) self._throughput = np.ones_like(self.wave) self.raw = np.array([self.wave.value, self.throughput]) # Calculate the effective wavelength wave_eff = ((wave_min + wave_max) / 2.).value width = (wave_max - wave_min).value # Add the attributes self.path = '' self.refs = '' self.Band = 'Top Hat' self.CalibrationReference = '' self.FWHM = width self.Facility = '-' self.FilterProfileService = '-' self.MagSys = '-' self.PhotCalID = '' self.PhotSystem = '' self.ProfileReference = '' self.WavelengthMin = wave_min.value self.WavelengthMax = wave_max.value self.WavelengthCen = wave_eff self.WavelengthEff = wave_eff self.WavelengthMean = wave_eff self.WavelengthPeak = wave_eff self.WavelengthPhot = wave_eff self.WavelengthPivot = wave_eff self.WavelengthUCD = '' self.WidthEff = width self.ZeroPoint = 0 self.ZeroPointType = '' self.ZeroPointUnit = 'Jy' self.filterID = 'Top Hat'
[ "def", "load_TopHat", "(", "self", ",", "wave_min", ",", "wave_max", ",", "pixels_per_bin", "=", "100", ")", ":", "# Get min, max, effective wavelengths and width", "self", ".", "pixels_per_bin", "=", "pixels_per_bin", "self", ".", "n_bins", "=", "1", "self", ".", "_wave_units", "=", "q", ".", "AA", "wave_min", "=", "wave_min", ".", "to", "(", "self", ".", "wave_units", ")", "wave_max", "=", "wave_max", ".", "to", "(", "self", ".", "wave_units", ")", "# Create the RSR curve", "self", ".", "_wave", "=", "np", ".", "linspace", "(", "wave_min", ",", "wave_max", ",", "pixels_per_bin", ")", "self", ".", "_throughput", "=", "np", ".", "ones_like", "(", "self", ".", "wave", ")", "self", ".", "raw", "=", "np", ".", "array", "(", "[", "self", ".", "wave", ".", "value", ",", "self", ".", "throughput", "]", ")", "# Calculate the effective wavelength", "wave_eff", "=", "(", "(", "wave_min", "+", "wave_max", ")", "/", "2.", ")", ".", "value", "width", "=", "(", "wave_max", "-", "wave_min", ")", ".", "value", "# Add the attributes", "self", ".", "path", "=", "''", "self", ".", "refs", "=", "''", "self", ".", "Band", "=", "'Top Hat'", "self", ".", "CalibrationReference", "=", "''", "self", ".", "FWHM", "=", "width", "self", ".", "Facility", "=", "'-'", "self", ".", "FilterProfileService", "=", "'-'", "self", ".", "MagSys", "=", "'-'", "self", ".", "PhotCalID", "=", "''", "self", ".", "PhotSystem", "=", "''", "self", ".", "ProfileReference", "=", "''", "self", ".", "WavelengthMin", "=", "wave_min", ".", "value", "self", ".", "WavelengthMax", "=", "wave_max", ".", "value", "self", ".", "WavelengthCen", "=", "wave_eff", "self", ".", "WavelengthEff", "=", "wave_eff", "self", ".", "WavelengthMean", "=", "wave_eff", "self", ".", "WavelengthPeak", "=", "wave_eff", "self", ".", "WavelengthPhot", "=", "wave_eff", "self", ".", "WavelengthPivot", "=", "wave_eff", "self", ".", "WavelengthUCD", "=", "''", "self", ".", "WidthEff", "=", "width", "self", ".", "ZeroPoint", "=", "0", "self", ".", "ZeroPointType", "=", "''", "self", ".", "ZeroPointUnit", "=", "'Jy'", "self", ".", "filterID", "=", "'Top Hat'" ]
Loads a top hat filter given wavelength min and max values Parameters ---------- wave_min: astropy.units.quantity (optional) The minimum wavelength to use wave_max: astropy.units.quantity (optional) The maximum wavelength to use n_pixels: int The number of pixels for the filter
[ "Loads", "a", "top", "hat", "filter", "given", "wavelength", "min", "and", "max", "values" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L438-L492
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.overlap
def overlap(self, spectrum): """Tests for overlap of this filter with a spectrum Example of full overlap: |---------- spectrum ----------| |------ self ------| Examples of partial overlap: : |---------- self ----------| |------ spectrum ------| |---- spectrum ----| |----- self -----| |---- self ----| |---- spectrum ----| Examples of no overlap: : |---- spectrum ----| |---- other ----| |---- other ----| |---- spectrum ----| Parameters ---------- spectrum: sequence The [W, F] spectrum with astropy units Returns ------- ans : {'full', 'partial', 'none'} Overlap status. """ swave = self.wave[np.where(self.throughput != 0)] s1, s2 = swave.min(), swave.max() owave = spectrum[0] o1, o2 = owave.min(), owave.max() if (s1 >= o1 and s2 <= o2): ans = 'full' elif (s2 < o1) or (o2 < s1): ans = 'none' else: ans = 'partial' return ans
python
def overlap(self, spectrum): """Tests for overlap of this filter with a spectrum Example of full overlap: |---------- spectrum ----------| |------ self ------| Examples of partial overlap: : |---------- self ----------| |------ spectrum ------| |---- spectrum ----| |----- self -----| |---- self ----| |---- spectrum ----| Examples of no overlap: : |---- spectrum ----| |---- other ----| |---- other ----| |---- spectrum ----| Parameters ---------- spectrum: sequence The [W, F] spectrum with astropy units Returns ------- ans : {'full', 'partial', 'none'} Overlap status. """ swave = self.wave[np.where(self.throughput != 0)] s1, s2 = swave.min(), swave.max() owave = spectrum[0] o1, o2 = owave.min(), owave.max() if (s1 >= o1 and s2 <= o2): ans = 'full' elif (s2 < o1) or (o2 < s1): ans = 'none' else: ans = 'partial' return ans
[ "def", "overlap", "(", "self", ",", "spectrum", ")", ":", "swave", "=", "self", ".", "wave", "[", "np", ".", "where", "(", "self", ".", "throughput", "!=", "0", ")", "]", "s1", ",", "s2", "=", "swave", ".", "min", "(", ")", ",", "swave", ".", "max", "(", ")", "owave", "=", "spectrum", "[", "0", "]", "o1", ",", "o2", "=", "owave", ".", "min", "(", ")", ",", "owave", ".", "max", "(", ")", "if", "(", "s1", ">=", "o1", "and", "s2", "<=", "o2", ")", ":", "ans", "=", "'full'", "elif", "(", "s2", "<", "o1", ")", "or", "(", "o2", "<", "s1", ")", ":", "ans", "=", "'none'", "else", ":", "ans", "=", "'partial'", "return", "ans" ]
Tests for overlap of this filter with a spectrum Example of full overlap: |---------- spectrum ----------| |------ self ------| Examples of partial overlap: : |---------- self ----------| |------ spectrum ------| |---- spectrum ----| |----- self -----| |---- self ----| |---- spectrum ----| Examples of no overlap: : |---- spectrum ----| |---- other ----| |---- other ----| |---- spectrum ----| Parameters ---------- spectrum: sequence The [W, F] spectrum with astropy units Returns ------- ans : {'full', 'partial', 'none'} Overlap status.
[ "Tests", "for", "overlap", "of", "this", "filter", "with", "a", "spectrum" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L588-L638
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.plot
def plot(self, fig=None, draw=True): """ Plot the filter Parameters ---------- fig: bokeh.plotting.figure (optional) A figure to plot on draw: bool Draw the figure, else return it Returns ------- bokeh.plotting.figure The filter figure """ COLORS = color_gen('Category10') # Make the figure if fig is None: xlab = 'Wavelength [{}]'.format(self.wave_units) ylab = 'Throughput' title = self.filterID fig = figure(title=title, x_axis_label=xlab, y_axis_label=ylab) # Plot the raw curve fig.line((self.raw[0]*q.AA).to(self.wave_units), self.raw[1], alpha=0.1, line_width=8, color='black') # Plot each with bin centers for x, y in self.rsr: fig.line(x, y, color=next(COLORS), line_width=2) fig.circle(*self.centers, size=8, color='black') if draw: show(fig) else: return fig
python
def plot(self, fig=None, draw=True): """ Plot the filter Parameters ---------- fig: bokeh.plotting.figure (optional) A figure to plot on draw: bool Draw the figure, else return it Returns ------- bokeh.plotting.figure The filter figure """ COLORS = color_gen('Category10') # Make the figure if fig is None: xlab = 'Wavelength [{}]'.format(self.wave_units) ylab = 'Throughput' title = self.filterID fig = figure(title=title, x_axis_label=xlab, y_axis_label=ylab) # Plot the raw curve fig.line((self.raw[0]*q.AA).to(self.wave_units), self.raw[1], alpha=0.1, line_width=8, color='black') # Plot each with bin centers for x, y in self.rsr: fig.line(x, y, color=next(COLORS), line_width=2) fig.circle(*self.centers, size=8, color='black') if draw: show(fig) else: return fig
[ "def", "plot", "(", "self", ",", "fig", "=", "None", ",", "draw", "=", "True", ")", ":", "COLORS", "=", "color_gen", "(", "'Category10'", ")", "# Make the figure", "if", "fig", "is", "None", ":", "xlab", "=", "'Wavelength [{}]'", ".", "format", "(", "self", ".", "wave_units", ")", "ylab", "=", "'Throughput'", "title", "=", "self", ".", "filterID", "fig", "=", "figure", "(", "title", "=", "title", ",", "x_axis_label", "=", "xlab", ",", "y_axis_label", "=", "ylab", ")", "# Plot the raw curve", "fig", ".", "line", "(", "(", "self", ".", "raw", "[", "0", "]", "*", "q", ".", "AA", ")", ".", "to", "(", "self", ".", "wave_units", ")", ",", "self", ".", "raw", "[", "1", "]", ",", "alpha", "=", "0.1", ",", "line_width", "=", "8", ",", "color", "=", "'black'", ")", "# Plot each with bin centers", "for", "x", ",", "y", "in", "self", ".", "rsr", ":", "fig", ".", "line", "(", "x", ",", "y", ",", "color", "=", "next", "(", "COLORS", ")", ",", "line_width", "=", "2", ")", "fig", ".", "circle", "(", "*", "self", ".", "centers", ",", "size", "=", "8", ",", "color", "=", "'black'", ")", "if", "draw", ":", "show", "(", "fig", ")", "else", ":", "return", "fig" ]
Plot the filter Parameters ---------- fig: bokeh.plotting.figure (optional) A figure to plot on draw: bool Draw the figure, else return it Returns ------- bokeh.plotting.figure The filter figure
[ "Plot", "the", "filter" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L640-L677
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.throughput
def throughput(self, points): """A setter for the throughput Parameters ---------- throughput: sequence The array of throughput points """ # Test shape if not points.shape == self.wave.shape: raise ValueError("Throughput and wavelength must be same shape.") self._throughput = points
python
def throughput(self, points): """A setter for the throughput Parameters ---------- throughput: sequence The array of throughput points """ # Test shape if not points.shape == self.wave.shape: raise ValueError("Throughput and wavelength must be same shape.") self._throughput = points
[ "def", "throughput", "(", "self", ",", "points", ")", ":", "# Test shape", "if", "not", "points", ".", "shape", "==", "self", ".", "wave", ".", "shape", ":", "raise", "ValueError", "(", "\"Throughput and wavelength must be same shape.\"", ")", "self", ".", "_throughput", "=", "points" ]
A setter for the throughput Parameters ---------- throughput: sequence The array of throughput points
[ "A", "setter", "for", "the", "throughput" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L692-L704
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.wave
def wave(self, wavelength): """A setter for the wavelength Parameters ---------- wavelength: astropy.units.quantity.Quantity The array with units """ # Test units if not isinstance(wavelength, q.quantity.Quantity): raise ValueError("Wavelength must be in length units.") self._wave = wavelength self.wave_units = wavelength.unit
python
def wave(self, wavelength): """A setter for the wavelength Parameters ---------- wavelength: astropy.units.quantity.Quantity The array with units """ # Test units if not isinstance(wavelength, q.quantity.Quantity): raise ValueError("Wavelength must be in length units.") self._wave = wavelength self.wave_units = wavelength.unit
[ "def", "wave", "(", "self", ",", "wavelength", ")", ":", "# Test units", "if", "not", "isinstance", "(", "wavelength", ",", "q", ".", "quantity", ".", "Quantity", ")", ":", "raise", "ValueError", "(", "\"Wavelength must be in length units.\"", ")", "self", ".", "_wave", "=", "wavelength", "self", ".", "wave_units", "=", "wavelength", ".", "unit" ]
A setter for the wavelength Parameters ---------- wavelength: astropy.units.quantity.Quantity The array with units
[ "A", "setter", "for", "the", "wavelength" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L712-L725
train
hover2pi/svo_filters
svo_filters/svo.py
Filter.wave_units
def wave_units(self, units): """ A setter for the wavelength units Parameters ---------- units: str, astropy.units.core.PrefixUnit The wavelength units """ # Make sure it's length units if not units.is_equivalent(q.m): raise ValueError(units, ": New wavelength units must be a length.") # Update the units self._wave_units = units # Update all the wavelength values self._wave = self.wave.to(self.wave_units).round(5) self.wave_min = self.wave_min.to(self.wave_units).round(5) self.wave_max = self.wave_max.to(self.wave_units).round(5) self.wave_eff = self.wave_eff.to(self.wave_units).round(5) self.wave_center = self.wave_center.to(self.wave_units).round(5) self.wave_mean = self.wave_mean.to(self.wave_units).round(5) self.wave_peak = self.wave_peak.to(self.wave_units).round(5) self.wave_phot = self.wave_phot.to(self.wave_units).round(5) self.wave_pivot = self.wave_pivot.to(self.wave_units).round(5) self.width_eff = self.width_eff.to(self.wave_units).round(5) self.fwhm = self.fwhm.to(self.wave_units).round(5)
python
def wave_units(self, units): """ A setter for the wavelength units Parameters ---------- units: str, astropy.units.core.PrefixUnit The wavelength units """ # Make sure it's length units if not units.is_equivalent(q.m): raise ValueError(units, ": New wavelength units must be a length.") # Update the units self._wave_units = units # Update all the wavelength values self._wave = self.wave.to(self.wave_units).round(5) self.wave_min = self.wave_min.to(self.wave_units).round(5) self.wave_max = self.wave_max.to(self.wave_units).round(5) self.wave_eff = self.wave_eff.to(self.wave_units).round(5) self.wave_center = self.wave_center.to(self.wave_units).round(5) self.wave_mean = self.wave_mean.to(self.wave_units).round(5) self.wave_peak = self.wave_peak.to(self.wave_units).round(5) self.wave_phot = self.wave_phot.to(self.wave_units).round(5) self.wave_pivot = self.wave_pivot.to(self.wave_units).round(5) self.width_eff = self.width_eff.to(self.wave_units).round(5) self.fwhm = self.fwhm.to(self.wave_units).round(5)
[ "def", "wave_units", "(", "self", ",", "units", ")", ":", "# Make sure it's length units", "if", "not", "units", ".", "is_equivalent", "(", "q", ".", "m", ")", ":", "raise", "ValueError", "(", "units", ",", "\": New wavelength units must be a length.\"", ")", "# Update the units", "self", ".", "_wave_units", "=", "units", "# Update all the wavelength values", "self", ".", "_wave", "=", "self", ".", "wave", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "wave_min", "=", "self", ".", "wave_min", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "wave_max", "=", "self", ".", "wave_max", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "wave_eff", "=", "self", ".", "wave_eff", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "wave_center", "=", "self", ".", "wave_center", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "wave_mean", "=", "self", ".", "wave_mean", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "wave_peak", "=", "self", ".", "wave_peak", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "wave_phot", "=", "self", ".", "wave_phot", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "wave_pivot", "=", "self", ".", "wave_pivot", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "width_eff", "=", "self", ".", "width_eff", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")", "self", ".", "fwhm", "=", "self", ".", "fwhm", ".", "to", "(", "self", ".", "wave_units", ")", ".", "round", "(", "5", ")" ]
A setter for the wavelength units Parameters ---------- units: str, astropy.units.core.PrefixUnit The wavelength units
[ "A", "setter", "for", "the", "wavelength", "units" ]
f0587c4908baf636d4bdf030fa95029e8f31b975
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L733-L760
train
bitesofcode/projexui
projexui/widgets/xdocktoolbar.py
XDockToolbar.clear
def clear(self): """ Clears out all the actions and items from this toolbar. """ # clear the actions from this widget for act in self.actions(): act.setParent(None) act.deleteLater() # clear the labels from this widget for lbl in self.actionLabels(): lbl.close() lbl.deleteLater()
python
def clear(self): """ Clears out all the actions and items from this toolbar. """ # clear the actions from this widget for act in self.actions(): act.setParent(None) act.deleteLater() # clear the labels from this widget for lbl in self.actionLabels(): lbl.close() lbl.deleteLater()
[ "def", "clear", "(", "self", ")", ":", "# clear the actions from this widget\r", "for", "act", "in", "self", ".", "actions", "(", ")", ":", "act", ".", "setParent", "(", "None", ")", "act", ".", "deleteLater", "(", ")", "# clear the labels from this widget\r", "for", "lbl", "in", "self", ".", "actionLabels", "(", ")", ":", "lbl", ".", "close", "(", ")", "lbl", ".", "deleteLater", "(", ")" ]
Clears out all the actions and items from this toolbar.
[ "Clears", "out", "all", "the", "actions", "and", "items", "from", "this", "toolbar", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xdocktoolbar.py#L242-L254
train
bitesofcode/projexui
projexui/widgets/xdocktoolbar.py
XDockToolbar.resizeToMinimum
def resizeToMinimum(self): """ Resizes the dock toolbar to the minimum sizes. """ offset = self.padding() min_size = self.minimumPixmapSize() if self.position() in (XDockToolbar.Position.East, XDockToolbar.Position.West): self.resize(min_size.width() + offset, self.height()) elif self.position() in (XDockToolbar.Position.North, XDockToolbar.Position.South): self.resize(self.width(), min_size.height() + offset)
python
def resizeToMinimum(self): """ Resizes the dock toolbar to the minimum sizes. """ offset = self.padding() min_size = self.minimumPixmapSize() if self.position() in (XDockToolbar.Position.East, XDockToolbar.Position.West): self.resize(min_size.width() + offset, self.height()) elif self.position() in (XDockToolbar.Position.North, XDockToolbar.Position.South): self.resize(self.width(), min_size.height() + offset)
[ "def", "resizeToMinimum", "(", "self", ")", ":", "offset", "=", "self", ".", "padding", "(", ")", "min_size", "=", "self", ".", "minimumPixmapSize", "(", ")", "if", "self", ".", "position", "(", ")", "in", "(", "XDockToolbar", ".", "Position", ".", "East", ",", "XDockToolbar", ".", "Position", ".", "West", ")", ":", "self", ".", "resize", "(", "min_size", ".", "width", "(", ")", "+", "offset", ",", "self", ".", "height", "(", ")", ")", "elif", "self", ".", "position", "(", ")", "in", "(", "XDockToolbar", ".", "Position", ".", "North", ",", "XDockToolbar", ".", "Position", ".", "South", ")", ":", "self", ".", "resize", "(", "self", ".", "width", "(", ")", ",", "min_size", ".", "height", "(", ")", "+", "offset", ")" ]
Resizes the dock toolbar to the minimum sizes.
[ "Resizes", "the", "dock", "toolbar", "to", "the", "minimum", "sizes", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xdocktoolbar.py#L490-L503
train
bitesofcode/projexui
projexui/widgets/xdocktoolbar.py
XDockToolbar.unholdAction
def unholdAction(self): """ Unholds the action from being blocked on the leave event. """ self._actionHeld = False point = self.mapFromGlobal(QCursor.pos()) self.setCurrentAction(self.actionAt(point))
python
def unholdAction(self): """ Unholds the action from being blocked on the leave event. """ self._actionHeld = False point = self.mapFromGlobal(QCursor.pos()) self.setCurrentAction(self.actionAt(point))
[ "def", "unholdAction", "(", "self", ")", ":", "self", ".", "_actionHeld", "=", "False", "point", "=", "self", ".", "mapFromGlobal", "(", "QCursor", ".", "pos", "(", ")", ")", "self", ".", "setCurrentAction", "(", "self", ".", "actionAt", "(", "point", ")", ")" ]
Unholds the action from being blocked on the leave event.
[ "Unholds", "the", "action", "from", "being", "blocked", "on", "the", "leave", "event", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xdocktoolbar.py#L741-L748
train
bitesofcode/projexui
projexui/xscheme.py
XScheme.apply
def apply( self ): """ Applies the scheme to the current application. """ font = self.value('font') try: font.setPointSize(self.value('fontSize')) # errors in linux for some reason except TypeError: pass palette = self.value('colorSet').palette() if ( unwrapVariant(QApplication.instance().property('useScheme')) ): QApplication.instance().setFont(font) QApplication.instance().setPalette(palette) # hack to support MDI Areas for widget in QApplication.topLevelWidgets(): for area in widget.findChildren(QMdiArea): area.setPalette(palette) else: logger.debug('The application doesnt have the useScheme property.')
python
def apply( self ): """ Applies the scheme to the current application. """ font = self.value('font') try: font.setPointSize(self.value('fontSize')) # errors in linux for some reason except TypeError: pass palette = self.value('colorSet').palette() if ( unwrapVariant(QApplication.instance().property('useScheme')) ): QApplication.instance().setFont(font) QApplication.instance().setPalette(palette) # hack to support MDI Areas for widget in QApplication.topLevelWidgets(): for area in widget.findChildren(QMdiArea): area.setPalette(palette) else: logger.debug('The application doesnt have the useScheme property.')
[ "def", "apply", "(", "self", ")", ":", "font", "=", "self", ".", "value", "(", "'font'", ")", "try", ":", "font", ".", "setPointSize", "(", "self", ".", "value", "(", "'fontSize'", ")", ")", "# errors in linux for some reason\r", "except", "TypeError", ":", "pass", "palette", "=", "self", ".", "value", "(", "'colorSet'", ")", ".", "palette", "(", ")", "if", "(", "unwrapVariant", "(", "QApplication", ".", "instance", "(", ")", ".", "property", "(", "'useScheme'", ")", ")", ")", ":", "QApplication", ".", "instance", "(", ")", ".", "setFont", "(", "font", ")", "QApplication", ".", "instance", "(", ")", ".", "setPalette", "(", "palette", ")", "# hack to support MDI Areas\r", "for", "widget", "in", "QApplication", ".", "topLevelWidgets", "(", ")", ":", "for", "area", "in", "widget", ".", "findChildren", "(", "QMdiArea", ")", ":", "area", ".", "setPalette", "(", "palette", ")", "else", ":", "logger", ".", "debug", "(", "'The application doesnt have the useScheme property.'", ")" ]
Applies the scheme to the current application.
[ "Applies", "the", "scheme", "to", "the", "current", "application", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xscheme.py#L38-L62
train
bitesofcode/projexui
projexui/xscheme.py
XScheme.reset
def reset( self ): """ Resets the values to the current application information. """ self.setValue('colorSet', XPaletteColorSet()) self.setValue('font', QApplication.font()) self.setValue('fontSize', QApplication.font().pointSize())
python
def reset( self ): """ Resets the values to the current application information. """ self.setValue('colorSet', XPaletteColorSet()) self.setValue('font', QApplication.font()) self.setValue('fontSize', QApplication.font().pointSize())
[ "def", "reset", "(", "self", ")", ":", "self", ".", "setValue", "(", "'colorSet'", ",", "XPaletteColorSet", "(", ")", ")", "self", ".", "setValue", "(", "'font'", ",", "QApplication", ".", "font", "(", ")", ")", "self", ".", "setValue", "(", "'fontSize'", ",", "QApplication", ".", "font", "(", ")", ".", "pointSize", "(", ")", ")" ]
Resets the values to the current application information.
[ "Resets", "the", "values", "to", "the", "current", "application", "information", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xscheme.py#L64-L70
train
bitesofcode/projexui
projexui/widgets/xcommentedit.py
XCommentEdit.pickAttachment
def pickAttachment(self): """ Prompts the user to select an attachment to add to this edit. """ filename = QFileDialog.getOpenFileName(self.window(), 'Select Attachment', '', 'All Files (*.*)') if type(filename) == tuple: filename = nativestring(filename[0]) filename = nativestring(filename) if filename: self.addAttachment(os.path.basename(filename), filename)
python
def pickAttachment(self): """ Prompts the user to select an attachment to add to this edit. """ filename = QFileDialog.getOpenFileName(self.window(), 'Select Attachment', '', 'All Files (*.*)') if type(filename) == tuple: filename = nativestring(filename[0]) filename = nativestring(filename) if filename: self.addAttachment(os.path.basename(filename), filename)
[ "def", "pickAttachment", "(", "self", ")", ":", "filename", "=", "QFileDialog", ".", "getOpenFileName", "(", "self", ".", "window", "(", ")", ",", "'Select Attachment'", ",", "''", ",", "'All Files (*.*)'", ")", "if", "type", "(", "filename", ")", "==", "tuple", ":", "filename", "=", "nativestring", "(", "filename", "[", "0", "]", ")", "filename", "=", "nativestring", "(", "filename", ")", "if", "filename", ":", "self", ".", "addAttachment", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "filename", ")" ]
Prompts the user to select an attachment to add to this edit.
[ "Prompts", "the", "user", "to", "select", "an", "attachment", "to", "add", "to", "this", "edit", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcommentedit.py#L145-L159
train
bitesofcode/projexui
projexui/widgets/xcommentedit.py
XCommentEdit.resizeToContents
def resizeToContents(self): """ Resizes this toolbar based on the contents of its text. """ if self._toolbar.isVisible(): doc = self.document() h = doc.documentLayout().documentSize().height() offset = 34 # update the attachments edit edit = self._attachmentsEdit if self._attachments: edit.move(2, self.height() - edit.height() - 31) edit.setTags(sorted(self._attachments.keys())) edit.show() offset = 34 + edit.height() else: edit.hide() offset = 34 self.setFixedHeight(h + offset) self._toolbar.move(2, self.height() - 32) else: super(XCommentEdit, self).resizeToContents()
python
def resizeToContents(self): """ Resizes this toolbar based on the contents of its text. """ if self._toolbar.isVisible(): doc = self.document() h = doc.documentLayout().documentSize().height() offset = 34 # update the attachments edit edit = self._attachmentsEdit if self._attachments: edit.move(2, self.height() - edit.height() - 31) edit.setTags(sorted(self._attachments.keys())) edit.show() offset = 34 + edit.height() else: edit.hide() offset = 34 self.setFixedHeight(h + offset) self._toolbar.move(2, self.height() - 32) else: super(XCommentEdit, self).resizeToContents()
[ "def", "resizeToContents", "(", "self", ")", ":", "if", "self", ".", "_toolbar", ".", "isVisible", "(", ")", ":", "doc", "=", "self", ".", "document", "(", ")", "h", "=", "doc", ".", "documentLayout", "(", ")", ".", "documentSize", "(", ")", ".", "height", "(", ")", "offset", "=", "34", "# update the attachments edit\r", "edit", "=", "self", ".", "_attachmentsEdit", "if", "self", ".", "_attachments", ":", "edit", ".", "move", "(", "2", ",", "self", ".", "height", "(", ")", "-", "edit", ".", "height", "(", ")", "-", "31", ")", "edit", ".", "setTags", "(", "sorted", "(", "self", ".", "_attachments", ".", "keys", "(", ")", ")", ")", "edit", ".", "show", "(", ")", "offset", "=", "34", "+", "edit", ".", "height", "(", ")", "else", ":", "edit", ".", "hide", "(", ")", "offset", "=", "34", "self", ".", "setFixedHeight", "(", "h", "+", "offset", ")", "self", ".", "_toolbar", ".", "move", "(", "2", ",", "self", ".", "height", "(", ")", "-", "32", ")", "else", ":", "super", "(", "XCommentEdit", ",", "self", ")", ".", "resizeToContents", "(", ")" ]
Resizes this toolbar based on the contents of its text.
[ "Resizes", "this", "toolbar", "based", "on", "the", "contents", "of", "its", "text", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcommentedit.py#L183-L208
train
johnnoone/aioconsul
aioconsul/client/operator_endpoint.py
OperatorEndpoint.configuration
async def configuration(self, *, dc=None, consistency=None): """Inspects the Raft configuration Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. consistency (str): Read the Raft configuration from any of the Consul servers, otherwise raise an exception if the cluster doesn't currently have a leader. Returns: Object: A JSON body is returned that looks like this:: { "Servers": [ { "ID": "127.0.0.1:8300", "Node": "alice", "Address": "127.0.0.1:8300", "Leader": True, "Voter": True }, { "ID": "127.0.0.2:8300", "Node": "bob", "Address": "127.0.0.2:8300", "Leader": False, "Voter": True }, { "ID": "127.0.0.3:8300", "Node": "carol", "Address": "127.0.0.3:8300", "Leader": False, "Voter": True } ], "Index": 22 } The **Servers** array has information about the servers in the Raft peer configuration: **ID** is the ID of the server. This is the same as the **Address**. **Node** is the node name of the server, as known to Consul, or "(unknown)" if the node is stale and not known. **Address** is the IP:port for the server. **Leader** is either ``True`` or ``False`` depending on the server's role in the Raft configuration. **Voter** is ``True`` or ``False``, indicating if the server has a vote in the Raft configuration. Future versions of Consul may add support for non-voting servers. The **Index** value is the Raft corresponding to this configuration. Note that the latest configuration may not yet be committed if changes are in flight. """ response = await self._api.get("/v1/operator/raft/configuration", params={"dc": dc}, consistency=consistency) return response.body
python
async def configuration(self, *, dc=None, consistency=None): """Inspects the Raft configuration Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. consistency (str): Read the Raft configuration from any of the Consul servers, otherwise raise an exception if the cluster doesn't currently have a leader. Returns: Object: A JSON body is returned that looks like this:: { "Servers": [ { "ID": "127.0.0.1:8300", "Node": "alice", "Address": "127.0.0.1:8300", "Leader": True, "Voter": True }, { "ID": "127.0.0.2:8300", "Node": "bob", "Address": "127.0.0.2:8300", "Leader": False, "Voter": True }, { "ID": "127.0.0.3:8300", "Node": "carol", "Address": "127.0.0.3:8300", "Leader": False, "Voter": True } ], "Index": 22 } The **Servers** array has information about the servers in the Raft peer configuration: **ID** is the ID of the server. This is the same as the **Address**. **Node** is the node name of the server, as known to Consul, or "(unknown)" if the node is stale and not known. **Address** is the IP:port for the server. **Leader** is either ``True`` or ``False`` depending on the server's role in the Raft configuration. **Voter** is ``True`` or ``False``, indicating if the server has a vote in the Raft configuration. Future versions of Consul may add support for non-voting servers. The **Index** value is the Raft corresponding to this configuration. Note that the latest configuration may not yet be committed if changes are in flight. """ response = await self._api.get("/v1/operator/raft/configuration", params={"dc": dc}, consistency=consistency) return response.body
[ "async", "def", "configuration", "(", "self", ",", "*", ",", "dc", "=", "None", ",", "consistency", "=", "None", ")", ":", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/operator/raft/configuration\"", ",", "params", "=", "{", "\"dc\"", ":", "dc", "}", ",", "consistency", "=", "consistency", ")", "return", "response", ".", "body" ]
Inspects the Raft configuration Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. consistency (str): Read the Raft configuration from any of the Consul servers, otherwise raise an exception if the cluster doesn't currently have a leader. Returns: Object: A JSON body is returned that looks like this:: { "Servers": [ { "ID": "127.0.0.1:8300", "Node": "alice", "Address": "127.0.0.1:8300", "Leader": True, "Voter": True }, { "ID": "127.0.0.2:8300", "Node": "bob", "Address": "127.0.0.2:8300", "Leader": False, "Voter": True }, { "ID": "127.0.0.3:8300", "Node": "carol", "Address": "127.0.0.3:8300", "Leader": False, "Voter": True } ], "Index": 22 } The **Servers** array has information about the servers in the Raft peer configuration: **ID** is the ID of the server. This is the same as the **Address**. **Node** is the node name of the server, as known to Consul, or "(unknown)" if the node is stale and not known. **Address** is the IP:port for the server. **Leader** is either ``True`` or ``False`` depending on the server's role in the Raft configuration. **Voter** is ``True`` or ``False``, indicating if the server has a vote in the Raft configuration. Future versions of Consul may add support for non-voting servers. The **Index** value is the Raft corresponding to this configuration. Note that the latest configuration may not yet be committed if changes are in flight.
[ "Inspects", "the", "Raft", "configuration" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/operator_endpoint.py#L7-L72
train
johnnoone/aioconsul
aioconsul/client/operator_endpoint.py
OperatorEndpoint.peer_delete
async def peer_delete(self, *, dc=None, address): """Remove the server with given address from the Raft configuration Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. address (str): "IP:port" of the server to remove. Returns: bool: ``True`` on success There are rare cases where a peer may be left behind in the Raft configuration even though the server is no longer present and known to the cluster. This endpoint can be used to remove the failed server so that it is no longer affects the Raft quorum. """ address = extract_attr(address, keys=["Address"]) params = {"dc": dc, "address": address} response = await self._api.delete("/v1/operator/raft/peer", params=params) return response.status < 400
python
async def peer_delete(self, *, dc=None, address): """Remove the server with given address from the Raft configuration Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. address (str): "IP:port" of the server to remove. Returns: bool: ``True`` on success There are rare cases where a peer may be left behind in the Raft configuration even though the server is no longer present and known to the cluster. This endpoint can be used to remove the failed server so that it is no longer affects the Raft quorum. """ address = extract_attr(address, keys=["Address"]) params = {"dc": dc, "address": address} response = await self._api.delete("/v1/operator/raft/peer", params=params) return response.status < 400
[ "async", "def", "peer_delete", "(", "self", ",", "*", ",", "dc", "=", "None", ",", "address", ")", ":", "address", "=", "extract_attr", "(", "address", ",", "keys", "=", "[", "\"Address\"", "]", ")", "params", "=", "{", "\"dc\"", ":", "dc", ",", "\"address\"", ":", "address", "}", "response", "=", "await", "self", ".", "_api", ".", "delete", "(", "\"/v1/operator/raft/peer\"", ",", "params", "=", "params", ")", "return", "response", ".", "status", "<", "400" ]
Remove the server with given address from the Raft configuration Parameters: dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. address (str): "IP:port" of the server to remove. Returns: bool: ``True`` on success There are rare cases where a peer may be left behind in the Raft configuration even though the server is no longer present and known to the cluster. This endpoint can be used to remove the failed server so that it is no longer affects the Raft quorum.
[ "Remove", "the", "server", "with", "given", "address", "from", "the", "Raft", "configuration" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/operator_endpoint.py#L74-L93
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthroughwidget.py
XWalkthroughWidget.autoLayout
def autoLayout(self): """ Automatically lays out the contents for this widget. """ try: direction = self.currentSlide().scene().direction() except AttributeError: direction = QtGui.QBoxLayout.TopToBottom size = self.size() self._slideshow.resize(size) prev = self._previousButton next = self._nextButton if direction == QtGui.QBoxLayout.BottomToTop: y = 9 else: y = size.height() - prev.height() - 9 prev.move(9, y) next.move(size.width() - next.width() - 9, y) # update the layout for the slides for i in range(self._slideshow.count()): widget = self._slideshow.widget(i) widget.scene().autoLayout(size)
python
def autoLayout(self): """ Automatically lays out the contents for this widget. """ try: direction = self.currentSlide().scene().direction() except AttributeError: direction = QtGui.QBoxLayout.TopToBottom size = self.size() self._slideshow.resize(size) prev = self._previousButton next = self._nextButton if direction == QtGui.QBoxLayout.BottomToTop: y = 9 else: y = size.height() - prev.height() - 9 prev.move(9, y) next.move(size.width() - next.width() - 9, y) # update the layout for the slides for i in range(self._slideshow.count()): widget = self._slideshow.widget(i) widget.scene().autoLayout(size)
[ "def", "autoLayout", "(", "self", ")", ":", "try", ":", "direction", "=", "self", ".", "currentSlide", "(", ")", ".", "scene", "(", ")", ".", "direction", "(", ")", "except", "AttributeError", ":", "direction", "=", "QtGui", ".", "QBoxLayout", ".", "TopToBottom", "size", "=", "self", ".", "size", "(", ")", "self", ".", "_slideshow", ".", "resize", "(", "size", ")", "prev", "=", "self", ".", "_previousButton", "next", "=", "self", ".", "_nextButton", "if", "direction", "==", "QtGui", ".", "QBoxLayout", ".", "BottomToTop", ":", "y", "=", "9", "else", ":", "y", "=", "size", ".", "height", "(", ")", "-", "prev", ".", "height", "(", ")", "-", "9", "prev", ".", "move", "(", "9", ",", "y", ")", "next", ".", "move", "(", "size", ".", "width", "(", ")", "-", "next", ".", "width", "(", ")", "-", "9", ",", "y", ")", "# update the layout for the slides\r", "for", "i", "in", "range", "(", "self", ".", "_slideshow", ".", "count", "(", ")", ")", ":", "widget", "=", "self", ".", "_slideshow", ".", "widget", "(", "i", ")", "widget", ".", "scene", "(", ")", ".", "autoLayout", "(", "size", ")" ]
Automatically lays out the contents for this widget.
[ "Automatically", "lays", "out", "the", "contents", "for", "this", "widget", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthroughwidget.py#L113-L139
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthroughwidget.py
XWalkthroughWidget.goForward
def goForward(self): """ Moves to the next slide or finishes the walkthrough. """ if self._slideshow.currentIndex() == self._slideshow.count() - 1: self.finished.emit() else: self._slideshow.slideInNext()
python
def goForward(self): """ Moves to the next slide or finishes the walkthrough. """ if self._slideshow.currentIndex() == self._slideshow.count() - 1: self.finished.emit() else: self._slideshow.slideInNext()
[ "def", "goForward", "(", "self", ")", ":", "if", "self", ".", "_slideshow", ".", "currentIndex", "(", ")", "==", "self", ".", "_slideshow", ".", "count", "(", ")", "-", "1", ":", "self", ".", "finished", ".", "emit", "(", ")", "else", ":", "self", ".", "_slideshow", ".", "slideInNext", "(", ")" ]
Moves to the next slide or finishes the walkthrough.
[ "Moves", "to", "the", "next", "slide", "or", "finishes", "the", "walkthrough", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthroughwidget.py#L187-L194
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthroughwidget.py
XWalkthroughWidget.updateUi
def updateUi(self): """ Updates the interface to show the selection buttons. """ index = self._slideshow.currentIndex() count = self._slideshow.count() self._previousButton.setVisible(index != 0) self._nextButton.setText('Finish' if index == count - 1 else 'Next') self.autoLayout()
python
def updateUi(self): """ Updates the interface to show the selection buttons. """ index = self._slideshow.currentIndex() count = self._slideshow.count() self._previousButton.setVisible(index != 0) self._nextButton.setText('Finish' if index == count - 1 else 'Next') self.autoLayout()
[ "def", "updateUi", "(", "self", ")", ":", "index", "=", "self", ".", "_slideshow", ".", "currentIndex", "(", ")", "count", "=", "self", ".", "_slideshow", ".", "count", "(", ")", "self", ".", "_previousButton", ".", "setVisible", "(", "index", "!=", "0", ")", "self", ".", "_nextButton", ".", "setText", "(", "'Finish'", "if", "index", "==", "count", "-", "1", "else", "'Next'", ")", "self", ".", "autoLayout", "(", ")" ]
Updates the interface to show the selection buttons.
[ "Updates", "the", "interface", "to", "show", "the", "selection", "buttons", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthroughwidget.py#L247-L256
train
fitnr/buoyant
buoyant/buoy.py
parse_unit
def parse_unit(prop, dictionary, dt=None): '''Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix.''' # add the observation's time try: dt = timezone.parse_datetime(dictionary.get('date_time')) except TypeError: dt = None # 'prop' is a stub of the property's attribute key, so search for matches matches = [k for k in dictionary.keys() if prop in k] try: value = dictionary[matches[0]] unit = re.search(r' \(([^)]+)\)', matches[0]) except IndexError: # No matches: fail out return None # Sometimes we get a list of values (e.g. waves) if ';' in value: # Ignore empty values values = [val for val in value.split(';') if val != ''] if unit: return [Observation(v, unit.group(1), dt) for v in values] else: return values # Sometimes there's no value! Sometimes there's no unit! if not value or not unit: return value or None return Observation(value, unit.group(1), dt)
python
def parse_unit(prop, dictionary, dt=None): '''Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix.''' # add the observation's time try: dt = timezone.parse_datetime(dictionary.get('date_time')) except TypeError: dt = None # 'prop' is a stub of the property's attribute key, so search for matches matches = [k for k in dictionary.keys() if prop in k] try: value = dictionary[matches[0]] unit = re.search(r' \(([^)]+)\)', matches[0]) except IndexError: # No matches: fail out return None # Sometimes we get a list of values (e.g. waves) if ';' in value: # Ignore empty values values = [val for val in value.split(';') if val != ''] if unit: return [Observation(v, unit.group(1), dt) for v in values] else: return values # Sometimes there's no value! Sometimes there's no unit! if not value or not unit: return value or None return Observation(value, unit.group(1), dt)
[ "def", "parse_unit", "(", "prop", ",", "dictionary", ",", "dt", "=", "None", ")", ":", "# add the observation's time", "try", ":", "dt", "=", "timezone", ".", "parse_datetime", "(", "dictionary", ".", "get", "(", "'date_time'", ")", ")", "except", "TypeError", ":", "dt", "=", "None", "# 'prop' is a stub of the property's attribute key, so search for matches", "matches", "=", "[", "k", "for", "k", "in", "dictionary", ".", "keys", "(", ")", "if", "prop", "in", "k", "]", "try", ":", "value", "=", "dictionary", "[", "matches", "[", "0", "]", "]", "unit", "=", "re", ".", "search", "(", "r' \\(([^)]+)\\)'", ",", "matches", "[", "0", "]", ")", "except", "IndexError", ":", "# No matches: fail out", "return", "None", "# Sometimes we get a list of values (e.g. waves)", "if", "';'", "in", "value", ":", "# Ignore empty values", "values", "=", "[", "val", "for", "val", "in", "value", ".", "split", "(", "';'", ")", "if", "val", "!=", "''", "]", "if", "unit", ":", "return", "[", "Observation", "(", "v", ",", "unit", ".", "group", "(", "1", ")", ",", "dt", ")", "for", "v", "in", "values", "]", "else", ":", "return", "values", "# Sometimes there's no value! Sometimes there's no unit!", "if", "not", "value", "or", "not", "unit", ":", "return", "value", "or", "None", "return", "Observation", "(", "value", ",", "unit", ".", "group", "(", "1", ")", ",", "dt", ")" ]
Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix.
[ "Do", "a", "fuzzy", "match", "for", "prop", "in", "the", "dictionary", "taking", "into", "account", "unit", "suffix", "." ]
ef7a74f9ebd4774629508ccf2c9abb43aa0235c9
https://github.com/fitnr/buoyant/blob/ef7a74f9ebd4774629508ccf2c9abb43aa0235c9/buoyant/buoy.py#L37-L70
train
bitesofcode/projexui
projexui/widgets/xorbquerywidget/xorbquerywidget.py
XOrbQueryWidget.clear
def clear(self): """ Clears all the container for this query widget. """ for i in range(self.count()): widget = self.widget(i) if widget is not None: widget.close() widget.setParent(None) widget.deleteLater()
python
def clear(self): """ Clears all the container for this query widget. """ for i in range(self.count()): widget = self.widget(i) if widget is not None: widget.close() widget.setParent(None) widget.deleteLater()
[ "def", "clear", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ":", "widget", "=", "self", ".", "widget", "(", "i", ")", "if", "widget", "is", "not", "None", ":", "widget", ".", "close", "(", ")", "widget", ".", "setParent", "(", "None", ")", "widget", ".", "deleteLater", "(", ")" ]
Clears all the container for this query widget.
[ "Clears", "all", "the", "container", "for", "this", "query", "widget", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquerywidget.py#L78-L87
train
bitesofcode/projexui
projexui/widgets/xorbquerywidget/xorbquerywidget.py
XOrbQueryWidget.cleanupContainers
def cleanupContainers(self): """ Cleans up all containers to the right of the current one. """ for i in range(self.count() - 1, self.currentIndex(), -1): widget = self.widget(i) widget.close() widget.setParent(None) widget.deleteLater()
python
def cleanupContainers(self): """ Cleans up all containers to the right of the current one. """ for i in range(self.count() - 1, self.currentIndex(), -1): widget = self.widget(i) widget.close() widget.setParent(None) widget.deleteLater()
[ "def", "cleanupContainers", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", "-", "1", ",", "self", ".", "currentIndex", "(", ")", ",", "-", "1", ")", ":", "widget", "=", "self", ".", "widget", "(", "i", ")", "widget", ".", "close", "(", ")", "widget", ".", "setParent", "(", "None", ")", "widget", ".", "deleteLater", "(", ")" ]
Cleans up all containers to the right of the current one.
[ "Cleans", "up", "all", "containers", "to", "the", "right", "of", "the", "current", "one", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquerywidget.py#L89-L97
train
bitesofcode/projexui
projexui/widgets/xorbquerywidget/xorbquerywidget.py
XOrbQueryWidget.exitContainer
def exitContainer(self): """ Removes the current query container. """ try: entry = self._compoundStack.pop() except IndexError: return container = self.currentContainer() entry.setQuery(container.query()) self.slideInPrev()
python
def exitContainer(self): """ Removes the current query container. """ try: entry = self._compoundStack.pop() except IndexError: return container = self.currentContainer() entry.setQuery(container.query()) self.slideInPrev()
[ "def", "exitContainer", "(", "self", ")", ":", "try", ":", "entry", "=", "self", ".", "_compoundStack", ".", "pop", "(", ")", "except", "IndexError", ":", "return", "container", "=", "self", ".", "currentContainer", "(", ")", "entry", ".", "setQuery", "(", "container", ".", "query", "(", ")", ")", "self", ".", "slideInPrev", "(", ")" ]
Removes the current query container.
[ "Removes", "the", "current", "query", "container", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquerywidget.py#L143-L155
train
bitesofcode/projexui
projexui/widgets/xorbrecordedit.py
XOrbRecordEdit.rebuild
def rebuild( self ): """ Rebuilds the interface for this widget based on the current model. """ self.setUpdatesEnabled(False) self.blockSignals(True) # clear out all the subwidgets for this widget for child in self.findChildren(QObject): child.setParent(None) child.deleteLater() # load up all the interface for this widget schema = self.schema() if ( schema ): self.setEnabled(True) uifile = self.uiFile() # load a user defined file if ( uifile ): projexui.loadUi('', self, uifile) for widget in self.findChildren(XOrbColumnEdit): columnName = widget.columnName() column = schema.column(columnName) if ( column ): widget.setColumn(column) else: logger.debug('%s is not a valid column of %s' % \ (columnName, schema.name())) # dynamically load files else: layout = QFormLayout() layout.setContentsMargins(0, 0, 0, 0) columns = schema.columns() columns.sort(key = lambda x: x.displayName()) record = self.record() for column in columns: # ignore protected columns if ( column.name().startswith('_') ): continue label = column.displayName() coltype = column.columnType() name = column.name() # create the column edit widget widget = XOrbColumnEdit(self) widget.setObjectName('ui_' + name) widget.setColumnName(name) widget.setColumnType(coltype) widget.setColumn(column) layout.addRow(QLabel(label, self), widget) self.setLayout(layout) self.adjustSize() self.setWindowTitle('Edit %s' % schema.name()) else: self.setEnabled(False) self.setUpdatesEnabled(True) self.blockSignals(False)
python
def rebuild( self ): """ Rebuilds the interface for this widget based on the current model. """ self.setUpdatesEnabled(False) self.blockSignals(True) # clear out all the subwidgets for this widget for child in self.findChildren(QObject): child.setParent(None) child.deleteLater() # load up all the interface for this widget schema = self.schema() if ( schema ): self.setEnabled(True) uifile = self.uiFile() # load a user defined file if ( uifile ): projexui.loadUi('', self, uifile) for widget in self.findChildren(XOrbColumnEdit): columnName = widget.columnName() column = schema.column(columnName) if ( column ): widget.setColumn(column) else: logger.debug('%s is not a valid column of %s' % \ (columnName, schema.name())) # dynamically load files else: layout = QFormLayout() layout.setContentsMargins(0, 0, 0, 0) columns = schema.columns() columns.sort(key = lambda x: x.displayName()) record = self.record() for column in columns: # ignore protected columns if ( column.name().startswith('_') ): continue label = column.displayName() coltype = column.columnType() name = column.name() # create the column edit widget widget = XOrbColumnEdit(self) widget.setObjectName('ui_' + name) widget.setColumnName(name) widget.setColumnType(coltype) widget.setColumn(column) layout.addRow(QLabel(label, self), widget) self.setLayout(layout) self.adjustSize() self.setWindowTitle('Edit %s' % schema.name()) else: self.setEnabled(False) self.setUpdatesEnabled(True) self.blockSignals(False)
[ "def", "rebuild", "(", "self", ")", ":", "self", ".", "setUpdatesEnabled", "(", "False", ")", "self", ".", "blockSignals", "(", "True", ")", "# clear out all the subwidgets for this widget\r", "for", "child", "in", "self", ".", "findChildren", "(", "QObject", ")", ":", "child", ".", "setParent", "(", "None", ")", "child", ".", "deleteLater", "(", ")", "# load up all the interface for this widget\r", "schema", "=", "self", ".", "schema", "(", ")", "if", "(", "schema", ")", ":", "self", ".", "setEnabled", "(", "True", ")", "uifile", "=", "self", ".", "uiFile", "(", ")", "# load a user defined file\r", "if", "(", "uifile", ")", ":", "projexui", ".", "loadUi", "(", "''", ",", "self", ",", "uifile", ")", "for", "widget", "in", "self", ".", "findChildren", "(", "XOrbColumnEdit", ")", ":", "columnName", "=", "widget", ".", "columnName", "(", ")", "column", "=", "schema", ".", "column", "(", "columnName", ")", "if", "(", "column", ")", ":", "widget", ".", "setColumn", "(", "column", ")", "else", ":", "logger", ".", "debug", "(", "'%s is not a valid column of %s'", "%", "(", "columnName", ",", "schema", ".", "name", "(", ")", ")", ")", "# dynamically load files\r", "else", ":", "layout", "=", "QFormLayout", "(", ")", "layout", ".", "setContentsMargins", "(", "0", ",", "0", ",", "0", ",", "0", ")", "columns", "=", "schema", ".", "columns", "(", ")", "columns", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "displayName", "(", ")", ")", "record", "=", "self", ".", "record", "(", ")", "for", "column", "in", "columns", ":", "# ignore protected columns\r", "if", "(", "column", ".", "name", "(", ")", ".", "startswith", "(", "'_'", ")", ")", ":", "continue", "label", "=", "column", ".", "displayName", "(", ")", "coltype", "=", "column", ".", "columnType", "(", ")", "name", "=", "column", ".", "name", "(", ")", "# create the column edit widget\r", "widget", "=", "XOrbColumnEdit", "(", "self", ")", "widget", ".", "setObjectName", "(", "'ui_'", "+", "name", ")", "widget", ".", "setColumnName", "(", "name", ")", "widget", ".", "setColumnType", "(", "coltype", ")", "widget", ".", "setColumn", "(", "column", ")", "layout", ".", "addRow", "(", "QLabel", "(", "label", ",", "self", ")", ",", "widget", ")", "self", ".", "setLayout", "(", "layout", ")", "self", ".", "adjustSize", "(", ")", "self", ".", "setWindowTitle", "(", "'Edit %s'", "%", "schema", ".", "name", "(", ")", ")", "else", ":", "self", ".", "setEnabled", "(", "False", ")", "self", ".", "setUpdatesEnabled", "(", "True", ")", "self", ".", "blockSignals", "(", "False", ")" ]
Rebuilds the interface for this widget based on the current model.
[ "Rebuilds", "the", "interface", "for", "this", "widget", "based", "on", "the", "current", "model", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordedit.py#L78-L146
train
bitesofcode/projexui
projexui/widgets/xorbrecordedit.py
XOrbRecordEdit.save
def save( self ): """ Saves the values from the editor to the system. """ schema = self.schema() if ( not schema ): self.saved.emit() return record = self.record() if not record: record = self._model() # validate the information save_data = [] column_edits = self.findChildren(XOrbColumnEdit) for widget in column_edits: columnName = widget.columnName() column = schema.column(columnName) if ( not column ): logger.warning('%s is not a valid column of %s.' % \ (columnName, schema.name())) continue value = widget.value() if ( value == IGNORED ): continue # check for required columns if ( column.required() and not value ): name = column.displayName() QMessageBox.information(self, 'Missing Required Field', '%s is a required field.' % name) return # check for unique columns elif ( column.unique() ): # check for uniqueness query = Q(column.name()) == value if ( record.isRecord() ): query &= Q(self._model) != record columns = self._model.schema().primaryColumns() result = self._model.select(columns = columns, where = query) if ( result.total() ): QMessageBox.information(self, 'Duplicate Entry', '%s already exists.' % value) return save_data.append((column, value)) # record the properties for the record for column, value in save_data: record.setRecordValue(column.name(), value) self._record = record self.saved.emit()
python
def save( self ): """ Saves the values from the editor to the system. """ schema = self.schema() if ( not schema ): self.saved.emit() return record = self.record() if not record: record = self._model() # validate the information save_data = [] column_edits = self.findChildren(XOrbColumnEdit) for widget in column_edits: columnName = widget.columnName() column = schema.column(columnName) if ( not column ): logger.warning('%s is not a valid column of %s.' % \ (columnName, schema.name())) continue value = widget.value() if ( value == IGNORED ): continue # check for required columns if ( column.required() and not value ): name = column.displayName() QMessageBox.information(self, 'Missing Required Field', '%s is a required field.' % name) return # check for unique columns elif ( column.unique() ): # check for uniqueness query = Q(column.name()) == value if ( record.isRecord() ): query &= Q(self._model) != record columns = self._model.schema().primaryColumns() result = self._model.select(columns = columns, where = query) if ( result.total() ): QMessageBox.information(self, 'Duplicate Entry', '%s already exists.' % value) return save_data.append((column, value)) # record the properties for the record for column, value in save_data: record.setRecordValue(column.name(), value) self._record = record self.saved.emit()
[ "def", "save", "(", "self", ")", ":", "schema", "=", "self", ".", "schema", "(", ")", "if", "(", "not", "schema", ")", ":", "self", ".", "saved", ".", "emit", "(", ")", "return", "record", "=", "self", ".", "record", "(", ")", "if", "not", "record", ":", "record", "=", "self", ".", "_model", "(", ")", "# validate the information\r", "save_data", "=", "[", "]", "column_edits", "=", "self", ".", "findChildren", "(", "XOrbColumnEdit", ")", "for", "widget", "in", "column_edits", ":", "columnName", "=", "widget", ".", "columnName", "(", ")", "column", "=", "schema", ".", "column", "(", "columnName", ")", "if", "(", "not", "column", ")", ":", "logger", ".", "warning", "(", "'%s is not a valid column of %s.'", "%", "(", "columnName", ",", "schema", ".", "name", "(", ")", ")", ")", "continue", "value", "=", "widget", ".", "value", "(", ")", "if", "(", "value", "==", "IGNORED", ")", ":", "continue", "# check for required columns\r", "if", "(", "column", ".", "required", "(", ")", "and", "not", "value", ")", ":", "name", "=", "column", ".", "displayName", "(", ")", "QMessageBox", ".", "information", "(", "self", ",", "'Missing Required Field'", ",", "'%s is a required field.'", "%", "name", ")", "return", "# check for unique columns\r", "elif", "(", "column", ".", "unique", "(", ")", ")", ":", "# check for uniqueness\r", "query", "=", "Q", "(", "column", ".", "name", "(", ")", ")", "==", "value", "if", "(", "record", ".", "isRecord", "(", ")", ")", ":", "query", "&=", "Q", "(", "self", ".", "_model", ")", "!=", "record", "columns", "=", "self", ".", "_model", ".", "schema", "(", ")", ".", "primaryColumns", "(", ")", "result", "=", "self", ".", "_model", ".", "select", "(", "columns", "=", "columns", ",", "where", "=", "query", ")", "if", "(", "result", ".", "total", "(", ")", ")", ":", "QMessageBox", ".", "information", "(", "self", ",", "'Duplicate Entry'", ",", "'%s already exists.'", "%", "value", ")", "return", "save_data", ".", "append", "(", "(", "column", ",", "value", ")", ")", "# record the properties for the record\r", "for", "column", ",", "value", "in", "save_data", ":", "record", ".", "setRecordValue", "(", "column", ".", "name", "(", ")", ",", "value", ")", "self", ".", "_record", "=", "record", "self", ".", "saved", ".", "emit", "(", ")" ]
Saves the values from the editor to the system.
[ "Saves", "the", "values", "from", "the", "editor", "to", "the", "system", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordedit.py#L149-L210
train
bitesofcode/projexui
projexui/widgets/xtextedit.py
XTextEdit.acceptText
def acceptText(self): """ Emits the editing finished signals for this widget. """ if not self.signalsBlocked(): self.textEntered.emit(self.toPlainText()) self.htmlEntered.emit(self.toHtml()) self.returnPressed.emit()
python
def acceptText(self): """ Emits the editing finished signals for this widget. """ if not self.signalsBlocked(): self.textEntered.emit(self.toPlainText()) self.htmlEntered.emit(self.toHtml()) self.returnPressed.emit()
[ "def", "acceptText", "(", "self", ")", ":", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "textEntered", ".", "emit", "(", "self", ".", "toPlainText", "(", ")", ")", "self", ".", "htmlEntered", ".", "emit", "(", "self", ".", "toHtml", "(", ")", ")", "self", ".", "returnPressed", ".", "emit", "(", ")" ]
Emits the editing finished signals for this widget.
[ "Emits", "the", "editing", "finished", "signals", "for", "this", "widget", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtextedit.py#L51-L58
train
bitesofcode/projexui
projexui/widgets/xtextedit.py
XTextEdit.clear
def clear(self): """ Clears the text for this edit and resizes the toolbar information. """ super(XTextEdit, self).clear() self.textEntered.emit('') self.htmlEntered.emit('') if self.autoResizeToContents(): self.resizeToContents()
python
def clear(self): """ Clears the text for this edit and resizes the toolbar information. """ super(XTextEdit, self).clear() self.textEntered.emit('') self.htmlEntered.emit('') if self.autoResizeToContents(): self.resizeToContents()
[ "def", "clear", "(", "self", ")", ":", "super", "(", "XTextEdit", ",", "self", ")", ".", "clear", "(", ")", "self", ".", "textEntered", ".", "emit", "(", "''", ")", "self", ".", "htmlEntered", ".", "emit", "(", "''", ")", "if", "self", ".", "autoResizeToContents", "(", ")", ":", "self", ".", "resizeToContents", "(", ")" ]
Clears the text for this edit and resizes the toolbar information.
[ "Clears", "the", "text", "for", "this", "edit", "and", "resizes", "the", "toolbar", "information", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtextedit.py#L70-L80
train
bitesofcode/projexui
projexui/widgets/xtextedit.py
XTextEdit.paste
def paste(self): """ Pastes text from the clipboard into this edit. """ html = QApplication.clipboard().text() if not self.isRichTextEditEnabled(): self.insertPlainText(projex.text.toAscii(html)) else: super(XTextEdit, self).paste()
python
def paste(self): """ Pastes text from the clipboard into this edit. """ html = QApplication.clipboard().text() if not self.isRichTextEditEnabled(): self.insertPlainText(projex.text.toAscii(html)) else: super(XTextEdit, self).paste()
[ "def", "paste", "(", "self", ")", ":", "html", "=", "QApplication", ".", "clipboard", "(", ")", ".", "text", "(", ")", "if", "not", "self", ".", "isRichTextEditEnabled", "(", ")", ":", "self", ".", "insertPlainText", "(", "projex", ".", "text", ".", "toAscii", "(", "html", ")", ")", "else", ":", "super", "(", "XTextEdit", ",", "self", ")", ".", "paste", "(", ")" ]
Pastes text from the clipboard into this edit.
[ "Pastes", "text", "from", "the", "clipboard", "into", "this", "edit", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtextedit.py#L198-L206
train
bitesofcode/projexui
projexui/widgets/xtextedit.py
XTextEdit.resizeToContents
def resizeToContents(self): """ Resizes this widget to fit the contents of its text. """ doc = self.document() h = doc.documentLayout().documentSize().height() self.setFixedHeight(h + 4)
python
def resizeToContents(self): """ Resizes this widget to fit the contents of its text. """ doc = self.document() h = doc.documentLayout().documentSize().height() self.setFixedHeight(h + 4)
[ "def", "resizeToContents", "(", "self", ")", ":", "doc", "=", "self", ".", "document", "(", ")", "h", "=", "doc", ".", "documentLayout", "(", ")", ".", "documentSize", "(", ")", ".", "height", "(", ")", "self", ".", "setFixedHeight", "(", "h", "+", "4", ")" ]
Resizes this widget to fit the contents of its text.
[ "Resizes", "this", "widget", "to", "fit", "the", "contents", "of", "its", "text", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtextedit.py#L231-L237
train
bitesofcode/projexui
projexui/widgets/xgroupbox.py
XGroupBox.matchCollapsedState
def matchCollapsedState( self ): """ Matches the collapsed state for this groupbox. """ collapsed = not self.isChecked() if self._inverted: collapsed = not collapsed if ( not self.isCollapsible() or not collapsed ): for child in self.children(): if ( not isinstance(child, QWidget) ): continue child.show() self.setMaximumHeight(MAX_INT) self.adjustSize() if ( self.parent() ): self.parent().adjustSize() else: self.setMaximumHeight(self.collapsedHeight()) for child in self.children(): if ( not isinstance(child, QWidget) ): continue child.hide()
python
def matchCollapsedState( self ): """ Matches the collapsed state for this groupbox. """ collapsed = not self.isChecked() if self._inverted: collapsed = not collapsed if ( not self.isCollapsible() or not collapsed ): for child in self.children(): if ( not isinstance(child, QWidget) ): continue child.show() self.setMaximumHeight(MAX_INT) self.adjustSize() if ( self.parent() ): self.parent().adjustSize() else: self.setMaximumHeight(self.collapsedHeight()) for child in self.children(): if ( not isinstance(child, QWidget) ): continue child.hide()
[ "def", "matchCollapsedState", "(", "self", ")", ":", "collapsed", "=", "not", "self", ".", "isChecked", "(", ")", "if", "self", ".", "_inverted", ":", "collapsed", "=", "not", "collapsed", "if", "(", "not", "self", ".", "isCollapsible", "(", ")", "or", "not", "collapsed", ")", ":", "for", "child", "in", "self", ".", "children", "(", ")", ":", "if", "(", "not", "isinstance", "(", "child", ",", "QWidget", ")", ")", ":", "continue", "child", ".", "show", "(", ")", "self", ".", "setMaximumHeight", "(", "MAX_INT", ")", "self", ".", "adjustSize", "(", ")", "if", "(", "self", ".", "parent", "(", ")", ")", ":", "self", ".", "parent", "(", ")", ".", "adjustSize", "(", ")", "else", ":", "self", ".", "setMaximumHeight", "(", "self", ".", "collapsedHeight", "(", ")", ")", "for", "child", "in", "self", ".", "children", "(", ")", ":", "if", "(", "not", "isinstance", "(", "child", ",", "QWidget", ")", ")", ":", "continue", "child", ".", "hide", "(", ")" ]
Matches the collapsed state for this groupbox.
[ "Matches", "the", "collapsed", "state", "for", "this", "groupbox", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xgroupbox.py#L99-L126
train
bitesofcode/projexui
projexui/xcommands.py
import_qt
def import_qt(glbls): """ Delayed qt loader. """ if 'QtCore' in glbls: return from projexui.qt import QtCore, QtGui, wrapVariant, uic from projexui.widgets.xloggersplashscreen import XLoggerSplashScreen glbls['QtCore'] = QtCore glbls['QtGui'] = QtGui glbls['wrapVariant'] = wrapVariant glbls['uic'] = uic glbls['XLoggerSplashScreen'] = XLoggerSplashScreen
python
def import_qt(glbls): """ Delayed qt loader. """ if 'QtCore' in glbls: return from projexui.qt import QtCore, QtGui, wrapVariant, uic from projexui.widgets.xloggersplashscreen import XLoggerSplashScreen glbls['QtCore'] = QtCore glbls['QtGui'] = QtGui glbls['wrapVariant'] = wrapVariant glbls['uic'] = uic glbls['XLoggerSplashScreen'] = XLoggerSplashScreen
[ "def", "import_qt", "(", "glbls", ")", ":", "if", "'QtCore'", "in", "glbls", ":", "return", "from", "projexui", ".", "qt", "import", "QtCore", ",", "QtGui", ",", "wrapVariant", ",", "uic", "from", "projexui", ".", "widgets", ".", "xloggersplashscreen", "import", "XLoggerSplashScreen", "glbls", "[", "'QtCore'", "]", "=", "QtCore", "glbls", "[", "'QtGui'", "]", "=", "QtGui", "glbls", "[", "'wrapVariant'", "]", "=", "wrapVariant", "glbls", "[", "'uic'", "]", "=", "uic", "glbls", "[", "'XLoggerSplashScreen'", "]", "=", "XLoggerSplashScreen" ]
Delayed qt loader.
[ "Delayed", "qt", "loader", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xcommands.py#L255-L267
train
johnnoone/aioconsul
aioconsul/encoders/__init__.py
encode_value
def encode_value(value, flags=None, base64=False): """Mostly used by payloads """ if flags: # still a no-operation logger.debug("Flag %s encoding not implemented yet" % flags) if not isinstance(value, bytes): raise ValueError("value must be bytes") return b64encode(value) if base64 else value
python
def encode_value(value, flags=None, base64=False): """Mostly used by payloads """ if flags: # still a no-operation logger.debug("Flag %s encoding not implemented yet" % flags) if not isinstance(value, bytes): raise ValueError("value must be bytes") return b64encode(value) if base64 else value
[ "def", "encode_value", "(", "value", ",", "flags", "=", "None", ",", "base64", "=", "False", ")", ":", "if", "flags", ":", "# still a no-operation", "logger", ".", "debug", "(", "\"Flag %s encoding not implemented yet\"", "%", "flags", ")", "if", "not", "isinstance", "(", "value", ",", "bytes", ")", ":", "raise", "ValueError", "(", "\"value must be bytes\"", ")", "return", "b64encode", "(", "value", ")", "if", "base64", "else", "value" ]
Mostly used by payloads
[ "Mostly", "used", "by", "payloads" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/encoders/__init__.py#L8-L16
train
bitesofcode/projexui
projexui/widgets/xstackedwidget.py
XStackedWidget._finishAnimation
def _finishAnimation(self): """ Cleans up post-animation. """ self.setCurrentIndex(self._nextIndex) self.widget(self._lastIndex).hide() self.widget(self._lastIndex).move(self._lastPoint) self._active = False if not self.signalsBlocked(): self.animationFinished.emit()
python
def _finishAnimation(self): """ Cleans up post-animation. """ self.setCurrentIndex(self._nextIndex) self.widget(self._lastIndex).hide() self.widget(self._lastIndex).move(self._lastPoint) self._active = False if not self.signalsBlocked(): self.animationFinished.emit()
[ "def", "_finishAnimation", "(", "self", ")", ":", "self", ".", "setCurrentIndex", "(", "self", ".", "_nextIndex", ")", "self", ".", "widget", "(", "self", ".", "_lastIndex", ")", ".", "hide", "(", ")", "self", ".", "widget", "(", "self", ".", "_lastIndex", ")", ".", "move", "(", "self", ".", "_lastPoint", ")", "self", ".", "_active", "=", "False", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "animationFinished", ".", "emit", "(", ")" ]
Cleans up post-animation.
[ "Cleans", "up", "post", "-", "animation", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xstackedwidget.py#L66-L76
train
bitesofcode/projexui
projexui/widgets/xstackedwidget.py
XStackedWidget.clear
def clear(self): """ Clears out the widgets from this stack. """ for i in range(self.count() - 1, -1, -1): w = self.widget(i) if w: self.removeWidget(w) w.close() w.deleteLater()
python
def clear(self): """ Clears out the widgets from this stack. """ for i in range(self.count() - 1, -1, -1): w = self.widget(i) if w: self.removeWidget(w) w.close() w.deleteLater()
[ "def", "clear", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "w", "=", "self", ".", "widget", "(", "i", ")", "if", "w", ":", "self", ".", "removeWidget", "(", "w", ")", "w", ".", "close", "(", ")", "w", ".", "deleteLater", "(", ")" ]
Clears out the widgets from this stack.
[ "Clears", "out", "the", "widgets", "from", "this", "stack", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xstackedwidget.py#L86-L95
train
talkincode/txradius
txradius/openvpn/statusdb.py
list
def list(conf): """ OpenVPN status list method """ try: config = init_config(conf) conn = get_conn(config.get('DEFAULT','statusdb')) cur = conn.cursor() sqlstr = '''select * from client_status order by ctime desc ''' cur.execute(sqlstr) result = cur.fetchall() conn.commit() conn.close() for r in result: print r except Exception, e: traceback.print_exc()
python
def list(conf): """ OpenVPN status list method """ try: config = init_config(conf) conn = get_conn(config.get('DEFAULT','statusdb')) cur = conn.cursor() sqlstr = '''select * from client_status order by ctime desc ''' cur.execute(sqlstr) result = cur.fetchall() conn.commit() conn.close() for r in result: print r except Exception, e: traceback.print_exc()
[ "def", "list", "(", "conf", ")", ":", "try", ":", "config", "=", "init_config", "(", "conf", ")", "conn", "=", "get_conn", "(", "config", ".", "get", "(", "'DEFAULT'", ",", "'statusdb'", ")", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sqlstr", "=", "'''select * from client_status order by ctime desc '''", "cur", ".", "execute", "(", "sqlstr", ")", "result", "=", "cur", ".", "fetchall", "(", ")", "conn", ".", "commit", "(", ")", "conn", ".", "close", "(", ")", "for", "r", "in", "result", ":", "print", "r", "except", "Exception", ",", "e", ":", "traceback", ".", "print_exc", "(", ")" ]
OpenVPN status list method
[ "OpenVPN", "status", "list", "method" ]
b86fdbc9be41183680b82b07d3a8e8ea10926e01
https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/statusdb.py#L130-L145
train
talkincode/txradius
txradius/openvpn/statusdb.py
cli
def cli(conf): """ OpenVPN status initdb method """ try: config = init_config(conf) debug = config.getboolean('DEFAULT', 'debug') conn = get_conn(config.get('DEFAULT','statusdb')) cur = conn.cursor() sqlstr = '''create table client_status (session_id text PRIMARY KEY, username text, userip text, realip text, realport int,ctime int, inbytes int, outbytes int, acct_interval int, session_timeout int, uptime int) ''' try: cur.execute('drop table client_status') except: pass cur.execute(sqlstr) print 'flush client status database' conn.commit() conn.close() except: traceback.print_exc()
python
def cli(conf): """ OpenVPN status initdb method """ try: config = init_config(conf) debug = config.getboolean('DEFAULT', 'debug') conn = get_conn(config.get('DEFAULT','statusdb')) cur = conn.cursor() sqlstr = '''create table client_status (session_id text PRIMARY KEY, username text, userip text, realip text, realport int,ctime int, inbytes int, outbytes int, acct_interval int, session_timeout int, uptime int) ''' try: cur.execute('drop table client_status') except: pass cur.execute(sqlstr) print 'flush client status database' conn.commit() conn.close() except: traceback.print_exc()
[ "def", "cli", "(", "conf", ")", ":", "try", ":", "config", "=", "init_config", "(", "conf", ")", "debug", "=", "config", ".", "getboolean", "(", "'DEFAULT'", ",", "'debug'", ")", "conn", "=", "get_conn", "(", "config", ".", "get", "(", "'DEFAULT'", ",", "'statusdb'", ")", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sqlstr", "=", "'''create table client_status\n (session_id text PRIMARY KEY, username text, userip text, \n realip text, realport int,ctime int,\n inbytes int, outbytes int, \n acct_interval int, session_timeout int, uptime int)\n '''", "try", ":", "cur", ".", "execute", "(", "'drop table client_status'", ")", "except", ":", "pass", "cur", ".", "execute", "(", "sqlstr", ")", "print", "'flush client status database'", "conn", ".", "commit", "(", ")", "conn", ".", "close", "(", ")", "except", ":", "traceback", ".", "print_exc", "(", ")" ]
OpenVPN status initdb method
[ "OpenVPN", "status", "initdb", "method" ]
b86fdbc9be41183680b82b07d3a8e8ea10926e01
https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/statusdb.py#L150-L173
train
johnnoone/aioconsul
aioconsul/client/services_endpoint.py
ServicesEndpoint.register
async def register(self, service): """Registers a new local service. Returns: bool: ``True`` on success The register endpoint is used to add a new service, with an optional health check, to the local agent. The request body must look like:: { "ID": "redis1", "Name": "redis", "Tags": [ "master", "v1" ], "Address": "127.0.0.1", "Port": 8000, "EnableTagOverride": False, "Check": { "DeregisterCriticalServiceAfter": timedelta(seconds=90), "Script": "/usr/local/bin/check_redis.py", "HTTP": "http://localhost:5000/health", "Interval": timedelta(seconds=10), "TTL": timedelta(seconds=15) } } The **Name** field is mandatory. If an **ID** is not provided, it is set to **Name**. You cannot have duplicate **ID** entries per agent, so it may be necessary to provide an **ID** in the case of a collision. **Tags**, **Address**, **Port**, **Check** and **EnableTagOverride** are optional. If **Address** is not provided or left empty, then the agent's address will be used as the address for the service during DNS queries. When querying for services using HTTP endpoints such as service health or service catalog and encountering an empty **Address** field for a service, use the **Address** field of the agent node associated with that instance of the service, which is returned alongside the service information. If **Check** is provided, only one of **Script**, **HTTP**, **TCP** or **TTL** should be specified. **Script** and **HTTP** also require **Interval**. The created check will be named "service:<ServiceId>". Checks that are associated with a service may also contain an optional **DeregisterCriticalServiceAfter** field, which is a timeout in the same format as **Interval** and **TTL**. If a check is in the critical state for more than this configured value, then its associated service (and all of its associated checks) will automatically be deregistered. The minimum timeout is 1 minute, and the process that reaps critical services runs every 30 seconds, so it may take slightly longer than the configured timeout to trigger the deregistration. This should generally be configured with a timeout that's much, much longer than any expected recoverable outage for the given service. **EnableTagOverride** can optionally be specified to disable the anti-entropy feature for this service's tags. If **EnableTagOverride** is set to ``True`` then external agents can update this service in the catalog and modify the tags. Subsequent local sync operations by this agent will ignore the updated tags. For instance, if an external agent modified both the tags and the port for this service and **EnableTagOverride** was set to true then after the next sync cycle the service's port would revert to the original value but the tags would maintain the updated value. As a counter example, if an external agent modified both the tags and port for this service and **EnableTagOverride** was set to false then after the next sync cycle the service's port and the tags would revert to the original value and all modifications would be lost. It's important to note that this applies only to the locally registered service. If you have multiple nodes all registering the same service their **EnableTagOverride** configuration and all other service configuration items are independent of one another. Updating the tags for the service registered on one node is independent of the same service (by name) registered on another node. If **EnableTagOverride** is not specified the default value is ``False``. """ response = await self._api.put("/v1/agent/service/register", data=service) return response.status == 200
python
async def register(self, service): """Registers a new local service. Returns: bool: ``True`` on success The register endpoint is used to add a new service, with an optional health check, to the local agent. The request body must look like:: { "ID": "redis1", "Name": "redis", "Tags": [ "master", "v1" ], "Address": "127.0.0.1", "Port": 8000, "EnableTagOverride": False, "Check": { "DeregisterCriticalServiceAfter": timedelta(seconds=90), "Script": "/usr/local/bin/check_redis.py", "HTTP": "http://localhost:5000/health", "Interval": timedelta(seconds=10), "TTL": timedelta(seconds=15) } } The **Name** field is mandatory. If an **ID** is not provided, it is set to **Name**. You cannot have duplicate **ID** entries per agent, so it may be necessary to provide an **ID** in the case of a collision. **Tags**, **Address**, **Port**, **Check** and **EnableTagOverride** are optional. If **Address** is not provided or left empty, then the agent's address will be used as the address for the service during DNS queries. When querying for services using HTTP endpoints such as service health or service catalog and encountering an empty **Address** field for a service, use the **Address** field of the agent node associated with that instance of the service, which is returned alongside the service information. If **Check** is provided, only one of **Script**, **HTTP**, **TCP** or **TTL** should be specified. **Script** and **HTTP** also require **Interval**. The created check will be named "service:<ServiceId>". Checks that are associated with a service may also contain an optional **DeregisterCriticalServiceAfter** field, which is a timeout in the same format as **Interval** and **TTL**. If a check is in the critical state for more than this configured value, then its associated service (and all of its associated checks) will automatically be deregistered. The minimum timeout is 1 minute, and the process that reaps critical services runs every 30 seconds, so it may take slightly longer than the configured timeout to trigger the deregistration. This should generally be configured with a timeout that's much, much longer than any expected recoverable outage for the given service. **EnableTagOverride** can optionally be specified to disable the anti-entropy feature for this service's tags. If **EnableTagOverride** is set to ``True`` then external agents can update this service in the catalog and modify the tags. Subsequent local sync operations by this agent will ignore the updated tags. For instance, if an external agent modified both the tags and the port for this service and **EnableTagOverride** was set to true then after the next sync cycle the service's port would revert to the original value but the tags would maintain the updated value. As a counter example, if an external agent modified both the tags and port for this service and **EnableTagOverride** was set to false then after the next sync cycle the service's port and the tags would revert to the original value and all modifications would be lost. It's important to note that this applies only to the locally registered service. If you have multiple nodes all registering the same service their **EnableTagOverride** configuration and all other service configuration items are independent of one another. Updating the tags for the service registered on one node is independent of the same service (by name) registered on another node. If **EnableTagOverride** is not specified the default value is ``False``. """ response = await self._api.put("/v1/agent/service/register", data=service) return response.status == 200
[ "async", "def", "register", "(", "self", ",", "service", ")", ":", "response", "=", "await", "self", ".", "_api", ".", "put", "(", "\"/v1/agent/service/register\"", ",", "data", "=", "service", ")", "return", "response", ".", "status", "==", "200" ]
Registers a new local service. Returns: bool: ``True`` on success The register endpoint is used to add a new service, with an optional health check, to the local agent. The request body must look like:: { "ID": "redis1", "Name": "redis", "Tags": [ "master", "v1" ], "Address": "127.0.0.1", "Port": 8000, "EnableTagOverride": False, "Check": { "DeregisterCriticalServiceAfter": timedelta(seconds=90), "Script": "/usr/local/bin/check_redis.py", "HTTP": "http://localhost:5000/health", "Interval": timedelta(seconds=10), "TTL": timedelta(seconds=15) } } The **Name** field is mandatory. If an **ID** is not provided, it is set to **Name**. You cannot have duplicate **ID** entries per agent, so it may be necessary to provide an **ID** in the case of a collision. **Tags**, **Address**, **Port**, **Check** and **EnableTagOverride** are optional. If **Address** is not provided or left empty, then the agent's address will be used as the address for the service during DNS queries. When querying for services using HTTP endpoints such as service health or service catalog and encountering an empty **Address** field for a service, use the **Address** field of the agent node associated with that instance of the service, which is returned alongside the service information. If **Check** is provided, only one of **Script**, **HTTP**, **TCP** or **TTL** should be specified. **Script** and **HTTP** also require **Interval**. The created check will be named "service:<ServiceId>". Checks that are associated with a service may also contain an optional **DeregisterCriticalServiceAfter** field, which is a timeout in the same format as **Interval** and **TTL**. If a check is in the critical state for more than this configured value, then its associated service (and all of its associated checks) will automatically be deregistered. The minimum timeout is 1 minute, and the process that reaps critical services runs every 30 seconds, so it may take slightly longer than the configured timeout to trigger the deregistration. This should generally be configured with a timeout that's much, much longer than any expected recoverable outage for the given service. **EnableTagOverride** can optionally be specified to disable the anti-entropy feature for this service's tags. If **EnableTagOverride** is set to ``True`` then external agents can update this service in the catalog and modify the tags. Subsequent local sync operations by this agent will ignore the updated tags. For instance, if an external agent modified both the tags and the port for this service and **EnableTagOverride** was set to true then after the next sync cycle the service's port would revert to the original value but the tags would maintain the updated value. As a counter example, if an external agent modified both the tags and port for this service and **EnableTagOverride** was set to false then after the next sync cycle the service's port and the tags would revert to the original value and all modifications would be lost. It's important to note that this applies only to the locally registered service. If you have multiple nodes all registering the same service their **EnableTagOverride** configuration and all other service configuration items are independent of one another. Updating the tags for the service registered on one node is independent of the same service (by name) registered on another node. If **EnableTagOverride** is not specified the default value is ``False``.
[ "Registers", "a", "new", "local", "service", "." ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/services_endpoint.py#L31-L116
train
johnnoone/aioconsul
aioconsul/client/services_endpoint.py
ServicesEndpoint.deregister
async def deregister(self, service): """Deregisters a local service Parameters: service (ObjectID): Service ID Returns: bool: ``True`` on success The deregister endpoint is used to remove a service from the local agent. The agent will take care of deregistering the service with the Catalog. If there is an associated check, that is also deregistered. """ service_id = extract_attr(service, keys=["ServiceID", "ID"]) response = await self._api.get( "/v1/agent/service/deregister", service_id) return response.status == 200
python
async def deregister(self, service): """Deregisters a local service Parameters: service (ObjectID): Service ID Returns: bool: ``True`` on success The deregister endpoint is used to remove a service from the local agent. The agent will take care of deregistering the service with the Catalog. If there is an associated check, that is also deregistered. """ service_id = extract_attr(service, keys=["ServiceID", "ID"]) response = await self._api.get( "/v1/agent/service/deregister", service_id) return response.status == 200
[ "async", "def", "deregister", "(", "self", ",", "service", ")", ":", "service_id", "=", "extract_attr", "(", "service", ",", "keys", "=", "[", "\"ServiceID\"", ",", "\"ID\"", "]", ")", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/agent/service/deregister\"", ",", "service_id", ")", "return", "response", ".", "status", "==", "200" ]
Deregisters a local service Parameters: service (ObjectID): Service ID Returns: bool: ``True`` on success The deregister endpoint is used to remove a service from the local agent. The agent will take care of deregistering the service with the Catalog. If there is an associated check, that is also deregistered.
[ "Deregisters", "a", "local", "service" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/services_endpoint.py#L118-L133
train
johnnoone/aioconsul
aioconsul/client/services_endpoint.py
ServicesEndpoint.disable
async def disable(self, service, *, reason=None): """Enters maintenance mode for service Parameters: service (ObjectID): Service ID reason (str): Text string explaining the reason for placing the service into maintenance mode. Returns: bool: ``True`` on success Places a given service into "maintenance mode". During maintenance mode, the service will be marked as unavailable and will not be present in DNS or API queries. Maintenance mode is persistent and will be automatically restored on agent restart. """ return await self.maintenance(service, False, reason=reason)
python
async def disable(self, service, *, reason=None): """Enters maintenance mode for service Parameters: service (ObjectID): Service ID reason (str): Text string explaining the reason for placing the service into maintenance mode. Returns: bool: ``True`` on success Places a given service into "maintenance mode". During maintenance mode, the service will be marked as unavailable and will not be present in DNS or API queries. Maintenance mode is persistent and will be automatically restored on agent restart. """ return await self.maintenance(service, False, reason=reason)
[ "async", "def", "disable", "(", "self", ",", "service", ",", "*", ",", "reason", "=", "None", ")", ":", "return", "await", "self", ".", "maintenance", "(", "service", ",", "False", ",", "reason", "=", "reason", ")" ]
Enters maintenance mode for service Parameters: service (ObjectID): Service ID reason (str): Text string explaining the reason for placing the service into maintenance mode. Returns: bool: ``True`` on success Places a given service into "maintenance mode". During maintenance mode, the service will be marked as unavailable and will not be present in DNS or API queries. Maintenance mode is persistent and will be automatically restored on agent restart.
[ "Enters", "maintenance", "mode", "for", "service" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/services_endpoint.py#L135-L152
train
johnnoone/aioconsul
aioconsul/client/services_endpoint.py
ServicesEndpoint.enable
async def enable(self, service, *, reason=None): """Resumes normal operation for service Parameters: service (ObjectID): Service ID reason (str): Text string explaining the reason for placing the service into normal mode. Returns: bool: ``True`` on success """ return await self.maintenance(service, False, reason=reason)
python
async def enable(self, service, *, reason=None): """Resumes normal operation for service Parameters: service (ObjectID): Service ID reason (str): Text string explaining the reason for placing the service into normal mode. Returns: bool: ``True`` on success """ return await self.maintenance(service, False, reason=reason)
[ "async", "def", "enable", "(", "self", ",", "service", ",", "*", ",", "reason", "=", "None", ")", ":", "return", "await", "self", ".", "maintenance", "(", "service", ",", "False", ",", "reason", "=", "reason", ")" ]
Resumes normal operation for service Parameters: service (ObjectID): Service ID reason (str): Text string explaining the reason for placing the service into normal mode. Returns: bool: ``True`` on success
[ "Resumes", "normal", "operation", "for", "service" ]
02f7a529d7dc2e49bed942111067aa5faf320e90
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/services_endpoint.py#L154-L164
train
talkincode/txradius
txradius/mschap/mppe.py
mppe_chap2_gen_keys
def mppe_chap2_gen_keys(password, nt_response): """ 3.3. Generating 128-bit Session Keys When used in conjunction with MS-CHAP-2 authentication, the initial MPPE session keys are derived from the peer's Windows NT password. The first step is to obfuscate the peer's password using NtPasswordHash() function as described in [8]. NtPasswordHash(Password, PasswordHash) The first 16 octets of the result are then hashed again using the MD4 algorithm. PasswordHashHash = md4(PasswordHash) The first 16 octets of this second hash are used together with the NT-Response field from the MS-CHAP-2 Response packet [8] as the basis for the master session key: GetMasterKey(PasswordHashHash, NtResponse, MasterKey) Once the master key has been generated, it is used to derive two 128-bit master session keys, one for sending and one for receiving: GetAsymmetricStartKey(MasterKey, MasterSendKey, 16, TRUE, TRUE) GetAsymmetricStartKey(MasterKey, MasterReceiveKey, 16, FALSE, TRUE) The master session keys are never used to encrypt or decrypt data; they are only used in the derivation of transient session keys. The initial transient session keys are obtained by calling the function GetNewKeyFromSHA() (described in [3]): GetNewKeyFromSHA(MasterSendKey, MasterSendKey, 16, SendSessionKey) GetNewKeyFromSHA(MasterReceiveKey, MasterReceiveKey, 16, ReceiveSessionKey) Finally, the RC4 tables are initialized using the new session keys: rc4_key(SendRC4key, 16, SendSessionKey) rc4_key(ReceiveRC4key, 16, ReceiveSessionKey) """ password_hash = mschap.nt_password_hash(password) password_hash_hash = mschap.hash_nt_password_hash(password_hash) master_key = get_master_key(password_hash_hash, nt_response) master_send_key = get_asymetric_start_key(master_key, 16, True, True) master_recv_key = get_asymetric_start_key(master_key, 16, False, True) return master_send_key, master_recv_key
python
def mppe_chap2_gen_keys(password, nt_response): """ 3.3. Generating 128-bit Session Keys When used in conjunction with MS-CHAP-2 authentication, the initial MPPE session keys are derived from the peer's Windows NT password. The first step is to obfuscate the peer's password using NtPasswordHash() function as described in [8]. NtPasswordHash(Password, PasswordHash) The first 16 octets of the result are then hashed again using the MD4 algorithm. PasswordHashHash = md4(PasswordHash) The first 16 octets of this second hash are used together with the NT-Response field from the MS-CHAP-2 Response packet [8] as the basis for the master session key: GetMasterKey(PasswordHashHash, NtResponse, MasterKey) Once the master key has been generated, it is used to derive two 128-bit master session keys, one for sending and one for receiving: GetAsymmetricStartKey(MasterKey, MasterSendKey, 16, TRUE, TRUE) GetAsymmetricStartKey(MasterKey, MasterReceiveKey, 16, FALSE, TRUE) The master session keys are never used to encrypt or decrypt data; they are only used in the derivation of transient session keys. The initial transient session keys are obtained by calling the function GetNewKeyFromSHA() (described in [3]): GetNewKeyFromSHA(MasterSendKey, MasterSendKey, 16, SendSessionKey) GetNewKeyFromSHA(MasterReceiveKey, MasterReceiveKey, 16, ReceiveSessionKey) Finally, the RC4 tables are initialized using the new session keys: rc4_key(SendRC4key, 16, SendSessionKey) rc4_key(ReceiveRC4key, 16, ReceiveSessionKey) """ password_hash = mschap.nt_password_hash(password) password_hash_hash = mschap.hash_nt_password_hash(password_hash) master_key = get_master_key(password_hash_hash, nt_response) master_send_key = get_asymetric_start_key(master_key, 16, True, True) master_recv_key = get_asymetric_start_key(master_key, 16, False, True) return master_send_key, master_recv_key
[ "def", "mppe_chap2_gen_keys", "(", "password", ",", "nt_response", ")", ":", "password_hash", "=", "mschap", ".", "nt_password_hash", "(", "password", ")", "password_hash_hash", "=", "mschap", ".", "hash_nt_password_hash", "(", "password_hash", ")", "master_key", "=", "get_master_key", "(", "password_hash_hash", ",", "nt_response", ")", "master_send_key", "=", "get_asymetric_start_key", "(", "master_key", ",", "16", ",", "True", ",", "True", ")", "master_recv_key", "=", "get_asymetric_start_key", "(", "master_key", ",", "16", ",", "False", ",", "True", ")", "return", "master_send_key", ",", "master_recv_key" ]
3.3. Generating 128-bit Session Keys When used in conjunction with MS-CHAP-2 authentication, the initial MPPE session keys are derived from the peer's Windows NT password. The first step is to obfuscate the peer's password using NtPasswordHash() function as described in [8]. NtPasswordHash(Password, PasswordHash) The first 16 octets of the result are then hashed again using the MD4 algorithm. PasswordHashHash = md4(PasswordHash) The first 16 octets of this second hash are used together with the NT-Response field from the MS-CHAP-2 Response packet [8] as the basis for the master session key: GetMasterKey(PasswordHashHash, NtResponse, MasterKey) Once the master key has been generated, it is used to derive two 128-bit master session keys, one for sending and one for receiving: GetAsymmetricStartKey(MasterKey, MasterSendKey, 16, TRUE, TRUE) GetAsymmetricStartKey(MasterKey, MasterReceiveKey, 16, FALSE, TRUE) The master session keys are never used to encrypt or decrypt data; they are only used in the derivation of transient session keys. The initial transient session keys are obtained by calling the function GetNewKeyFromSHA() (described in [3]): GetNewKeyFromSHA(MasterSendKey, MasterSendKey, 16, SendSessionKey) GetNewKeyFromSHA(MasterReceiveKey, MasterReceiveKey, 16, ReceiveSessionKey) Finally, the RC4 tables are initialized using the new session keys: rc4_key(SendRC4key, 16, SendSessionKey) rc4_key(ReceiveRC4key, 16, ReceiveSessionKey)
[ "3", ".", "3", ".", "Generating", "128", "-", "bit", "Session", "Keys" ]
b86fdbc9be41183680b82b07d3a8e8ea10926e01
https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/mschap/mppe.py#L45-L93
train
whiteclover/dbpy
db/_db.py
DB.query
def query(self, sql, args=None, many=None, as_dict=False): """The connection raw sql query, when select table, show table to fetch records, it is compatible the dbi execute method. :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else dbi execute(sql, args), the args keep the original rules, it shuld be tuple or list of list :param many int: when set, the query method will return genarate an iterate :param as_dict bool: when is true, the type of row will be dict, otherwise is tuple """ con = self.pool.pop() c = None try: c = con.cursor(as_dict) LOGGER.debug("Query sql: " + sql + " args:" + str(args)) c.execute(sql, args) if many and many > 0: return self._yield(con, c, many) else: return c.fetchall() except Exception as e: LOGGER.error("Error Qeury on %s", str(e)) raise DBError(e.args[0], e.args[1]) finally: many or (c and c.close()) many or (con and self.pool.push(con))
python
def query(self, sql, args=None, many=None, as_dict=False): """The connection raw sql query, when select table, show table to fetch records, it is compatible the dbi execute method. :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else dbi execute(sql, args), the args keep the original rules, it shuld be tuple or list of list :param many int: when set, the query method will return genarate an iterate :param as_dict bool: when is true, the type of row will be dict, otherwise is tuple """ con = self.pool.pop() c = None try: c = con.cursor(as_dict) LOGGER.debug("Query sql: " + sql + " args:" + str(args)) c.execute(sql, args) if many and many > 0: return self._yield(con, c, many) else: return c.fetchall() except Exception as e: LOGGER.error("Error Qeury on %s", str(e)) raise DBError(e.args[0], e.args[1]) finally: many or (c and c.close()) many or (con and self.pool.push(con))
[ "def", "query", "(", "self", ",", "sql", ",", "args", "=", "None", ",", "many", "=", "None", ",", "as_dict", "=", "False", ")", ":", "con", "=", "self", ".", "pool", ".", "pop", "(", ")", "c", "=", "None", "try", ":", "c", "=", "con", ".", "cursor", "(", "as_dict", ")", "LOGGER", ".", "debug", "(", "\"Query sql: \"", "+", "sql", "+", "\" args:\"", "+", "str", "(", "args", ")", ")", "c", ".", "execute", "(", "sql", ",", "args", ")", "if", "many", "and", "many", ">", "0", ":", "return", "self", ".", "_yield", "(", "con", ",", "c", ",", "many", ")", "else", ":", "return", "c", ".", "fetchall", "(", ")", "except", "Exception", "as", "e", ":", "LOGGER", ".", "error", "(", "\"Error Qeury on %s\"", ",", "str", "(", "e", ")", ")", "raise", "DBError", "(", "e", ".", "args", "[", "0", "]", ",", "e", ".", "args", "[", "1", "]", ")", "finally", ":", "many", "or", "(", "c", "and", "c", ".", "close", "(", ")", ")", "many", "or", "(", "con", "and", "self", ".", "pool", ".", "push", "(", "con", ")", ")" ]
The connection raw sql query, when select table, show table to fetch records, it is compatible the dbi execute method. :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else dbi execute(sql, args), the args keep the original rules, it shuld be tuple or list of list :param many int: when set, the query method will return genarate an iterate :param as_dict bool: when is true, the type of row will be dict, otherwise is tuple
[ "The", "connection", "raw", "sql", "query", "when", "select", "table", "show", "table", "to", "fetch", "records", "it", "is", "compatible", "the", "dbi", "execute", "method", "." ]
3d9ce85f55cfb39cced22081e525f79581b26b3a
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/_db.py#L85-L112
train
whiteclover/dbpy
db/_db.py
DB.connection_class
def connection_class(self, adapter): """Get connection class by adapter""" if self.adapters.get(adapter): return self.adapters[adapter] try: class_prefix = getattr( __import__('db.' + adapter, globals(), locals(), ['__class_prefix__']), '__class_prefix__') driver = self._import_class('db.' + adapter + '.connection.' + class_prefix + 'Connection') except ImportError: raise DBError("Must install adapter `%s` or doesn't support" % (adapter)) self.adapters[adapter] = driver return driver
python
def connection_class(self, adapter): """Get connection class by adapter""" if self.adapters.get(adapter): return self.adapters[adapter] try: class_prefix = getattr( __import__('db.' + adapter, globals(), locals(), ['__class_prefix__']), '__class_prefix__') driver = self._import_class('db.' + adapter + '.connection.' + class_prefix + 'Connection') except ImportError: raise DBError("Must install adapter `%s` or doesn't support" % (adapter)) self.adapters[adapter] = driver return driver
[ "def", "connection_class", "(", "self", ",", "adapter", ")", ":", "if", "self", ".", "adapters", ".", "get", "(", "adapter", ")", ":", "return", "self", ".", "adapters", "[", "adapter", "]", "try", ":", "class_prefix", "=", "getattr", "(", "__import__", "(", "'db.'", "+", "adapter", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "[", "'__class_prefix__'", "]", ")", ",", "'__class_prefix__'", ")", "driver", "=", "self", ".", "_import_class", "(", "'db.'", "+", "adapter", "+", "'.connection.'", "+", "class_prefix", "+", "'Connection'", ")", "except", "ImportError", ":", "raise", "DBError", "(", "\"Must install adapter `%s` or doesn't support\"", "%", "(", "adapter", ")", ")", "self", ".", "adapters", "[", "adapter", "]", "=", "driver", "return", "driver" ]
Get connection class by adapter
[ "Get", "connection", "class", "by", "adapter" ]
3d9ce85f55cfb39cced22081e525f79581b26b3a
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/_db.py#L164-L179
train
whiteclover/dbpy
db/_db.py
DB.dialect_class
def dialect_class(self, adapter): """Get dialect sql class by adapter""" if self.dialects.get(adapter): return self.dialects[adapter] try: class_prefix = getattr( __import__('db.' + adapter, globals(), locals(), ['__class_prefix__']), '__class_prefix__') driver = self._import_class('db.' + adapter + '.dialect.' + class_prefix + 'Dialect') except ImportError: raise DBError("Must install adapter `%s` or doesn't support" % (adapter)) self.dialects[adapter] = driver return driver
python
def dialect_class(self, adapter): """Get dialect sql class by adapter""" if self.dialects.get(adapter): return self.dialects[adapter] try: class_prefix = getattr( __import__('db.' + adapter, globals(), locals(), ['__class_prefix__']), '__class_prefix__') driver = self._import_class('db.' + adapter + '.dialect.' + class_prefix + 'Dialect') except ImportError: raise DBError("Must install adapter `%s` or doesn't support" % (adapter)) self.dialects[adapter] = driver return driver
[ "def", "dialect_class", "(", "self", ",", "adapter", ")", ":", "if", "self", ".", "dialects", ".", "get", "(", "adapter", ")", ":", "return", "self", ".", "dialects", "[", "adapter", "]", "try", ":", "class_prefix", "=", "getattr", "(", "__import__", "(", "'db.'", "+", "adapter", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "[", "'__class_prefix__'", "]", ")", ",", "'__class_prefix__'", ")", "driver", "=", "self", ".", "_import_class", "(", "'db.'", "+", "adapter", "+", "'.dialect.'", "+", "class_prefix", "+", "'Dialect'", ")", "except", "ImportError", ":", "raise", "DBError", "(", "\"Must install adapter `%s` or doesn't support\"", "%", "(", "adapter", ")", ")", "self", ".", "dialects", "[", "adapter", "]", "=", "driver", "return", "driver" ]
Get dialect sql class by adapter
[ "Get", "dialect", "sql", "class", "by", "adapter" ]
3d9ce85f55cfb39cced22081e525f79581b26b3a
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/_db.py#L181-L196
train
whiteclover/dbpy
db/_db.py
DB._import_class
def _import_class(self, module2cls): """Import class by module dot split string""" d = module2cls.rfind(".") classname = module2cls[d + 1: len(module2cls)] m = __import__(module2cls[0:d], globals(), locals(), [classname]) return getattr(m, classname)
python
def _import_class(self, module2cls): """Import class by module dot split string""" d = module2cls.rfind(".") classname = module2cls[d + 1: len(module2cls)] m = __import__(module2cls[0:d], globals(), locals(), [classname]) return getattr(m, classname)
[ "def", "_import_class", "(", "self", ",", "module2cls", ")", ":", "d", "=", "module2cls", ".", "rfind", "(", "\".\"", ")", "classname", "=", "module2cls", "[", "d", "+", "1", ":", "len", "(", "module2cls", ")", "]", "m", "=", "__import__", "(", "module2cls", "[", "0", ":", "d", "]", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "[", "classname", "]", ")", "return", "getattr", "(", "m", ",", "classname", ")" ]
Import class by module dot split string
[ "Import", "class", "by", "module", "dot", "split", "string" ]
3d9ce85f55cfb39cced22081e525f79581b26b3a
https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/_db.py#L198-L203
train
bitesofcode/projexui
projexui/widgets/xchartwidget/xcharttrackeritem.py
XChartTrackerItem.rebuild
def rebuild( self, gridRect ): """ Rebuilds the tracker item. """ scene = self.scene() if ( not scene ): return self.setVisible(gridRect.contains(self.pos())) self.setZValue(100) path = QPainterPath() path.moveTo(0, 0) path.lineTo(0, gridRect.height()) tip = '' tip_point = None self._ellipses = [] items = scene.collidingItems(self) self._basePath = QPainterPath(path) for item in items: item_path = item.path() found = None for y in range(int(gridRect.top()), int(gridRect.bottom())): point = QPointF(self.pos().x(), y) if ( item_path.contains(point) ): found = QPointF(0, y - self.pos().y()) break if ( found ): path.addEllipse(found, 6, 6) self._ellipses.append(found) # update the value information value = scene.valueAt(self.mapToScene(found)) tip_point = self.mapToScene(found) hruler = scene.horizontalRuler() vruler = scene.verticalRuler() x_value = hruler.formatValue(value[0]) y_value = vruler.formatValue(value[1]) tip = '<b>x:</b> %s<br/><b>y:</b> %s' % (x_value, y_value) self.setPath(path) self.setVisible(True) # show the popup widget if ( tip ): anchor = XPopupWidget.Anchor.RightCenter widget = self.scene().chartWidget() tip_point = widget.mapToGlobal(widget.mapFromScene(tip_point)) XPopupWidget.showToolTip(tip, anchor = anchor, parent = widget, point = tip_point, foreground = QColor('blue'), background = QColor(148, 148, 255))
python
def rebuild( self, gridRect ): """ Rebuilds the tracker item. """ scene = self.scene() if ( not scene ): return self.setVisible(gridRect.contains(self.pos())) self.setZValue(100) path = QPainterPath() path.moveTo(0, 0) path.lineTo(0, gridRect.height()) tip = '' tip_point = None self._ellipses = [] items = scene.collidingItems(self) self._basePath = QPainterPath(path) for item in items: item_path = item.path() found = None for y in range(int(gridRect.top()), int(gridRect.bottom())): point = QPointF(self.pos().x(), y) if ( item_path.contains(point) ): found = QPointF(0, y - self.pos().y()) break if ( found ): path.addEllipse(found, 6, 6) self._ellipses.append(found) # update the value information value = scene.valueAt(self.mapToScene(found)) tip_point = self.mapToScene(found) hruler = scene.horizontalRuler() vruler = scene.verticalRuler() x_value = hruler.formatValue(value[0]) y_value = vruler.formatValue(value[1]) tip = '<b>x:</b> %s<br/><b>y:</b> %s' % (x_value, y_value) self.setPath(path) self.setVisible(True) # show the popup widget if ( tip ): anchor = XPopupWidget.Anchor.RightCenter widget = self.scene().chartWidget() tip_point = widget.mapToGlobal(widget.mapFromScene(tip_point)) XPopupWidget.showToolTip(tip, anchor = anchor, parent = widget, point = tip_point, foreground = QColor('blue'), background = QColor(148, 148, 255))
[ "def", "rebuild", "(", "self", ",", "gridRect", ")", ":", "scene", "=", "self", ".", "scene", "(", ")", "if", "(", "not", "scene", ")", ":", "return", "self", ".", "setVisible", "(", "gridRect", ".", "contains", "(", "self", ".", "pos", "(", ")", ")", ")", "self", ".", "setZValue", "(", "100", ")", "path", "=", "QPainterPath", "(", ")", "path", ".", "moveTo", "(", "0", ",", "0", ")", "path", ".", "lineTo", "(", "0", ",", "gridRect", ".", "height", "(", ")", ")", "tip", "=", "''", "tip_point", "=", "None", "self", ".", "_ellipses", "=", "[", "]", "items", "=", "scene", ".", "collidingItems", "(", "self", ")", "self", ".", "_basePath", "=", "QPainterPath", "(", "path", ")", "for", "item", "in", "items", ":", "item_path", "=", "item", ".", "path", "(", ")", "found", "=", "None", "for", "y", "in", "range", "(", "int", "(", "gridRect", ".", "top", "(", ")", ")", ",", "int", "(", "gridRect", ".", "bottom", "(", ")", ")", ")", ":", "point", "=", "QPointF", "(", "self", ".", "pos", "(", ")", ".", "x", "(", ")", ",", "y", ")", "if", "(", "item_path", ".", "contains", "(", "point", ")", ")", ":", "found", "=", "QPointF", "(", "0", ",", "y", "-", "self", ".", "pos", "(", ")", ".", "y", "(", ")", ")", "break", "if", "(", "found", ")", ":", "path", ".", "addEllipse", "(", "found", ",", "6", ",", "6", ")", "self", ".", "_ellipses", ".", "append", "(", "found", ")", "# update the value information\r", "value", "=", "scene", ".", "valueAt", "(", "self", ".", "mapToScene", "(", "found", ")", ")", "tip_point", "=", "self", ".", "mapToScene", "(", "found", ")", "hruler", "=", "scene", ".", "horizontalRuler", "(", ")", "vruler", "=", "scene", ".", "verticalRuler", "(", ")", "x_value", "=", "hruler", ".", "formatValue", "(", "value", "[", "0", "]", ")", "y_value", "=", "vruler", ".", "formatValue", "(", "value", "[", "1", "]", ")", "tip", "=", "'<b>x:</b> %s<br/><b>y:</b> %s'", "%", "(", "x_value", ",", "y_value", ")", "self", ".", "setPath", "(", "path", ")", "self", ".", "setVisible", "(", "True", ")", "# show the popup widget\r", "if", "(", "tip", ")", ":", "anchor", "=", "XPopupWidget", ".", "Anchor", ".", "RightCenter", "widget", "=", "self", ".", "scene", "(", ")", ".", "chartWidget", "(", ")", "tip_point", "=", "widget", ".", "mapToGlobal", "(", "widget", ".", "mapFromScene", "(", "tip_point", ")", ")", "XPopupWidget", ".", "showToolTip", "(", "tip", ",", "anchor", "=", "anchor", ",", "parent", "=", "widget", ",", "point", "=", "tip_point", ",", "foreground", "=", "QColor", "(", "'blue'", ")", ",", "background", "=", "QColor", "(", "148", ",", "148", ",", "255", ")", ")" ]
Rebuilds the tracker item.
[ "Rebuilds", "the", "tracker", "item", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xcharttrackeritem.py#L65-L124
train
ReneNulschDE/mercedesmejsonpy
mercedesmejsonpy/oauth.py
MercedesMeClientCredentials.get_access_token
def get_access_token(self): """ If a valid access token is in memory, returns it Else feches a new token and returns it """ if self.token_info and not self.is_token_expired(self.token_info): return self.token_info['access_token'] token_info = self._request_access_token() token_info = self._add_custom_values_to_token_info(token_info) self.token_info = token_info return self.token_info['access_token']
python
def get_access_token(self): """ If a valid access token is in memory, returns it Else feches a new token and returns it """ if self.token_info and not self.is_token_expired(self.token_info): return self.token_info['access_token'] token_info = self._request_access_token() token_info = self._add_custom_values_to_token_info(token_info) self.token_info = token_info return self.token_info['access_token']
[ "def", "get_access_token", "(", "self", ")", ":", "if", "self", ".", "token_info", "and", "not", "self", ".", "is_token_expired", "(", "self", ".", "token_info", ")", ":", "return", "self", ".", "token_info", "[", "'access_token'", "]", "token_info", "=", "self", ".", "_request_access_token", "(", ")", "token_info", "=", "self", ".", "_add_custom_values_to_token_info", "(", "token_info", ")", "self", ".", "token_info", "=", "token_info", "return", "self", ".", "token_info", "[", "'access_token'", "]" ]
If a valid access token is in memory, returns it Else feches a new token and returns it
[ "If", "a", "valid", "access", "token", "is", "in", "memory", "returns", "it", "Else", "feches", "a", "new", "token", "and", "returns", "it" ]
0618a0b49d6bb46599d11a8f66dc8d08d112ceec
https://github.com/ReneNulschDE/mercedesmejsonpy/blob/0618a0b49d6bb46599d11a8f66dc8d08d112ceec/mercedesmejsonpy/oauth.py#L56-L67
train
ReneNulschDE/mercedesmejsonpy
mercedesmejsonpy/oauth.py
MercedesMeClientCredentials._request_access_token
def _request_access_token(self): """Gets client credentials access token """ payload = {'grant_type': 'authorization_code', 'code': code, 'redirect_uri': self.redirect_uri} headers = _make_authorization_headers(self.client_id, self.client_secret) response = requests.post(self.OAUTH_TOKEN_URL, data=payload, headers=headers, verify=LOGIN_VERIFY_SSL_CERT) if response.status_code is not 200: raise MercedesMeAuthError(response.reason) token_info = response.json() return token_info
python
def _request_access_token(self): """Gets client credentials access token """ payload = {'grant_type': 'authorization_code', 'code': code, 'redirect_uri': self.redirect_uri} headers = _make_authorization_headers(self.client_id, self.client_secret) response = requests.post(self.OAUTH_TOKEN_URL, data=payload, headers=headers, verify=LOGIN_VERIFY_SSL_CERT) if response.status_code is not 200: raise MercedesMeAuthError(response.reason) token_info = response.json() return token_info
[ "def", "_request_access_token", "(", "self", ")", ":", "payload", "=", "{", "'grant_type'", ":", "'authorization_code'", ",", "'code'", ":", "code", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", "}", "headers", "=", "_make_authorization_headers", "(", "self", ".", "client_id", ",", "self", ".", "client_secret", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "OAUTH_TOKEN_URL", ",", "data", "=", "payload", ",", "headers", "=", "headers", ",", "verify", "=", "LOGIN_VERIFY_SSL_CERT", ")", "if", "response", ".", "status_code", "is", "not", "200", ":", "raise", "MercedesMeAuthError", "(", "response", ".", "reason", ")", "token_info", "=", "response", ".", "json", "(", ")", "return", "token_info" ]
Gets client credentials access token
[ "Gets", "client", "credentials", "access", "token" ]
0618a0b49d6bb46599d11a8f66dc8d08d112ceec
https://github.com/ReneNulschDE/mercedesmejsonpy/blob/0618a0b49d6bb46599d11a8f66dc8d08d112ceec/mercedesmejsonpy/oauth.py#L69-L85
train
ReneNulschDE/mercedesmejsonpy
mercedesmejsonpy/oauth.py
MercedesMeOAuth.get_cached_token
def get_cached_token(self): ''' Gets a cached auth token ''' token_info = None if self.cache_path: try: f = open(self.cache_path) token_info_string = f.read() f.close() token_info = json.loads(token_info_string) if self.is_token_expired(token_info): token_info = self.refresh_access_token(token_info['refresh_token']) except IOError: pass return token_info
python
def get_cached_token(self): ''' Gets a cached auth token ''' token_info = None if self.cache_path: try: f = open(self.cache_path) token_info_string = f.read() f.close() token_info = json.loads(token_info_string) if self.is_token_expired(token_info): token_info = self.refresh_access_token(token_info['refresh_token']) except IOError: pass return token_info
[ "def", "get_cached_token", "(", "self", ")", ":", "token_info", "=", "None", "if", "self", ".", "cache_path", ":", "try", ":", "f", "=", "open", "(", "self", ".", "cache_path", ")", "token_info_string", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "token_info", "=", "json", ".", "loads", "(", "token_info_string", ")", "if", "self", ".", "is_token_expired", "(", "token_info", ")", ":", "token_info", "=", "self", ".", "refresh_access_token", "(", "token_info", "[", "'refresh_token'", "]", ")", "except", "IOError", ":", "pass", "return", "token_info" ]
Gets a cached auth token
[ "Gets", "a", "cached", "auth", "token" ]
0618a0b49d6bb46599d11a8f66dc8d08d112ceec
https://github.com/ReneNulschDE/mercedesmejsonpy/blob/0618a0b49d6bb46599d11a8f66dc8d08d112ceec/mercedesmejsonpy/oauth.py#L126-L142
train
ReneNulschDE/mercedesmejsonpy
mercedesmejsonpy/oauth.py
MercedesMeOAuth.get_authorize_url
def get_authorize_url(self, state=None): """ Gets the URL to use to authorize this app """ payload = {'client_id': self.client_id, 'response_type': 'code', 'redirect_uri': self.redirect_uri, 'scope': self.scope} urlparams = urllib.parse.urlencode(payload) return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams)
python
def get_authorize_url(self, state=None): """ Gets the URL to use to authorize this app """ payload = {'client_id': self.client_id, 'response_type': 'code', 'redirect_uri': self.redirect_uri, 'scope': self.scope} urlparams = urllib.parse.urlencode(payload) return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams)
[ "def", "get_authorize_url", "(", "self", ",", "state", "=", "None", ")", ":", "payload", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'response_type'", ":", "'code'", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "'scope'", ":", "self", ".", "scope", "}", "urlparams", "=", "urllib", ".", "parse", ".", "urlencode", "(", "payload", ")", "return", "\"%s?%s\"", "%", "(", "self", ".", "OAUTH_AUTHORIZE_URL", ",", "urlparams", ")" ]
Gets the URL to use to authorize this app
[ "Gets", "the", "URL", "to", "use", "to", "authorize", "this", "app" ]
0618a0b49d6bb46599d11a8f66dc8d08d112ceec
https://github.com/ReneNulschDE/mercedesmejsonpy/blob/0618a0b49d6bb46599d11a8f66dc8d08d112ceec/mercedesmejsonpy/oauth.py#L156-L166
train
ReneNulschDE/mercedesmejsonpy
mercedesmejsonpy/oauth.py
MercedesMeOAuth.get_access_token
def get_access_token(self, code): """ Gets the access token for the app given the code Parameters: - code - the response code """ payload = {'redirect_uri': self.redirect_uri, 'code': code, 'grant_type': 'authorization_code'} headers = self._make_authorization_headers() response = requests.post(self.OAUTH_TOKEN_URL, data=payload, headers=headers, verify=LOGIN_VERIFY_SSL_CERT) if response.status_code is not 200: raise MercedesMeAuthError(response.reason) token_info = response.json() token_info = self._add_custom_values_to_token_info(token_info) self._save_token_info(token_info) return token_info
python
def get_access_token(self, code): """ Gets the access token for the app given the code Parameters: - code - the response code """ payload = {'redirect_uri': self.redirect_uri, 'code': code, 'grant_type': 'authorization_code'} headers = self._make_authorization_headers() response = requests.post(self.OAUTH_TOKEN_URL, data=payload, headers=headers, verify=LOGIN_VERIFY_SSL_CERT) if response.status_code is not 200: raise MercedesMeAuthError(response.reason) token_info = response.json() token_info = self._add_custom_values_to_token_info(token_info) self._save_token_info(token_info) return token_info
[ "def", "get_access_token", "(", "self", ",", "code", ")", ":", "payload", "=", "{", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "'code'", ":", "code", ",", "'grant_type'", ":", "'authorization_code'", "}", "headers", "=", "self", ".", "_make_authorization_headers", "(", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "OAUTH_TOKEN_URL", ",", "data", "=", "payload", ",", "headers", "=", "headers", ",", "verify", "=", "LOGIN_VERIFY_SSL_CERT", ")", "if", "response", ".", "status_code", "is", "not", "200", ":", "raise", "MercedesMeAuthError", "(", "response", ".", "reason", ")", "token_info", "=", "response", ".", "json", "(", ")", "token_info", "=", "self", ".", "_add_custom_values_to_token_info", "(", "token_info", ")", "self", ".", "_save_token_info", "(", "token_info", ")", "return", "token_info" ]
Gets the access token for the app given the code Parameters: - code - the response code
[ "Gets", "the", "access", "token", "for", "the", "app", "given", "the", "code" ]
0618a0b49d6bb46599d11a8f66dc8d08d112ceec
https://github.com/ReneNulschDE/mercedesmejsonpy/blob/0618a0b49d6bb46599d11a8f66dc8d08d112ceec/mercedesmejsonpy/oauth.py#L183-L203
train
ReneNulschDE/mercedesmejsonpy
mercedesmejsonpy/oauth.py
MercedesMeOAuth._add_custom_values_to_token_info
def _add_custom_values_to_token_info(self, token_info): ''' Store some values that aren't directly provided by a Web API response. ''' token_info['expires_at'] = int(time.time()) + token_info['expires_in'] token_info['scope'] = self.scope return token_info
python
def _add_custom_values_to_token_info(self, token_info): ''' Store some values that aren't directly provided by a Web API response. ''' token_info['expires_at'] = int(time.time()) + token_info['expires_in'] token_info['scope'] = self.scope return token_info
[ "def", "_add_custom_values_to_token_info", "(", "self", ",", "token_info", ")", ":", "token_info", "[", "'expires_at'", "]", "=", "int", "(", "time", ".", "time", "(", ")", ")", "+", "token_info", "[", "'expires_in'", "]", "token_info", "[", "'scope'", "]", "=", "self", ".", "scope", "return", "token_info" ]
Store some values that aren't directly provided by a Web API response.
[ "Store", "some", "values", "that", "aren", "t", "directly", "provided", "by", "a", "Web", "API", "response", "." ]
0618a0b49d6bb46599d11a8f66dc8d08d112ceec
https://github.com/ReneNulschDE/mercedesmejsonpy/blob/0618a0b49d6bb46599d11a8f66dc8d08d112ceec/mercedesmejsonpy/oauth.py#L226-L233
train
bitesofcode/projexui
projexui/widgets/xsplitbutton.py
XSplitButton.clear
def clear(self, autoBuild=True): """ Clears the actions for this widget. """ for action in self._actionGroup.actions(): self._actionGroup.removeAction(action) action = QAction('', self) action.setObjectName('place_holder') self._actionGroup.addAction(action) if autoBuild: self.rebuild()
python
def clear(self, autoBuild=True): """ Clears the actions for this widget. """ for action in self._actionGroup.actions(): self._actionGroup.removeAction(action) action = QAction('', self) action.setObjectName('place_holder') self._actionGroup.addAction(action) if autoBuild: self.rebuild()
[ "def", "clear", "(", "self", ",", "autoBuild", "=", "True", ")", ":", "for", "action", "in", "self", ".", "_actionGroup", ".", "actions", "(", ")", ":", "self", ".", "_actionGroup", ".", "removeAction", "(", "action", ")", "action", "=", "QAction", "(", "''", ",", "self", ")", "action", ".", "setObjectName", "(", "'place_holder'", ")", "self", ".", "_actionGroup", ".", "addAction", "(", "action", ")", "if", "autoBuild", ":", "self", ".", "rebuild", "(", ")" ]
Clears the actions for this widget.
[ "Clears", "the", "actions", "for", "this", "widget", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsplitbutton.py#L187-L198
train
bitesofcode/projexui
projexui/widgets/xfilepathedit.py
XFilepathEdit.copyFilepath
def copyFilepath( self ): """ Copies the current filepath contents to the current clipboard. """ clipboard = QApplication.instance().clipboard() clipboard.setText(self.filepath()) clipboard.setText(self.filepath(), clipboard.Selection)
python
def copyFilepath( self ): """ Copies the current filepath contents to the current clipboard. """ clipboard = QApplication.instance().clipboard() clipboard.setText(self.filepath()) clipboard.setText(self.filepath(), clipboard.Selection)
[ "def", "copyFilepath", "(", "self", ")", ":", "clipboard", "=", "QApplication", ".", "instance", "(", ")", ".", "clipboard", "(", ")", "clipboard", ".", "setText", "(", "self", ".", "filepath", "(", ")", ")", "clipboard", ".", "setText", "(", "self", ".", "filepath", "(", ")", ",", "clipboard", ".", "Selection", ")" ]
Copies the current filepath contents to the current clipboard.
[ "Copies", "the", "current", "filepath", "contents", "to", "the", "current", "clipboard", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xfilepathedit.py#L136-L142
train
bitesofcode/projexui
projexui/widgets/xfilepathedit.py
XFilepathEdit.pickFilepath
def pickFilepath( self ): """ Prompts the user to select a filepath from the system based on the \ current filepath mode. """ mode = self.filepathMode() filepath = '' filepaths = [] curr_dir = nativestring(self._filepathEdit.text()) if ( not curr_dir ): curr_dir = QDir.currentPath() if mode == XFilepathEdit.Mode.SaveFile: filepath = QFileDialog.getSaveFileName( self, self.windowTitle(), curr_dir, self.filepathTypes() ) elif mode == XFilepathEdit.Mode.OpenFile: filepath = QFileDialog.getOpenFileName( self, self.windowTitle(), curr_dir, self.filepathTypes() ) elif mode == XFilepathEdit.Mode.OpenFiles: filepaths = QFileDialog.getOpenFileNames( self, self.windowTitle(), curr_dir, self.filepathTypes() ) else: filepath = QFileDialog.getExistingDirectory( self, self.windowTitle(), curr_dir ) if filepath: if type(filepath) == tuple: filepath = filepath[0] self.setFilepath(nativestring(filepath)) elif filepaths: self.setFilepaths(map(str, filepaths))
python
def pickFilepath( self ): """ Prompts the user to select a filepath from the system based on the \ current filepath mode. """ mode = self.filepathMode() filepath = '' filepaths = [] curr_dir = nativestring(self._filepathEdit.text()) if ( not curr_dir ): curr_dir = QDir.currentPath() if mode == XFilepathEdit.Mode.SaveFile: filepath = QFileDialog.getSaveFileName( self, self.windowTitle(), curr_dir, self.filepathTypes() ) elif mode == XFilepathEdit.Mode.OpenFile: filepath = QFileDialog.getOpenFileName( self, self.windowTitle(), curr_dir, self.filepathTypes() ) elif mode == XFilepathEdit.Mode.OpenFiles: filepaths = QFileDialog.getOpenFileNames( self, self.windowTitle(), curr_dir, self.filepathTypes() ) else: filepath = QFileDialog.getExistingDirectory( self, self.windowTitle(), curr_dir ) if filepath: if type(filepath) == tuple: filepath = filepath[0] self.setFilepath(nativestring(filepath)) elif filepaths: self.setFilepaths(map(str, filepaths))
[ "def", "pickFilepath", "(", "self", ")", ":", "mode", "=", "self", ".", "filepathMode", "(", ")", "filepath", "=", "''", "filepaths", "=", "[", "]", "curr_dir", "=", "nativestring", "(", "self", ".", "_filepathEdit", ".", "text", "(", ")", ")", "if", "(", "not", "curr_dir", ")", ":", "curr_dir", "=", "QDir", ".", "currentPath", "(", ")", "if", "mode", "==", "XFilepathEdit", ".", "Mode", ".", "SaveFile", ":", "filepath", "=", "QFileDialog", ".", "getSaveFileName", "(", "self", ",", "self", ".", "windowTitle", "(", ")", ",", "curr_dir", ",", "self", ".", "filepathTypes", "(", ")", ")", "elif", "mode", "==", "XFilepathEdit", ".", "Mode", ".", "OpenFile", ":", "filepath", "=", "QFileDialog", ".", "getOpenFileName", "(", "self", ",", "self", ".", "windowTitle", "(", ")", ",", "curr_dir", ",", "self", ".", "filepathTypes", "(", ")", ")", "elif", "mode", "==", "XFilepathEdit", ".", "Mode", ".", "OpenFiles", ":", "filepaths", "=", "QFileDialog", ".", "getOpenFileNames", "(", "self", ",", "self", ".", "windowTitle", "(", ")", ",", "curr_dir", ",", "self", ".", "filepathTypes", "(", ")", ")", "else", ":", "filepath", "=", "QFileDialog", ".", "getExistingDirectory", "(", "self", ",", "self", ".", "windowTitle", "(", ")", ",", "curr_dir", ")", "if", "filepath", ":", "if", "type", "(", "filepath", ")", "==", "tuple", ":", "filepath", "=", "filepath", "[", "0", "]", "self", ".", "setFilepath", "(", "nativestring", "(", "filepath", ")", ")", "elif", "filepaths", ":", "self", ".", "setFilepaths", "(", "map", "(", "str", ",", "filepaths", ")", ")" ]
Prompts the user to select a filepath from the system based on the \ current filepath mode.
[ "Prompts", "the", "user", "to", "select", "a", "filepath", "from", "the", "system", "based", "on", "the", "\\", "current", "filepath", "mode", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xfilepathedit.py#L322-L363
train
bitesofcode/projexui
projexui/widgets/xfilepathedit.py
XFilepathEdit.showMenu
def showMenu( self, pos ): """ Popups a menu for this widget. """ menu = QMenu(self) menu.setAttribute(Qt.WA_DeleteOnClose) menu.addAction('Clear').triggered.connect(self.clearFilepath) menu.addSeparator() menu.addAction('Copy Filepath').triggered.connect(self.copyFilepath) menu.exec_(self.mapToGlobal(pos))
python
def showMenu( self, pos ): """ Popups a menu for this widget. """ menu = QMenu(self) menu.setAttribute(Qt.WA_DeleteOnClose) menu.addAction('Clear').triggered.connect(self.clearFilepath) menu.addSeparator() menu.addAction('Copy Filepath').triggered.connect(self.copyFilepath) menu.exec_(self.mapToGlobal(pos))
[ "def", "showMenu", "(", "self", ",", "pos", ")", ":", "menu", "=", "QMenu", "(", "self", ")", "menu", ".", "setAttribute", "(", "Qt", ".", "WA_DeleteOnClose", ")", "menu", ".", "addAction", "(", "'Clear'", ")", ".", "triggered", ".", "connect", "(", "self", ".", "clearFilepath", ")", "menu", ".", "addSeparator", "(", ")", "menu", ".", "addAction", "(", "'Copy Filepath'", ")", ".", "triggered", ".", "connect", "(", "self", ".", "copyFilepath", ")", "menu", ".", "exec_", "(", "self", ".", "mapToGlobal", "(", "pos", ")", ")" ]
Popups a menu for this widget.
[ "Popups", "a", "menu", "for", "this", "widget", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xfilepathedit.py#L519-L529
train
bitesofcode/projexui
projexui/widgets/xfilepathedit.py
XFilepathEdit.validateFilepath
def validateFilepath( self ): """ Alters the color scheme based on the validation settings. """ if ( not self.isValidated() ): return valid = self.isValid() if ( not valid ): fg = self.invalidForeground() bg = self.invalidBackground() else: fg = self.validForeground() bg = self.validBackground() palette = self.palette() palette.setColor(palette.Base, bg) palette.setColor(palette.Text, fg) self._filepathEdit.setPalette(palette)
python
def validateFilepath( self ): """ Alters the color scheme based on the validation settings. """ if ( not self.isValidated() ): return valid = self.isValid() if ( not valid ): fg = self.invalidForeground() bg = self.invalidBackground() else: fg = self.validForeground() bg = self.validBackground() palette = self.palette() palette.setColor(palette.Base, bg) palette.setColor(palette.Text, fg) self._filepathEdit.setPalette(palette)
[ "def", "validateFilepath", "(", "self", ")", ":", "if", "(", "not", "self", ".", "isValidated", "(", ")", ")", ":", "return", "valid", "=", "self", ".", "isValid", "(", ")", "if", "(", "not", "valid", ")", ":", "fg", "=", "self", ".", "invalidForeground", "(", ")", "bg", "=", "self", ".", "invalidBackground", "(", ")", "else", ":", "fg", "=", "self", ".", "validForeground", "(", ")", "bg", "=", "self", ".", "validBackground", "(", ")", "palette", "=", "self", ".", "palette", "(", ")", "palette", ".", "setColor", "(", "palette", ".", "Base", ",", "bg", ")", "palette", ".", "setColor", "(", "palette", ".", "Text", ",", "fg", ")", "self", ".", "_filepathEdit", ".", "setPalette", "(", "palette", ")" ]
Alters the color scheme based on the validation settings.
[ "Alters", "the", "color", "scheme", "based", "on", "the", "validation", "settings", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xfilepathedit.py#L547-L565
train
bitesofcode/projexui
projexui/widgets/xorbrecordsetedit/xorbrecordsetedit.py
XOrbRecordSetEdit.clear
def clear( self ): """ Clears the information for this edit. """ self.uiQueryTXT.setText('') self.uiQueryTREE.clear() self.uiGroupingTXT.setText('') self.uiSortingTXT.setText('')
python
def clear( self ): """ Clears the information for this edit. """ self.uiQueryTXT.setText('') self.uiQueryTREE.clear() self.uiGroupingTXT.setText('') self.uiSortingTXT.setText('')
[ "def", "clear", "(", "self", ")", ":", "self", ".", "uiQueryTXT", ".", "setText", "(", "''", ")", "self", ".", "uiQueryTREE", ".", "clear", "(", ")", "self", ".", "uiGroupingTXT", ".", "setText", "(", "''", ")", "self", ".", "uiSortingTXT", ".", "setText", "(", "''", ")" ]
Clears the information for this edit.
[ "Clears", "the", "information", "for", "this", "edit", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordsetedit/xorbrecordsetedit.py#L216-L223
train
bitesofcode/projexui
projexui/widgets/xorbrecordwidget.py
XOrbRecordWidget.save
def save(self): """ Saves the changes from the ui to this widgets record instance. """ record = self.record() if not record: logger.warning('No record has been defined for %s.' % self) return False if not self.signalsBlocked(): self.aboutToSaveRecord.emit(record) self.aboutToSave.emit() values = self.saveValues() # ignore columns that are the same (fixes bugs in encrypted columns) check = values.copy() for column_name, value in check.items(): try: equals = value == record.recordValue(column_name) except UnicodeWarning: equals = False if equals: check.pop(column_name) # check to see if nothing has changed if not check and record.isRecord(): if not self.signalsBlocked(): self.recordSaved.emit(record) self.saved.emit() self._saveSignalBlocked = False else: self._saveSignalBlocked = True if self.autoCommitOnSave(): status, result = record.commit() if status == 'errored': if 'db_error' in result: msg = nativestring(result['db_error']) else: msg = 'An unknown database error has occurred.' QMessageBox.information(self, 'Commit Error', msg) return False return True # validate the modified values success, msg = record.validateValues(check) if ( not success ): QMessageBox.information(None, 'Could Not Save', msg) return False record.setRecordValues(**values) success, msg = record.validateRecord() if not success: QMessageBox.information(None, 'Could Not Save', msg) return False if ( self.autoCommitOnSave() ): result = record.commit() if 'errored' in result: QMessageBox.information(None, 'Could Not Save', msg) return False if ( not self.signalsBlocked() ): self.recordSaved.emit(record) self.saved.emit() self._saveSignalBlocked = False else: self._saveSignalBlocked = True return True
python
def save(self): """ Saves the changes from the ui to this widgets record instance. """ record = self.record() if not record: logger.warning('No record has been defined for %s.' % self) return False if not self.signalsBlocked(): self.aboutToSaveRecord.emit(record) self.aboutToSave.emit() values = self.saveValues() # ignore columns that are the same (fixes bugs in encrypted columns) check = values.copy() for column_name, value in check.items(): try: equals = value == record.recordValue(column_name) except UnicodeWarning: equals = False if equals: check.pop(column_name) # check to see if nothing has changed if not check and record.isRecord(): if not self.signalsBlocked(): self.recordSaved.emit(record) self.saved.emit() self._saveSignalBlocked = False else: self._saveSignalBlocked = True if self.autoCommitOnSave(): status, result = record.commit() if status == 'errored': if 'db_error' in result: msg = nativestring(result['db_error']) else: msg = 'An unknown database error has occurred.' QMessageBox.information(self, 'Commit Error', msg) return False return True # validate the modified values success, msg = record.validateValues(check) if ( not success ): QMessageBox.information(None, 'Could Not Save', msg) return False record.setRecordValues(**values) success, msg = record.validateRecord() if not success: QMessageBox.information(None, 'Could Not Save', msg) return False if ( self.autoCommitOnSave() ): result = record.commit() if 'errored' in result: QMessageBox.information(None, 'Could Not Save', msg) return False if ( not self.signalsBlocked() ): self.recordSaved.emit(record) self.saved.emit() self._saveSignalBlocked = False else: self._saveSignalBlocked = True return True
[ "def", "save", "(", "self", ")", ":", "record", "=", "self", ".", "record", "(", ")", "if", "not", "record", ":", "logger", ".", "warning", "(", "'No record has been defined for %s.'", "%", "self", ")", "return", "False", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "aboutToSaveRecord", ".", "emit", "(", "record", ")", "self", ".", "aboutToSave", ".", "emit", "(", ")", "values", "=", "self", ".", "saveValues", "(", ")", "# ignore columns that are the same (fixes bugs in encrypted columns)\r", "check", "=", "values", ".", "copy", "(", ")", "for", "column_name", ",", "value", "in", "check", ".", "items", "(", ")", ":", "try", ":", "equals", "=", "value", "==", "record", ".", "recordValue", "(", "column_name", ")", "except", "UnicodeWarning", ":", "equals", "=", "False", "if", "equals", ":", "check", ".", "pop", "(", "column_name", ")", "# check to see if nothing has changed\r", "if", "not", "check", "and", "record", ".", "isRecord", "(", ")", ":", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "recordSaved", ".", "emit", "(", "record", ")", "self", ".", "saved", ".", "emit", "(", ")", "self", ".", "_saveSignalBlocked", "=", "False", "else", ":", "self", ".", "_saveSignalBlocked", "=", "True", "if", "self", ".", "autoCommitOnSave", "(", ")", ":", "status", ",", "result", "=", "record", ".", "commit", "(", ")", "if", "status", "==", "'errored'", ":", "if", "'db_error'", "in", "result", ":", "msg", "=", "nativestring", "(", "result", "[", "'db_error'", "]", ")", "else", ":", "msg", "=", "'An unknown database error has occurred.'", "QMessageBox", ".", "information", "(", "self", ",", "'Commit Error'", ",", "msg", ")", "return", "False", "return", "True", "# validate the modified values\r", "success", ",", "msg", "=", "record", ".", "validateValues", "(", "check", ")", "if", "(", "not", "success", ")", ":", "QMessageBox", ".", "information", "(", "None", ",", "'Could Not Save'", ",", "msg", ")", "return", "False", "record", ".", "setRecordValues", "(", "*", "*", "values", ")", "success", ",", "msg", "=", "record", ".", "validateRecord", "(", ")", "if", "not", "success", ":", "QMessageBox", ".", "information", "(", "None", ",", "'Could Not Save'", ",", "msg", ")", "return", "False", "if", "(", "self", ".", "autoCommitOnSave", "(", ")", ")", ":", "result", "=", "record", ".", "commit", "(", ")", "if", "'errored'", "in", "result", ":", "QMessageBox", ".", "information", "(", "None", ",", "'Could Not Save'", ",", "msg", ")", "return", "False", "if", "(", "not", "self", ".", "signalsBlocked", "(", ")", ")", ":", "self", ".", "recordSaved", ".", "emit", "(", "record", ")", "self", ".", "saved", ".", "emit", "(", ")", "self", ".", "_saveSignalBlocked", "=", "False", "else", ":", "self", ".", "_saveSignalBlocked", "=", "True", "return", "True" ]
Saves the changes from the ui to this widgets record instance.
[ "Saves", "the", "changes", "from", "the", "ui", "to", "this", "widgets", "record", "instance", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordwidget.py#L201-L275
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/namespace.py
Namespace.add_dynamic_element
def add_dynamic_element(self, name, description): """Adds a dynamic namespace element to the end of the Namespace. A dynamic namespace element is defined by an element that contains a non-static data relative to the metric being collected. For instance, when collecting metrics for a given virtual machine the namespace element that contains the virtual-machine-id would be dynamic. This is modeled by the a NamespaceElement when its `name` attribute contains the value 'virtual-machine-id'. In this example the `value` attribute would be set to the ID of the virtual machine when the metric is collected. Args: value (:py:class:`snap_plugin.v1.namespace_element.NamespaceElement`): namespace element Returns: :py:class:`snap_plugin.v1.namespace.Namespace` """ self._pb.add(Name=name, Description=description, Value="*") return self
python
def add_dynamic_element(self, name, description): """Adds a dynamic namespace element to the end of the Namespace. A dynamic namespace element is defined by an element that contains a non-static data relative to the metric being collected. For instance, when collecting metrics for a given virtual machine the namespace element that contains the virtual-machine-id would be dynamic. This is modeled by the a NamespaceElement when its `name` attribute contains the value 'virtual-machine-id'. In this example the `value` attribute would be set to the ID of the virtual machine when the metric is collected. Args: value (:py:class:`snap_plugin.v1.namespace_element.NamespaceElement`): namespace element Returns: :py:class:`snap_plugin.v1.namespace.Namespace` """ self._pb.add(Name=name, Description=description, Value="*") return self
[ "def", "add_dynamic_element", "(", "self", ",", "name", ",", "description", ")", ":", "self", ".", "_pb", ".", "add", "(", "Name", "=", "name", ",", "Description", "=", "description", ",", "Value", "=", "\"*\"", ")", "return", "self" ]
Adds a dynamic namespace element to the end of the Namespace. A dynamic namespace element is defined by an element that contains a non-static data relative to the metric being collected. For instance, when collecting metrics for a given virtual machine the namespace element that contains the virtual-machine-id would be dynamic. This is modeled by the a NamespaceElement when its `name` attribute contains the value 'virtual-machine-id'. In this example the `value` attribute would be set to the ID of the virtual machine when the metric is collected. Args: value (:py:class:`snap_plugin.v1.namespace_element.NamespaceElement`): namespace element Returns: :py:class:`snap_plugin.v1.namespace.Namespace`
[ "Adds", "a", "dynamic", "namespace", "element", "to", "the", "end", "of", "the", "Namespace", "." ]
8da5d00ac5f9d2b48a7239563ac7788209891ca4
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/namespace.py#L71-L90
train
SkullTech/webdriver-start
wdstart/webdriver.py
Chrome
def Chrome(headless=False, user_agent=None, profile_path=None): """ Starts and returns a Selenium webdriver object for Chrome. Starts a Selenium webdriver according to the given specifications, and returns the corresponding `selenium.webdriver.Chrome` object. Parameters ---------- headless : bool Whether to start the browser in headless mode. user_agent : str, optional The `user_agent` string the webdriver should use. profile_path : str, optional The path of the browser profile (only for Firefox and Chrome). Returns ------- `selenium.webdriver.Chrome` Selenium webdriver, according to the given specifications. """ chromedriver = drivers.ChromeDriver(headless, user_agent, profile_path) return chromedriver.driver
python
def Chrome(headless=False, user_agent=None, profile_path=None): """ Starts and returns a Selenium webdriver object for Chrome. Starts a Selenium webdriver according to the given specifications, and returns the corresponding `selenium.webdriver.Chrome` object. Parameters ---------- headless : bool Whether to start the browser in headless mode. user_agent : str, optional The `user_agent` string the webdriver should use. profile_path : str, optional The path of the browser profile (only for Firefox and Chrome). Returns ------- `selenium.webdriver.Chrome` Selenium webdriver, according to the given specifications. """ chromedriver = drivers.ChromeDriver(headless, user_agent, profile_path) return chromedriver.driver
[ "def", "Chrome", "(", "headless", "=", "False", ",", "user_agent", "=", "None", ",", "profile_path", "=", "None", ")", ":", "chromedriver", "=", "drivers", ".", "ChromeDriver", "(", "headless", ",", "user_agent", ",", "profile_path", ")", "return", "chromedriver", ".", "driver" ]
Starts and returns a Selenium webdriver object for Chrome. Starts a Selenium webdriver according to the given specifications, and returns the corresponding `selenium.webdriver.Chrome` object. Parameters ---------- headless : bool Whether to start the browser in headless mode. user_agent : str, optional The `user_agent` string the webdriver should use. profile_path : str, optional The path of the browser profile (only for Firefox and Chrome). Returns ------- `selenium.webdriver.Chrome` Selenium webdriver, according to the given specifications.
[ "Starts", "and", "returns", "a", "Selenium", "webdriver", "object", "for", "Chrome", "." ]
26285fd84c4deaf8906828e0ec0758a650b7ba49
https://github.com/SkullTech/webdriver-start/blob/26285fd84c4deaf8906828e0ec0758a650b7ba49/wdstart/webdriver.py#L9-L31
train
SkullTech/webdriver-start
wdstart/webdriver.py
Firefox
def Firefox(headless=False, user_agent=None, profile_path=None): """ Starts and returns a Selenium webdriver object for Firefox. Starts a Selenium webdriver according to the given specifications, and returns the corresponding `selenium.webdriver.Chrome` object. Parameters ---------- headless : bool Whether to start the browser in headless mode. user_agent : str, optional The `user_agent` string the webdriver should use. profile_path : str, optional The path of the browser profile (only for Firefox and Chrome). Returns ------- `selenium.webdriver.Firefox` Selenium webdriver, according to the given specifications. """ firefoxdriver = drivers.FirefoxDriver(headless, user_agent, profile_path) return firefoxdriver.driver
python
def Firefox(headless=False, user_agent=None, profile_path=None): """ Starts and returns a Selenium webdriver object for Firefox. Starts a Selenium webdriver according to the given specifications, and returns the corresponding `selenium.webdriver.Chrome` object. Parameters ---------- headless : bool Whether to start the browser in headless mode. user_agent : str, optional The `user_agent` string the webdriver should use. profile_path : str, optional The path of the browser profile (only for Firefox and Chrome). Returns ------- `selenium.webdriver.Firefox` Selenium webdriver, according to the given specifications. """ firefoxdriver = drivers.FirefoxDriver(headless, user_agent, profile_path) return firefoxdriver.driver
[ "def", "Firefox", "(", "headless", "=", "False", ",", "user_agent", "=", "None", ",", "profile_path", "=", "None", ")", ":", "firefoxdriver", "=", "drivers", ".", "FirefoxDriver", "(", "headless", ",", "user_agent", ",", "profile_path", ")", "return", "firefoxdriver", ".", "driver" ]
Starts and returns a Selenium webdriver object for Firefox. Starts a Selenium webdriver according to the given specifications, and returns the corresponding `selenium.webdriver.Chrome` object. Parameters ---------- headless : bool Whether to start the browser in headless mode. user_agent : str, optional The `user_agent` string the webdriver should use. profile_path : str, optional The path of the browser profile (only for Firefox and Chrome). Returns ------- `selenium.webdriver.Firefox` Selenium webdriver, according to the given specifications.
[ "Starts", "and", "returns", "a", "Selenium", "webdriver", "object", "for", "Firefox", "." ]
26285fd84c4deaf8906828e0ec0758a650b7ba49
https://github.com/SkullTech/webdriver-start/blob/26285fd84c4deaf8906828e0ec0758a650b7ba49/wdstart/webdriver.py#L34-L56
train
bitesofcode/projexui
projexui/xorblookupworker.py
XOrbLookupWorker.cancel
def cancel(self): """ Cancels the current lookup. """ if self._running: self.interrupt() self._running = False self._cancelled = True self.loadingFinished.emit()
python
def cancel(self): """ Cancels the current lookup. """ if self._running: self.interrupt() self._running = False self._cancelled = True self.loadingFinished.emit()
[ "def", "cancel", "(", "self", ")", ":", "if", "self", ".", "_running", ":", "self", ".", "interrupt", "(", ")", "self", ".", "_running", "=", "False", "self", ".", "_cancelled", "=", "True", "self", ".", "loadingFinished", ".", "emit", "(", ")" ]
Cancels the current lookup.
[ "Cancels", "the", "current", "lookup", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xorblookupworker.py#L56-L64
train
bitesofcode/projexui
projexui/xorblookupworker.py
XOrbLookupWorker.loadBatch
def loadBatch(self, records): """ Loads the records for this instance in a batched mode. """ try: curr_batch = records[:self.batchSize()] next_batch = records[self.batchSize():] curr_records = list(curr_batch) if self._preloadColumns: for record in curr_records: record.recordValues(self._preloadColumns) if len(curr_records) == self.batchSize(): self.loadedRecords[object, object].emit(curr_records, next_batch) else: self.loadedRecords[object].emit(curr_records) except ConnectionLostError: self.connectionLost.emit() except Interruption: pass
python
def loadBatch(self, records): """ Loads the records for this instance in a batched mode. """ try: curr_batch = records[:self.batchSize()] next_batch = records[self.batchSize():] curr_records = list(curr_batch) if self._preloadColumns: for record in curr_records: record.recordValues(self._preloadColumns) if len(curr_records) == self.batchSize(): self.loadedRecords[object, object].emit(curr_records, next_batch) else: self.loadedRecords[object].emit(curr_records) except ConnectionLostError: self.connectionLost.emit() except Interruption: pass
[ "def", "loadBatch", "(", "self", ",", "records", ")", ":", "try", ":", "curr_batch", "=", "records", "[", ":", "self", ".", "batchSize", "(", ")", "]", "next_batch", "=", "records", "[", "self", ".", "batchSize", "(", ")", ":", "]", "curr_records", "=", "list", "(", "curr_batch", ")", "if", "self", ".", "_preloadColumns", ":", "for", "record", "in", "curr_records", ":", "record", ".", "recordValues", "(", "self", ".", "_preloadColumns", ")", "if", "len", "(", "curr_records", ")", "==", "self", ".", "batchSize", "(", ")", ":", "self", ".", "loadedRecords", "[", "object", ",", "object", "]", ".", "emit", "(", "curr_records", ",", "next_batch", ")", "else", ":", "self", ".", "loadedRecords", "[", "object", "]", ".", "emit", "(", "curr_records", ")", "except", "ConnectionLostError", ":", "self", ".", "connectionLost", ".", "emit", "(", ")", "except", "Interruption", ":", "pass" ]
Loads the records for this instance in a batched mode.
[ "Loads", "the", "records", "for", "this", "instance", "in", "a", "batched", "mode", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xorblookupworker.py#L104-L127
train
xflr6/fileconfig
fileconfig/bases.py
Config.names
def names(self): """Names, by which the instance can be retrieved.""" if getattr(self, 'key', None) is None: result = [] else: result = [self.key] if hasattr(self, 'aliases'): result.extend(self.aliases) return result
python
def names(self): """Names, by which the instance can be retrieved.""" if getattr(self, 'key', None) is None: result = [] else: result = [self.key] if hasattr(self, 'aliases'): result.extend(self.aliases) return result
[ "def", "names", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'key'", ",", "None", ")", "is", "None", ":", "result", "=", "[", "]", "else", ":", "result", "=", "[", "self", ".", "key", "]", "if", "hasattr", "(", "self", ",", "'aliases'", ")", ":", "result", ".", "extend", "(", "self", ".", "aliases", ")", "return", "result" ]
Names, by which the instance can be retrieved.
[ "Names", "by", "which", "the", "instance", "can", "be", "retrieved", "." ]
473d65f6442eb1ac49ada0b6e56cab45f8018c15
https://github.com/xflr6/fileconfig/blob/473d65f6442eb1ac49ada0b6e56cab45f8018c15/fileconfig/bases.py#L27-L35
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthroughscene.py
XWalkthroughScene.autoLayout
def autoLayout(self, size=None): """ Updates the layout for the graphics within this scene. """ if size is None: size = self._view.size() self.setSceneRect(0, 0, size.width(), size.height()) for item in self.items(): if isinstance(item, XWalkthroughGraphic): item.autoLayout(size)
python
def autoLayout(self, size=None): """ Updates the layout for the graphics within this scene. """ if size is None: size = self._view.size() self.setSceneRect(0, 0, size.width(), size.height()) for item in self.items(): if isinstance(item, XWalkthroughGraphic): item.autoLayout(size)
[ "def", "autoLayout", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", "=", "self", ".", "_view", ".", "size", "(", ")", "self", ".", "setSceneRect", "(", "0", ",", "0", ",", "size", ".", "width", "(", ")", ",", "size", ".", "height", "(", ")", ")", "for", "item", "in", "self", ".", "items", "(", ")", ":", "if", "isinstance", "(", "item", ",", "XWalkthroughGraphic", ")", ":", "item", ".", "autoLayout", "(", "size", ")" ]
Updates the layout for the graphics within this scene.
[ "Updates", "the", "layout", "for", "the", "graphics", "within", "this", "scene", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthroughscene.py#L46-L56
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthroughscene.py
XWalkthroughScene.prepare
def prepare(self): """ Prepares the items for display. """ for item in self.items(): if isinstance(item, XWalkthroughGraphic): item.prepare()
python
def prepare(self): """ Prepares the items for display. """ for item in self.items(): if isinstance(item, XWalkthroughGraphic): item.prepare()
[ "def", "prepare", "(", "self", ")", ":", "for", "item", "in", "self", ".", "items", "(", ")", ":", "if", "isinstance", "(", "item", ",", "XWalkthroughGraphic", ")", ":", "item", ".", "prepare", "(", ")" ]
Prepares the items for display.
[ "Prepares", "the", "items", "for", "display", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthroughscene.py#L83-L89
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthroughgraphics.py
XWalkthroughGraphic.autoLayout
def autoLayout(self, size): """ Lays out this widget within the graphics scene. """ # update the children alignment direction = self.property('direction', QtGui.QBoxLayout.TopToBottom) x = 0 y = 0 base_off_x = 0 base_off_y = 0 for i, child in enumerate(self.childItems()): off_x = 6 + child.boundingRect().width() off_y = 6 + child.boundingRect().height() if direction == QtGui.QBoxLayout.TopToBottom: child.setPos(x, y) y += off_y elif direction == QtGui.QBoxLayout.BottomToTop: y -= off_y child.setPos(x, y) if not base_off_y: base_off_y = off_y elif direction == QtGui.QBoxLayout.LeftToRight: child.setPos(x, y) x += off_x else: x -= off_x child.setPos(x, y) if not base_off_x: base_off_x = off_x #---------------------------------------------------------------------- pos = self.property('pos') align = self.property('align') offset = self.property('offset') rect = self.boundingRect() if pos: x = pos.x() y = pos.y() elif align == QtCore.Qt.AlignCenter: x = (size.width() - rect.width()) / 2.0 y = (size.height() - rect.height()) / 2.0 else: if align & QtCore.Qt.AlignLeft: x = 0 elif align & QtCore.Qt.AlignRight: x = (size.width() - rect.width()) else: x = (size.width() - rect.width()) / 2.0 if align & QtCore.Qt.AlignTop: y = 0 elif align & QtCore.Qt.AlignBottom: y = (size.height() - rect.height()) else: y = (size.height() - rect.height()) / 2.0 if offset: x += offset.x() y += offset.y() x += base_off_x y += base_off_y self.setPos(x, y)
python
def autoLayout(self, size): """ Lays out this widget within the graphics scene. """ # update the children alignment direction = self.property('direction', QtGui.QBoxLayout.TopToBottom) x = 0 y = 0 base_off_x = 0 base_off_y = 0 for i, child in enumerate(self.childItems()): off_x = 6 + child.boundingRect().width() off_y = 6 + child.boundingRect().height() if direction == QtGui.QBoxLayout.TopToBottom: child.setPos(x, y) y += off_y elif direction == QtGui.QBoxLayout.BottomToTop: y -= off_y child.setPos(x, y) if not base_off_y: base_off_y = off_y elif direction == QtGui.QBoxLayout.LeftToRight: child.setPos(x, y) x += off_x else: x -= off_x child.setPos(x, y) if not base_off_x: base_off_x = off_x #---------------------------------------------------------------------- pos = self.property('pos') align = self.property('align') offset = self.property('offset') rect = self.boundingRect() if pos: x = pos.x() y = pos.y() elif align == QtCore.Qt.AlignCenter: x = (size.width() - rect.width()) / 2.0 y = (size.height() - rect.height()) / 2.0 else: if align & QtCore.Qt.AlignLeft: x = 0 elif align & QtCore.Qt.AlignRight: x = (size.width() - rect.width()) else: x = (size.width() - rect.width()) / 2.0 if align & QtCore.Qt.AlignTop: y = 0 elif align & QtCore.Qt.AlignBottom: y = (size.height() - rect.height()) else: y = (size.height() - rect.height()) / 2.0 if offset: x += offset.x() y += offset.y() x += base_off_x y += base_off_y self.setPos(x, y)
[ "def", "autoLayout", "(", "self", ",", "size", ")", ":", "# update the children alignment\r", "direction", "=", "self", ".", "property", "(", "'direction'", ",", "QtGui", ".", "QBoxLayout", ".", "TopToBottom", ")", "x", "=", "0", "y", "=", "0", "base_off_x", "=", "0", "base_off_y", "=", "0", "for", "i", ",", "child", "in", "enumerate", "(", "self", ".", "childItems", "(", ")", ")", ":", "off_x", "=", "6", "+", "child", ".", "boundingRect", "(", ")", ".", "width", "(", ")", "off_y", "=", "6", "+", "child", ".", "boundingRect", "(", ")", ".", "height", "(", ")", "if", "direction", "==", "QtGui", ".", "QBoxLayout", ".", "TopToBottom", ":", "child", ".", "setPos", "(", "x", ",", "y", ")", "y", "+=", "off_y", "elif", "direction", "==", "QtGui", ".", "QBoxLayout", ".", "BottomToTop", ":", "y", "-=", "off_y", "child", ".", "setPos", "(", "x", ",", "y", ")", "if", "not", "base_off_y", ":", "base_off_y", "=", "off_y", "elif", "direction", "==", "QtGui", ".", "QBoxLayout", ".", "LeftToRight", ":", "child", ".", "setPos", "(", "x", ",", "y", ")", "x", "+=", "off_x", "else", ":", "x", "-=", "off_x", "child", ".", "setPos", "(", "x", ",", "y", ")", "if", "not", "base_off_x", ":", "base_off_x", "=", "off_x", "#----------------------------------------------------------------------\r", "pos", "=", "self", ".", "property", "(", "'pos'", ")", "align", "=", "self", ".", "property", "(", "'align'", ")", "offset", "=", "self", ".", "property", "(", "'offset'", ")", "rect", "=", "self", ".", "boundingRect", "(", ")", "if", "pos", ":", "x", "=", "pos", ".", "x", "(", ")", "y", "=", "pos", ".", "y", "(", ")", "elif", "align", "==", "QtCore", ".", "Qt", ".", "AlignCenter", ":", "x", "=", "(", "size", ".", "width", "(", ")", "-", "rect", ".", "width", "(", ")", ")", "/", "2.0", "y", "=", "(", "size", ".", "height", "(", ")", "-", "rect", ".", "height", "(", ")", ")", "/", "2.0", "else", ":", "if", "align", "&", "QtCore", ".", "Qt", ".", "AlignLeft", ":", "x", "=", "0", "elif", "align", "&", "QtCore", ".", "Qt", ".", "AlignRight", ":", "x", "=", "(", "size", ".", "width", "(", ")", "-", "rect", ".", "width", "(", ")", ")", "else", ":", "x", "=", "(", "size", ".", "width", "(", ")", "-", "rect", ".", "width", "(", ")", ")", "/", "2.0", "if", "align", "&", "QtCore", ".", "Qt", ".", "AlignTop", ":", "y", "=", "0", "elif", "align", "&", "QtCore", ".", "Qt", ".", "AlignBottom", ":", "y", "=", "(", "size", ".", "height", "(", ")", "-", "rect", ".", "height", "(", ")", ")", "else", ":", "y", "=", "(", "size", ".", "height", "(", ")", "-", "rect", ".", "height", "(", ")", ")", "/", "2.0", "if", "offset", ":", "x", "+=", "offset", ".", "x", "(", ")", "y", "+=", "offset", ".", "y", "(", ")", "x", "+=", "base_off_x", "y", "+=", "base_off_y", "self", ".", "setPos", "(", "x", ",", "y", ")" ]
Lays out this widget within the graphics scene.
[ "Lays", "out", "this", "widget", "within", "the", "graphics", "scene", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthroughgraphics.py#L105-L177
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthroughgraphics.py
XWalkthroughGraphic.prepare
def prepare(self): """ Prepares this graphic item to be displayed. """ text = self.property('caption') if text: capw = int(self.property('caption_width', 0)) item = self.addText(text, capw)
python
def prepare(self): """ Prepares this graphic item to be displayed. """ text = self.property('caption') if text: capw = int(self.property('caption_width', 0)) item = self.addText(text, capw)
[ "def", "prepare", "(", "self", ")", ":", "text", "=", "self", ".", "property", "(", "'caption'", ")", "if", "text", ":", "capw", "=", "int", "(", "self", ".", "property", "(", "'caption_width'", ",", "0", ")", ")", "item", "=", "self", ".", "addText", "(", "text", ",", "capw", ")" ]
Prepares this graphic item to be displayed.
[ "Prepares", "this", "graphic", "item", "to", "be", "displayed", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthroughgraphics.py#L209-L216
train
bitesofcode/projexui
projexui/widgets/xwalkthroughwidget/xwalkthroughgraphics.py
XWalkthroughSnapshot.prepare
def prepare(self): """ Prepares the information for this graphic. """ # determine if we already have a snapshot setup pixmap = self.property('pixmap') if pixmap is not None: return super(XWalkthroughSnapshot, self).prepare() # otherwise, setup the snapshot widget = self.property('widget') if type(widget) in (unicode, str): widget = self.findReference(widget) if not widget: return super(XWalkthroughSnapshot, self).prepare() # test if this is an overlay option if self.property('overlay') and widget.parent(): ref = self.referenceWidget() if ref == widget: pos = QtCore.QPoint(0, 0) else: glbl_pos = widget.mapToGlobal(QtCore.QPoint(0, 0)) pos = ref.mapFromGlobal(glbl_pos) self.setProperty('pos', pos) # crop out the options crop = self.property('crop', QtCore.QRect(0, 0, 0, 0)) if crop: rect = widget.rect() if crop.width(): rect.setWidth(crop.width()) if crop.height(): rect.setHeight(crop.height()) if crop.x(): rect.setX(rect.width() - crop.x()) if crop.y(): rect.setY(rect.height() - crop.y()) pixmap = QtGui.QPixmap.grabWidget(widget, rect) else: pixmap = QtGui.QPixmap.grabWidget(widget) scaled = self.property('scaled') if scaled: pixmap = pixmap.scaled(pixmap.width() * scaled, pixmap.height() * scaled, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation) kwds = {} kwds['whatsThis'] = widget.whatsThis() kwds['toolTip'] = widget.toolTip() kwds['windowTitle'] = widget.windowTitle() kwds['objectName'] = widget.objectName() self.setProperty('caption', self.property('caption', '').format(**kwds)) self.setProperty('pixmap', pixmap) self.addPixmap(pixmap) return super(XWalkthroughSnapshot, self).prepare()
python
def prepare(self): """ Prepares the information for this graphic. """ # determine if we already have a snapshot setup pixmap = self.property('pixmap') if pixmap is not None: return super(XWalkthroughSnapshot, self).prepare() # otherwise, setup the snapshot widget = self.property('widget') if type(widget) in (unicode, str): widget = self.findReference(widget) if not widget: return super(XWalkthroughSnapshot, self).prepare() # test if this is an overlay option if self.property('overlay') and widget.parent(): ref = self.referenceWidget() if ref == widget: pos = QtCore.QPoint(0, 0) else: glbl_pos = widget.mapToGlobal(QtCore.QPoint(0, 0)) pos = ref.mapFromGlobal(glbl_pos) self.setProperty('pos', pos) # crop out the options crop = self.property('crop', QtCore.QRect(0, 0, 0, 0)) if crop: rect = widget.rect() if crop.width(): rect.setWidth(crop.width()) if crop.height(): rect.setHeight(crop.height()) if crop.x(): rect.setX(rect.width() - crop.x()) if crop.y(): rect.setY(rect.height() - crop.y()) pixmap = QtGui.QPixmap.grabWidget(widget, rect) else: pixmap = QtGui.QPixmap.grabWidget(widget) scaled = self.property('scaled') if scaled: pixmap = pixmap.scaled(pixmap.width() * scaled, pixmap.height() * scaled, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation) kwds = {} kwds['whatsThis'] = widget.whatsThis() kwds['toolTip'] = widget.toolTip() kwds['windowTitle'] = widget.windowTitle() kwds['objectName'] = widget.objectName() self.setProperty('caption', self.property('caption', '').format(**kwds)) self.setProperty('pixmap', pixmap) self.addPixmap(pixmap) return super(XWalkthroughSnapshot, self).prepare()
[ "def", "prepare", "(", "self", ")", ":", "# determine if we already have a snapshot setup\r", "pixmap", "=", "self", ".", "property", "(", "'pixmap'", ")", "if", "pixmap", "is", "not", "None", ":", "return", "super", "(", "XWalkthroughSnapshot", ",", "self", ")", ".", "prepare", "(", ")", "# otherwise, setup the snapshot\r", "widget", "=", "self", ".", "property", "(", "'widget'", ")", "if", "type", "(", "widget", ")", "in", "(", "unicode", ",", "str", ")", ":", "widget", "=", "self", ".", "findReference", "(", "widget", ")", "if", "not", "widget", ":", "return", "super", "(", "XWalkthroughSnapshot", ",", "self", ")", ".", "prepare", "(", ")", "# test if this is an overlay option\r", "if", "self", ".", "property", "(", "'overlay'", ")", "and", "widget", ".", "parent", "(", ")", ":", "ref", "=", "self", ".", "referenceWidget", "(", ")", "if", "ref", "==", "widget", ":", "pos", "=", "QtCore", ".", "QPoint", "(", "0", ",", "0", ")", "else", ":", "glbl_pos", "=", "widget", ".", "mapToGlobal", "(", "QtCore", ".", "QPoint", "(", "0", ",", "0", ")", ")", "pos", "=", "ref", ".", "mapFromGlobal", "(", "glbl_pos", ")", "self", ".", "setProperty", "(", "'pos'", ",", "pos", ")", "# crop out the options\r", "crop", "=", "self", ".", "property", "(", "'crop'", ",", "QtCore", ".", "QRect", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "if", "crop", ":", "rect", "=", "widget", ".", "rect", "(", ")", "if", "crop", ".", "width", "(", ")", ":", "rect", ".", "setWidth", "(", "crop", ".", "width", "(", ")", ")", "if", "crop", ".", "height", "(", ")", ":", "rect", ".", "setHeight", "(", "crop", ".", "height", "(", ")", ")", "if", "crop", ".", "x", "(", ")", ":", "rect", ".", "setX", "(", "rect", ".", "width", "(", ")", "-", "crop", ".", "x", "(", ")", ")", "if", "crop", ".", "y", "(", ")", ":", "rect", ".", "setY", "(", "rect", ".", "height", "(", ")", "-", "crop", ".", "y", "(", ")", ")", "pixmap", "=", "QtGui", ".", "QPixmap", ".", "grabWidget", "(", "widget", ",", "rect", ")", "else", ":", "pixmap", "=", "QtGui", ".", "QPixmap", ".", "grabWidget", "(", "widget", ")", "scaled", "=", "self", ".", "property", "(", "'scaled'", ")", "if", "scaled", ":", "pixmap", "=", "pixmap", ".", "scaled", "(", "pixmap", ".", "width", "(", ")", "*", "scaled", ",", "pixmap", ".", "height", "(", ")", "*", "scaled", ",", "QtCore", ".", "Qt", ".", "KeepAspectRatio", ",", "QtCore", ".", "Qt", ".", "SmoothTransformation", ")", "kwds", "=", "{", "}", "kwds", "[", "'whatsThis'", "]", "=", "widget", ".", "whatsThis", "(", ")", "kwds", "[", "'toolTip'", "]", "=", "widget", ".", "toolTip", "(", ")", "kwds", "[", "'windowTitle'", "]", "=", "widget", ".", "windowTitle", "(", ")", "kwds", "[", "'objectName'", "]", "=", "widget", ".", "objectName", "(", ")", "self", ".", "setProperty", "(", "'caption'", ",", "self", ".", "property", "(", "'caption'", ",", "''", ")", ".", "format", "(", "*", "*", "kwds", ")", ")", "self", ".", "setProperty", "(", "'pixmap'", ",", "pixmap", ")", "self", ".", "addPixmap", "(", "pixmap", ")", "return", "super", "(", "XWalkthroughSnapshot", ",", "self", ")", ".", "prepare", "(", ")" ]
Prepares the information for this graphic.
[ "Prepares", "the", "information", "for", "this", "graphic", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xwalkthroughwidget/xwalkthroughgraphics.py#L280-L342
train
nprapps/mapturner
mapturner/__init__.py
MapTurner.get_real_layer_path
def get_real_layer_path(self, path): """ Get the path the actual layer file. """ filename = path.split('/')[-1] local_path = path filetype = os.path.splitext(filename)[1] # Url if re.match(r'^[a-zA-Z]+://', path): local_path = os.path.join(DATA_DIRECTORY, filename) if not os.path.exists(local_path): sys.stdout.write('* Downloading %s...\n' % filename) self.download_file(path, local_path) elif self.args.redownload: os.remove(local_path) sys.stdout.write('* Redownloading %s...\n' % filename) self.download_file(path, local_path) # Non-existant file elif not os.path.exists(local_path): raise Exception('%s does not exist' % local_path) real_path = path # Zip files if filetype == '.zip': slug = os.path.splitext(filename)[0] real_path = os.path.join(DATA_DIRECTORY, slug) if not os.path.exists(real_path): sys.stdout.write('* Unzipping...\n') self.unzip_file(local_path, real_path) return real_path
python
def get_real_layer_path(self, path): """ Get the path the actual layer file. """ filename = path.split('/')[-1] local_path = path filetype = os.path.splitext(filename)[1] # Url if re.match(r'^[a-zA-Z]+://', path): local_path = os.path.join(DATA_DIRECTORY, filename) if not os.path.exists(local_path): sys.stdout.write('* Downloading %s...\n' % filename) self.download_file(path, local_path) elif self.args.redownload: os.remove(local_path) sys.stdout.write('* Redownloading %s...\n' % filename) self.download_file(path, local_path) # Non-existant file elif not os.path.exists(local_path): raise Exception('%s does not exist' % local_path) real_path = path # Zip files if filetype == '.zip': slug = os.path.splitext(filename)[0] real_path = os.path.join(DATA_DIRECTORY, slug) if not os.path.exists(real_path): sys.stdout.write('* Unzipping...\n') self.unzip_file(local_path, real_path) return real_path
[ "def", "get_real_layer_path", "(", "self", ",", "path", ")", ":", "filename", "=", "path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "local_path", "=", "path", "filetype", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "# Url", "if", "re", ".", "match", "(", "r'^[a-zA-Z]+://'", ",", "path", ")", ":", "local_path", "=", "os", ".", "path", ".", "join", "(", "DATA_DIRECTORY", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "local_path", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'* Downloading %s...\\n'", "%", "filename", ")", "self", ".", "download_file", "(", "path", ",", "local_path", ")", "elif", "self", ".", "args", ".", "redownload", ":", "os", ".", "remove", "(", "local_path", ")", "sys", ".", "stdout", ".", "write", "(", "'* Redownloading %s...\\n'", "%", "filename", ")", "self", ".", "download_file", "(", "path", ",", "local_path", ")", "# Non-existant file", "elif", "not", "os", ".", "path", ".", "exists", "(", "local_path", ")", ":", "raise", "Exception", "(", "'%s does not exist'", "%", "local_path", ")", "real_path", "=", "path", "# Zip files", "if", "filetype", "==", "'.zip'", ":", "slug", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "real_path", "=", "os", ".", "path", ".", "join", "(", "DATA_DIRECTORY", ",", "slug", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "real_path", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'* Unzipping...\\n'", ")", "self", ".", "unzip_file", "(", "local_path", ",", "real_path", ")", "return", "real_path" ]
Get the path the actual layer file.
[ "Get", "the", "path", "the", "actual", "layer", "file", "." ]
fc9747c9d1584af2053bff3df229a460ef2a5f62
https://github.com/nprapps/mapturner/blob/fc9747c9d1584af2053bff3df229a460ef2a5f62/mapturner/__init__.py#L122-L157
train
nprapps/mapturner
mapturner/__init__.py
MapTurner.download_file
def download_file(self, url, local_path): """ Download a file from a remote host. """ response = requests.get(url, stream=True) with open(local_path, 'wb') as f: for chunk in tqdm(response.iter_content(chunk_size=1024), unit='KB'): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush()
python
def download_file(self, url, local_path): """ Download a file from a remote host. """ response = requests.get(url, stream=True) with open(local_path, 'wb') as f: for chunk in tqdm(response.iter_content(chunk_size=1024), unit='KB'): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush()
[ "def", "download_file", "(", "self", ",", "url", ",", "local_path", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "with", "open", "(", "local_path", ",", "'wb'", ")", "as", "f", ":", "for", "chunk", "in", "tqdm", "(", "response", ".", "iter_content", "(", "chunk_size", "=", "1024", ")", ",", "unit", "=", "'KB'", ")", ":", "if", "chunk", ":", "# filter out keep-alive new chunks", "f", ".", "write", "(", "chunk", ")", "f", ".", "flush", "(", ")" ]
Download a file from a remote host.
[ "Download", "a", "file", "from", "a", "remote", "host", "." ]
fc9747c9d1584af2053bff3df229a460ef2a5f62
https://github.com/nprapps/mapturner/blob/fc9747c9d1584af2053bff3df229a460ef2a5f62/mapturner/__init__.py#L159-L169
train
nprapps/mapturner
mapturner/__init__.py
MapTurner.unzip_file
def unzip_file(self, zip_path, output_path): """ Unzip a local file into a specified directory. """ with zipfile.ZipFile(zip_path, 'r') as z: z.extractall(output_path)
python
def unzip_file(self, zip_path, output_path): """ Unzip a local file into a specified directory. """ with zipfile.ZipFile(zip_path, 'r') as z: z.extractall(output_path)
[ "def", "unzip_file", "(", "self", ",", "zip_path", ",", "output_path", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "zip_path", ",", "'r'", ")", "as", "z", ":", "z", ".", "extractall", "(", "output_path", ")" ]
Unzip a local file into a specified directory.
[ "Unzip", "a", "local", "file", "into", "a", "specified", "directory", "." ]
fc9747c9d1584af2053bff3df229a460ef2a5f62
https://github.com/nprapps/mapturner/blob/fc9747c9d1584af2053bff3df229a460ef2a5f62/mapturner/__init__.py#L171-L176
train
nprapps/mapturner
mapturner/__init__.py
MapTurner.process_ogr2ogr
def process_ogr2ogr(self, name, layer, input_path): """ Process a layer using ogr2ogr. """ output_path = os.path.join(TEMP_DIRECTORY, '%s.json' % name) if os.path.exists(output_path): os.remove(output_path) ogr2ogr_cmd = [ 'ogr2ogr', '-f', 'GeoJSON', '-clipsrc', self.config['bbox'] ] if 'where' in layer: ogr2ogr_cmd.extend([ '-where', '"%s"' % layer['where'] ]) ogr2ogr_cmd.extend([ output_path, input_path ]) sys.stdout.write('* Running ogr2ogr\n') if self.args.verbose: sys.stdout.write(' %s\n' % ' '.join(ogr2ogr_cmd)) r = envoy.run(' '.join(ogr2ogr_cmd)) if r.status_code != 0: sys.stderr.write(r.std_err) return output_path
python
def process_ogr2ogr(self, name, layer, input_path): """ Process a layer using ogr2ogr. """ output_path = os.path.join(TEMP_DIRECTORY, '%s.json' % name) if os.path.exists(output_path): os.remove(output_path) ogr2ogr_cmd = [ 'ogr2ogr', '-f', 'GeoJSON', '-clipsrc', self.config['bbox'] ] if 'where' in layer: ogr2ogr_cmd.extend([ '-where', '"%s"' % layer['where'] ]) ogr2ogr_cmd.extend([ output_path, input_path ]) sys.stdout.write('* Running ogr2ogr\n') if self.args.verbose: sys.stdout.write(' %s\n' % ' '.join(ogr2ogr_cmd)) r = envoy.run(' '.join(ogr2ogr_cmd)) if r.status_code != 0: sys.stderr.write(r.std_err) return output_path
[ "def", "process_ogr2ogr", "(", "self", ",", "name", ",", "layer", ",", "input_path", ")", ":", "output_path", "=", "os", ".", "path", ".", "join", "(", "TEMP_DIRECTORY", ",", "'%s.json'", "%", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "output_path", ")", ":", "os", ".", "remove", "(", "output_path", ")", "ogr2ogr_cmd", "=", "[", "'ogr2ogr'", ",", "'-f'", ",", "'GeoJSON'", ",", "'-clipsrc'", ",", "self", ".", "config", "[", "'bbox'", "]", "]", "if", "'where'", "in", "layer", ":", "ogr2ogr_cmd", ".", "extend", "(", "[", "'-where'", ",", "'\"%s\"'", "%", "layer", "[", "'where'", "]", "]", ")", "ogr2ogr_cmd", ".", "extend", "(", "[", "output_path", ",", "input_path", "]", ")", "sys", ".", "stdout", ".", "write", "(", "'* Running ogr2ogr\\n'", ")", "if", "self", ".", "args", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "' %s\\n'", "%", "' '", ".", "join", "(", "ogr2ogr_cmd", ")", ")", "r", "=", "envoy", ".", "run", "(", "' '", ".", "join", "(", "ogr2ogr_cmd", ")", ")", "if", "r", ".", "status_code", "!=", "0", ":", "sys", ".", "stderr", ".", "write", "(", "r", ".", "std_err", ")", "return", "output_path" ]
Process a layer using ogr2ogr.
[ "Process", "a", "layer", "using", "ogr2ogr", "." ]
fc9747c9d1584af2053bff3df229a460ef2a5f62
https://github.com/nprapps/mapturner/blob/fc9747c9d1584af2053bff3df229a460ef2a5f62/mapturner/__init__.py#L193-L228
train
nprapps/mapturner
mapturner/__init__.py
MapTurner.process_topojson
def process_topojson(self, name, layer, input_path): """ Process layer using topojson. """ output_path = os.path.join(TEMP_DIRECTORY, '%s.topojson' % name) # Use local topojson binary topojson_binary = 'node_modules/bin/topojson' if not os.path.exists(topojson_binary): # try with global topojson binary topojson_binary = 'topojson' topo_cmd = [ topojson_binary, '-o', output_path ] if 'id-property' in layer: topo_cmd.extend([ '--id-property', layer['id-property'] ]) if layer.get('all-properties', False): topo_cmd.append('-p') elif 'properties' in layer: topo_cmd.extend([ '-p', ','.join(layer['properties']) ]) topo_cmd.extend([ '--', input_path ]) sys.stdout.write('* Running TopoJSON\n') if self.args.verbose: sys.stdout.write(' %s\n' % ' '.join(topo_cmd)) r = envoy.run(' '.join(topo_cmd)) if r.status_code != 0: sys.stderr.write(r.std_err) return output_path
python
def process_topojson(self, name, layer, input_path): """ Process layer using topojson. """ output_path = os.path.join(TEMP_DIRECTORY, '%s.topojson' % name) # Use local topojson binary topojson_binary = 'node_modules/bin/topojson' if not os.path.exists(topojson_binary): # try with global topojson binary topojson_binary = 'topojson' topo_cmd = [ topojson_binary, '-o', output_path ] if 'id-property' in layer: topo_cmd.extend([ '--id-property', layer['id-property'] ]) if layer.get('all-properties', False): topo_cmd.append('-p') elif 'properties' in layer: topo_cmd.extend([ '-p', ','.join(layer['properties']) ]) topo_cmd.extend([ '--', input_path ]) sys.stdout.write('* Running TopoJSON\n') if self.args.verbose: sys.stdout.write(' %s\n' % ' '.join(topo_cmd)) r = envoy.run(' '.join(topo_cmd)) if r.status_code != 0: sys.stderr.write(r.std_err) return output_path
[ "def", "process_topojson", "(", "self", ",", "name", ",", "layer", ",", "input_path", ")", ":", "output_path", "=", "os", ".", "path", ".", "join", "(", "TEMP_DIRECTORY", ",", "'%s.topojson'", "%", "name", ")", "# Use local topojson binary", "topojson_binary", "=", "'node_modules/bin/topojson'", "if", "not", "os", ".", "path", ".", "exists", "(", "topojson_binary", ")", ":", "# try with global topojson binary", "topojson_binary", "=", "'topojson'", "topo_cmd", "=", "[", "topojson_binary", ",", "'-o'", ",", "output_path", "]", "if", "'id-property'", "in", "layer", ":", "topo_cmd", ".", "extend", "(", "[", "'--id-property'", ",", "layer", "[", "'id-property'", "]", "]", ")", "if", "layer", ".", "get", "(", "'all-properties'", ",", "False", ")", ":", "topo_cmd", ".", "append", "(", "'-p'", ")", "elif", "'properties'", "in", "layer", ":", "topo_cmd", ".", "extend", "(", "[", "'-p'", ",", "','", ".", "join", "(", "layer", "[", "'properties'", "]", ")", "]", ")", "topo_cmd", ".", "extend", "(", "[", "'--'", ",", "input_path", "]", ")", "sys", ".", "stdout", ".", "write", "(", "'* Running TopoJSON\\n'", ")", "if", "self", ".", "args", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "' %s\\n'", "%", "' '", ".", "join", "(", "topo_cmd", ")", ")", "r", "=", "envoy", ".", "run", "(", "' '", ".", "join", "(", "topo_cmd", ")", ")", "if", "r", ".", "status_code", "!=", "0", ":", "sys", ".", "stderr", ".", "write", "(", "r", ".", "std_err", ")", "return", "output_path" ]
Process layer using topojson.
[ "Process", "layer", "using", "topojson", "." ]
fc9747c9d1584af2053bff3df229a460ef2a5f62
https://github.com/nprapps/mapturner/blob/fc9747c9d1584af2053bff3df229a460ef2a5f62/mapturner/__init__.py#L230-L275
train
nprapps/mapturner
mapturner/__init__.py
MapTurner.merge
def merge(self, paths): """ Merge data layers into a single topojson file. """ # Use local topojson binary topojson_binary = 'node_modules/bin/topojson' if not os.path.exists(topojson_binary): # try with global topojson binary topojson_binary = 'topojson' merge_cmd = '%(binary)s -o %(output_path)s --bbox -p -- %(paths)s' % { 'output_path': self.args.output_path, 'paths': ' '.join(paths), 'binary': topojson_binary } sys.stdout.write('Merging layers\n') if self.args.verbose: sys.stdout.write(' %s\n' % merge_cmd) r = envoy.run(merge_cmd) if r.status_code != 0: sys.stderr.write(r.std_err)
python
def merge(self, paths): """ Merge data layers into a single topojson file. """ # Use local topojson binary topojson_binary = 'node_modules/bin/topojson' if not os.path.exists(topojson_binary): # try with global topojson binary topojson_binary = 'topojson' merge_cmd = '%(binary)s -o %(output_path)s --bbox -p -- %(paths)s' % { 'output_path': self.args.output_path, 'paths': ' '.join(paths), 'binary': topojson_binary } sys.stdout.write('Merging layers\n') if self.args.verbose: sys.stdout.write(' %s\n' % merge_cmd) r = envoy.run(merge_cmd) if r.status_code != 0: sys.stderr.write(r.std_err)
[ "def", "merge", "(", "self", ",", "paths", ")", ":", "# Use local topojson binary", "topojson_binary", "=", "'node_modules/bin/topojson'", "if", "not", "os", ".", "path", ".", "exists", "(", "topojson_binary", ")", ":", "# try with global topojson binary", "topojson_binary", "=", "'topojson'", "merge_cmd", "=", "'%(binary)s -o %(output_path)s --bbox -p -- %(paths)s'", "%", "{", "'output_path'", ":", "self", ".", "args", ".", "output_path", ",", "'paths'", ":", "' '", ".", "join", "(", "paths", ")", ",", "'binary'", ":", "topojson_binary", "}", "sys", ".", "stdout", ".", "write", "(", "'Merging layers\\n'", ")", "if", "self", ".", "args", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "' %s\\n'", "%", "merge_cmd", ")", "r", "=", "envoy", ".", "run", "(", "merge_cmd", ")", "if", "r", ".", "status_code", "!=", "0", ":", "sys", ".", "stderr", ".", "write", "(", "r", ".", "std_err", ")" ]
Merge data layers into a single topojson file.
[ "Merge", "data", "layers", "into", "a", "single", "topojson", "file", "." ]
fc9747c9d1584af2053bff3df229a460ef2a5f62
https://github.com/nprapps/mapturner/blob/fc9747c9d1584af2053bff3df229a460ef2a5f62/mapturner/__init__.py#L277-L303
train
bitesofcode/projexui
projexui/widgets/xmenutemplatewidget/xmenutemplatewidget.py
XMenuTemplateWidget.createMenu
def createMenu( self ): """ Creates a new menu with the given name. """ name, accepted = QInputDialog.getText( self, 'Create Menu', 'Name: ') if ( accepted ): self.addMenuItem(self.createMenuItem(name), self.uiMenuTREE.currentItem())
python
def createMenu( self ): """ Creates a new menu with the given name. """ name, accepted = QInputDialog.getText( self, 'Create Menu', 'Name: ') if ( accepted ): self.addMenuItem(self.createMenuItem(name), self.uiMenuTREE.currentItem())
[ "def", "createMenu", "(", "self", ")", ":", "name", ",", "accepted", "=", "QInputDialog", ".", "getText", "(", "self", ",", "'Create Menu'", ",", "'Name: '", ")", "if", "(", "accepted", ")", ":", "self", ".", "addMenuItem", "(", "self", ".", "createMenuItem", "(", "name", ")", ",", "self", ".", "uiMenuTREE", ".", "currentItem", "(", ")", ")" ]
Creates a new menu with the given name.
[ "Creates", "a", "new", "menu", "with", "the", "given", "name", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmenutemplatewidget/xmenutemplatewidget.py#L120-L130
train
bitesofcode/projexui
projexui/widgets/xmenutemplatewidget/xmenutemplatewidget.py
XMenuTemplateWidget.removeItem
def removeItem( self ): """ Removes the item from the menu. """ item = self.uiMenuTREE.currentItem() if ( not item ): return opts = QMessageBox.Yes | QMessageBox.No answer = QMessageBox.question( self, 'Remove Item', 'Are you sure you want to remove this '\ ' item?', opts ) if ( answer == QMessageBox.Yes ): parent = item.parent() if ( parent ): parent.takeChild(parent.indexOfChild(item)) else: tree = self.uiMenuTREE tree.takeTopLevelItem(tree.indexOfTopLevelItem(item))
python
def removeItem( self ): """ Removes the item from the menu. """ item = self.uiMenuTREE.currentItem() if ( not item ): return opts = QMessageBox.Yes | QMessageBox.No answer = QMessageBox.question( self, 'Remove Item', 'Are you sure you want to remove this '\ ' item?', opts ) if ( answer == QMessageBox.Yes ): parent = item.parent() if ( parent ): parent.takeChild(parent.indexOfChild(item)) else: tree = self.uiMenuTREE tree.takeTopLevelItem(tree.indexOfTopLevelItem(item))
[ "def", "removeItem", "(", "self", ")", ":", "item", "=", "self", ".", "uiMenuTREE", ".", "currentItem", "(", ")", "if", "(", "not", "item", ")", ":", "return", "opts", "=", "QMessageBox", ".", "Yes", "|", "QMessageBox", ".", "No", "answer", "=", "QMessageBox", ".", "question", "(", "self", ",", "'Remove Item'", ",", "'Are you sure you want to remove this '", "' item?'", ",", "opts", ")", "if", "(", "answer", "==", "QMessageBox", ".", "Yes", ")", ":", "parent", "=", "item", ".", "parent", "(", ")", "if", "(", "parent", ")", ":", "parent", ".", "takeChild", "(", "parent", ".", "indexOfChild", "(", "item", ")", ")", "else", ":", "tree", "=", "self", ".", "uiMenuTREE", "tree", ".", "takeTopLevelItem", "(", "tree", ".", "indexOfTopLevelItem", "(", "item", ")", ")" ]
Removes the item from the menu.
[ "Removes", "the", "item", "from", "the", "menu", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmenutemplatewidget/xmenutemplatewidget.py#L248-L269
train
bitesofcode/projexui
projexui/widgets/xmenutemplatewidget/xmenutemplatewidget.py
XMenuTemplateWidget.renameMenu
def renameMenu( self ): """ Prompts the user to supply a new name for the menu. """ item = self.uiMenuTREE.currentItem() name, accepted = QInputDialog.getText( self, 'Rename Menu', 'Name:', QLineEdit.Normal, item.text(0)) if ( accepted ): item.setText(0, name)
python
def renameMenu( self ): """ Prompts the user to supply a new name for the menu. """ item = self.uiMenuTREE.currentItem() name, accepted = QInputDialog.getText( self, 'Rename Menu', 'Name:', QLineEdit.Normal, item.text(0)) if ( accepted ): item.setText(0, name)
[ "def", "renameMenu", "(", "self", ")", ":", "item", "=", "self", ".", "uiMenuTREE", ".", "currentItem", "(", ")", "name", ",", "accepted", "=", "QInputDialog", ".", "getText", "(", "self", ",", "'Rename Menu'", ",", "'Name:'", ",", "QLineEdit", ".", "Normal", ",", "item", ".", "text", "(", "0", ")", ")", "if", "(", "accepted", ")", ":", "item", ".", "setText", "(", "0", ",", "name", ")" ]
Prompts the user to supply a new name for the menu.
[ "Prompts", "the", "user", "to", "supply", "a", "new", "name", "for", "the", "menu", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmenutemplatewidget/xmenutemplatewidget.py#L271-L283
train
bitesofcode/projexui
projexui/widgets/xmenutemplatewidget/xmenutemplatewidget.py
XMenuTemplateWidget.showMenu
def showMenu( self ): """ Creates a menu to display for the editing of template information. """ item = self.uiMenuTREE.currentItem() menu = QMenu(self) act = menu.addAction('Add Menu...') act.setIcon(QIcon(projexui.resources.find('img/folder.png'))) act.triggered.connect(self.createMenu) if ( item and item.data(0, Qt.UserRole) == 'menu' ): act = menu.addAction('Rename Menu...') ico = QIcon(projexui.resources.find('img/edit.png')) act.setIcon(ico) act.triggered.connect(self.renameMenu) act = menu.addAction('Add Separator') act.setIcon(QIcon(projexui.resources.find('img/ui/splitter.png'))) act.triggered.connect(self.createSeparator) menu.addSeparator() act = menu.addAction('Remove Item') act.setIcon(QIcon(projexui.resources.find('img/remove.png'))) act.triggered.connect(self.removeItem) act.setEnabled(item is not None) menu.exec_(QCursor.pos())
python
def showMenu( self ): """ Creates a menu to display for the editing of template information. """ item = self.uiMenuTREE.currentItem() menu = QMenu(self) act = menu.addAction('Add Menu...') act.setIcon(QIcon(projexui.resources.find('img/folder.png'))) act.triggered.connect(self.createMenu) if ( item and item.data(0, Qt.UserRole) == 'menu' ): act = menu.addAction('Rename Menu...') ico = QIcon(projexui.resources.find('img/edit.png')) act.setIcon(ico) act.triggered.connect(self.renameMenu) act = menu.addAction('Add Separator') act.setIcon(QIcon(projexui.resources.find('img/ui/splitter.png'))) act.triggered.connect(self.createSeparator) menu.addSeparator() act = menu.addAction('Remove Item') act.setIcon(QIcon(projexui.resources.find('img/remove.png'))) act.triggered.connect(self.removeItem) act.setEnabled(item is not None) menu.exec_(QCursor.pos())
[ "def", "showMenu", "(", "self", ")", ":", "item", "=", "self", ".", "uiMenuTREE", ".", "currentItem", "(", ")", "menu", "=", "QMenu", "(", "self", ")", "act", "=", "menu", ".", "addAction", "(", "'Add Menu...'", ")", "act", ".", "setIcon", "(", "QIcon", "(", "projexui", ".", "resources", ".", "find", "(", "'img/folder.png'", ")", ")", ")", "act", ".", "triggered", ".", "connect", "(", "self", ".", "createMenu", ")", "if", "(", "item", "and", "item", ".", "data", "(", "0", ",", "Qt", ".", "UserRole", ")", "==", "'menu'", ")", ":", "act", "=", "menu", ".", "addAction", "(", "'Rename Menu...'", ")", "ico", "=", "QIcon", "(", "projexui", ".", "resources", ".", "find", "(", "'img/edit.png'", ")", ")", "act", ".", "setIcon", "(", "ico", ")", "act", ".", "triggered", ".", "connect", "(", "self", ".", "renameMenu", ")", "act", "=", "menu", ".", "addAction", "(", "'Add Separator'", ")", "act", ".", "setIcon", "(", "QIcon", "(", "projexui", ".", "resources", ".", "find", "(", "'img/ui/splitter.png'", ")", ")", ")", "act", ".", "triggered", ".", "connect", "(", "self", ".", "createSeparator", ")", "menu", ".", "addSeparator", "(", ")", "act", "=", "menu", ".", "addAction", "(", "'Remove Item'", ")", "act", ".", "setIcon", "(", "QIcon", "(", "projexui", ".", "resources", ".", "find", "(", "'img/remove.png'", ")", ")", ")", "act", ".", "triggered", ".", "connect", "(", "self", ".", "removeItem", ")", "act", ".", "setEnabled", "(", "item", "is", "not", "None", ")", "menu", ".", "exec_", "(", "QCursor", ".", "pos", "(", ")", ")" ]
Creates a menu to display for the editing of template information.
[ "Creates", "a", "menu", "to", "display", "for", "the", "editing", "of", "template", "information", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmenutemplatewidget/xmenutemplatewidget.py#L350-L378
train
solarnz/Flask-Stats
flask_stats/__init__.py
Stats.init_app
def init_app(self, app): """Inititialise the extension with the app object. :param app: Your application object """ host = app.config.get('STATS_HOSTNAME', 'localhost') port = app.config.get('STATS_PORT', 8125) base_key = app.config.get('STATS_BASE_KEY', app.name) client = _StatsClient( host=host, port=port, prefix=base_key, ) app.before_request(client.flask_time_start) app.after_request(client.flask_time_end) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions.setdefault('stats', {}) app.extensions['stats'][self] = client return client
python
def init_app(self, app): """Inititialise the extension with the app object. :param app: Your application object """ host = app.config.get('STATS_HOSTNAME', 'localhost') port = app.config.get('STATS_PORT', 8125) base_key = app.config.get('STATS_BASE_KEY', app.name) client = _StatsClient( host=host, port=port, prefix=base_key, ) app.before_request(client.flask_time_start) app.after_request(client.flask_time_end) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions.setdefault('stats', {}) app.extensions['stats'][self] = client return client
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "host", "=", "app", ".", "config", ".", "get", "(", "'STATS_HOSTNAME'", ",", "'localhost'", ")", "port", "=", "app", ".", "config", ".", "get", "(", "'STATS_PORT'", ",", "8125", ")", "base_key", "=", "app", ".", "config", ".", "get", "(", "'STATS_BASE_KEY'", ",", "app", ".", "name", ")", "client", "=", "_StatsClient", "(", "host", "=", "host", ",", "port", "=", "port", ",", "prefix", "=", "base_key", ",", ")", "app", ".", "before_request", "(", "client", ".", "flask_time_start", ")", "app", ".", "after_request", "(", "client", ".", "flask_time_end", ")", "if", "not", "hasattr", "(", "app", ",", "'extensions'", ")", ":", "app", ".", "extensions", "=", "{", "}", "app", ".", "extensions", ".", "setdefault", "(", "'stats'", ",", "{", "}", ")", "app", ".", "extensions", "[", "'stats'", "]", "[", "self", "]", "=", "client", "return", "client" ]
Inititialise the extension with the app object. :param app: Your application object
[ "Inititialise", "the", "extension", "with", "the", "app", "object", "." ]
de9e476a30a98c9aa0eec4b9a18b150c905c382e
https://github.com/solarnz/Flask-Stats/blob/de9e476a30a98c9aa0eec4b9a18b150c905c382e/flask_stats/__init__.py#L50-L73
train
Zitrax/nose-dep
nosedep.py
depends
def depends(func=None, after=None, before=None, priority=None): """Decorator to specify test dependencies :param after: The test needs to run after this/these tests. String or list of strings. :param before: The test needs to run before this/these tests. String or list of strings. """ if not (func is None or inspect.ismethod(func) or inspect.isfunction(func)): raise ValueError("depends decorator can only be used on functions or methods") if not (after or before or priority): raise ValueError("depends decorator needs at least one argument") # This avoids some nesting in the decorator # If called without func the decorator was called with optional args # so we'll return a function with those args filled in. if func is None: return partial(depends, after=after, before=before, priority=priority) def self_check(a, b): if a == b: raise ValueError("Test '{}' cannot depend on itself".format(a)) def handle_dep(conditions, _before=True): if conditions: if type(conditions) is not list: conditions = [conditions] for cond in conditions: if hasattr(cond, '__call__'): cond = cond.__name__ self_check(func.__name__, cond) if _before: soft_dependencies[cond].add(func.__name__) else: dependencies[func.__name__].add(cond) handle_dep(before) handle_dep(after, False) if priority: priorities[func.__name__] = priority @wraps(func) def inner(*args, **kwargs): return func(*args, **kwargs) return inner
python
def depends(func=None, after=None, before=None, priority=None): """Decorator to specify test dependencies :param after: The test needs to run after this/these tests. String or list of strings. :param before: The test needs to run before this/these tests. String or list of strings. """ if not (func is None or inspect.ismethod(func) or inspect.isfunction(func)): raise ValueError("depends decorator can only be used on functions or methods") if not (after or before or priority): raise ValueError("depends decorator needs at least one argument") # This avoids some nesting in the decorator # If called without func the decorator was called with optional args # so we'll return a function with those args filled in. if func is None: return partial(depends, after=after, before=before, priority=priority) def self_check(a, b): if a == b: raise ValueError("Test '{}' cannot depend on itself".format(a)) def handle_dep(conditions, _before=True): if conditions: if type(conditions) is not list: conditions = [conditions] for cond in conditions: if hasattr(cond, '__call__'): cond = cond.__name__ self_check(func.__name__, cond) if _before: soft_dependencies[cond].add(func.__name__) else: dependencies[func.__name__].add(cond) handle_dep(before) handle_dep(after, False) if priority: priorities[func.__name__] = priority @wraps(func) def inner(*args, **kwargs): return func(*args, **kwargs) return inner
[ "def", "depends", "(", "func", "=", "None", ",", "after", "=", "None", ",", "before", "=", "None", ",", "priority", "=", "None", ")", ":", "if", "not", "(", "func", "is", "None", "or", "inspect", ".", "ismethod", "(", "func", ")", "or", "inspect", ".", "isfunction", "(", "func", ")", ")", ":", "raise", "ValueError", "(", "\"depends decorator can only be used on functions or methods\"", ")", "if", "not", "(", "after", "or", "before", "or", "priority", ")", ":", "raise", "ValueError", "(", "\"depends decorator needs at least one argument\"", ")", "# This avoids some nesting in the decorator", "# If called without func the decorator was called with optional args", "# so we'll return a function with those args filled in.", "if", "func", "is", "None", ":", "return", "partial", "(", "depends", ",", "after", "=", "after", ",", "before", "=", "before", ",", "priority", "=", "priority", ")", "def", "self_check", "(", "a", ",", "b", ")", ":", "if", "a", "==", "b", ":", "raise", "ValueError", "(", "\"Test '{}' cannot depend on itself\"", ".", "format", "(", "a", ")", ")", "def", "handle_dep", "(", "conditions", ",", "_before", "=", "True", ")", ":", "if", "conditions", ":", "if", "type", "(", "conditions", ")", "is", "not", "list", ":", "conditions", "=", "[", "conditions", "]", "for", "cond", "in", "conditions", ":", "if", "hasattr", "(", "cond", ",", "'__call__'", ")", ":", "cond", "=", "cond", ".", "__name__", "self_check", "(", "func", ".", "__name__", ",", "cond", ")", "if", "_before", ":", "soft_dependencies", "[", "cond", "]", ".", "add", "(", "func", ".", "__name__", ")", "else", ":", "dependencies", "[", "func", ".", "__name__", "]", ".", "add", "(", "cond", ")", "handle_dep", "(", "before", ")", "handle_dep", "(", "after", ",", "False", ")", "if", "priority", ":", "priorities", "[", "func", ".", "__name__", "]", "=", "priority", "@", "wraps", "(", "func", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "inner" ]
Decorator to specify test dependencies :param after: The test needs to run after this/these tests. String or list of strings. :param before: The test needs to run before this/these tests. String or list of strings.
[ "Decorator", "to", "specify", "test", "dependencies" ]
fd29c95e0e5eb2dbd821f6566b72dfcf42631226
https://github.com/Zitrax/nose-dep/blob/fd29c95e0e5eb2dbd821f6566b72dfcf42631226/nosedep.py#L84-L127
train
Zitrax/nose-dep
nosedep.py
split_on_condition
def split_on_condition(seq, condition): """Split a sequence into two iterables without looping twice""" l1, l2 = tee((condition(item), item) for item in seq) return (i for p, i in l1 if p), (i for p, i in l2 if not p)
python
def split_on_condition(seq, condition): """Split a sequence into two iterables without looping twice""" l1, l2 = tee((condition(item), item) for item in seq) return (i for p, i in l1 if p), (i for p, i in l2 if not p)
[ "def", "split_on_condition", "(", "seq", ",", "condition", ")", ":", "l1", ",", "l2", "=", "tee", "(", "(", "condition", "(", "item", ")", ",", "item", ")", "for", "item", "in", "seq", ")", "return", "(", "i", "for", "p", ",", "i", "in", "l1", "if", "p", ")", ",", "(", "i", "for", "p", ",", "i", "in", "l2", "if", "not", "p", ")" ]
Split a sequence into two iterables without looping twice
[ "Split", "a", "sequence", "into", "two", "iterables", "without", "looping", "twice" ]
fd29c95e0e5eb2dbd821f6566b72dfcf42631226
https://github.com/Zitrax/nose-dep/blob/fd29c95e0e5eb2dbd821f6566b72dfcf42631226/nosedep.py#L195-L198
train
Zitrax/nose-dep
nosedep.py
NoseDep.prepare_suite
def prepare_suite(self, suite): """Prepare suite and determine test ordering""" all_tests = {} for s in suite: m = re.match(r'(\w+)\s+\(.+\)', str(s)) if m: name = m.group(1) else: name = str(s).split('.')[-1] all_tests[name] = s return self.orderTests(all_tests, suite)
python
def prepare_suite(self, suite): """Prepare suite and determine test ordering""" all_tests = {} for s in suite: m = re.match(r'(\w+)\s+\(.+\)', str(s)) if m: name = m.group(1) else: name = str(s).split('.')[-1] all_tests[name] = s return self.orderTests(all_tests, suite)
[ "def", "prepare_suite", "(", "self", ",", "suite", ")", ":", "all_tests", "=", "{", "}", "for", "s", "in", "suite", ":", "m", "=", "re", ".", "match", "(", "r'(\\w+)\\s+\\(.+\\)'", ",", "str", "(", "s", ")", ")", "if", "m", ":", "name", "=", "m", ".", "group", "(", "1", ")", "else", ":", "name", "=", "str", "(", "s", ")", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "all_tests", "[", "name", "]", "=", "s", "return", "self", ".", "orderTests", "(", "all_tests", ",", "suite", ")" ]
Prepare suite and determine test ordering
[ "Prepare", "suite", "and", "determine", "test", "ordering" ]
fd29c95e0e5eb2dbd821f6566b72dfcf42631226
https://github.com/Zitrax/nose-dep/blob/fd29c95e0e5eb2dbd821f6566b72dfcf42631226/nosedep.py#L268-L279
train
Zitrax/nose-dep
nosedep.py
NoseDep.dependency_ran
def dependency_ran(self, test): """Returns an error string if any of the dependencies did not run""" for d in (self.test_name(i) for i in dependencies[test]): if d not in self.ok_results: return "Required test '{}' did not run (does it exist?)".format(d) return None
python
def dependency_ran(self, test): """Returns an error string if any of the dependencies did not run""" for d in (self.test_name(i) for i in dependencies[test]): if d not in self.ok_results: return "Required test '{}' did not run (does it exist?)".format(d) return None
[ "def", "dependency_ran", "(", "self", ",", "test", ")", ":", "for", "d", "in", "(", "self", ".", "test_name", "(", "i", ")", "for", "i", "in", "dependencies", "[", "test", "]", ")", ":", "if", "d", "not", "in", "self", ".", "ok_results", ":", "return", "\"Required test '{}' did not run (does it exist?)\"", ".", "format", "(", "d", ")", "return", "None" ]
Returns an error string if any of the dependencies did not run
[ "Returns", "an", "error", "string", "if", "any", "of", "the", "dependencies", "did", "not", "run" ]
fd29c95e0e5eb2dbd821f6566b72dfcf42631226
https://github.com/Zitrax/nose-dep/blob/fd29c95e0e5eb2dbd821f6566b72dfcf42631226/nosedep.py#L332-L337
train
xflr6/fileconfig
fileconfig/tools.py
class_path
def class_path(cls): """Return the path to the source file of the given class.""" if cls.__module__ == '__main__': path = None else: path = os.path.dirname(inspect.getfile(cls)) if not path: path = os.getcwd() return os.path.realpath(path)
python
def class_path(cls): """Return the path to the source file of the given class.""" if cls.__module__ == '__main__': path = None else: path = os.path.dirname(inspect.getfile(cls)) if not path: path = os.getcwd() return os.path.realpath(path)
[ "def", "class_path", "(", "cls", ")", ":", "if", "cls", ".", "__module__", "==", "'__main__'", ":", "path", "=", "None", "else", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "inspect", ".", "getfile", "(", "cls", ")", ")", "if", "not", "path", ":", "path", "=", "os", ".", "getcwd", "(", ")", "return", "os", ".", "path", ".", "realpath", "(", "path", ")" ]
Return the path to the source file of the given class.
[ "Return", "the", "path", "to", "the", "source", "file", "of", "the", "given", "class", "." ]
473d65f6442eb1ac49ada0b6e56cab45f8018c15
https://github.com/xflr6/fileconfig/blob/473d65f6442eb1ac49ada0b6e56cab45f8018c15/fileconfig/tools.py#L10-L20
train
xflr6/fileconfig
fileconfig/tools.py
caller_path
def caller_path(steps=1): """Return the path to the source file of the current frames' caller.""" frame = sys._getframe(steps + 1) try: path = os.path.dirname(frame.f_code.co_filename) finally: del frame if not path: path = os.getcwd() return os.path.realpath(path)
python
def caller_path(steps=1): """Return the path to the source file of the current frames' caller.""" frame = sys._getframe(steps + 1) try: path = os.path.dirname(frame.f_code.co_filename) finally: del frame if not path: path = os.getcwd() return os.path.realpath(path)
[ "def", "caller_path", "(", "steps", "=", "1", ")", ":", "frame", "=", "sys", ".", "_getframe", "(", "steps", "+", "1", ")", "try", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "frame", ".", "f_code", ".", "co_filename", ")", "finally", ":", "del", "frame", "if", "not", "path", ":", "path", "=", "os", ".", "getcwd", "(", ")", "return", "os", ".", "path", ".", "realpath", "(", "path", ")" ]
Return the path to the source file of the current frames' caller.
[ "Return", "the", "path", "to", "the", "source", "file", "of", "the", "current", "frames", "caller", "." ]
473d65f6442eb1ac49ada0b6e56cab45f8018c15
https://github.com/xflr6/fileconfig/blob/473d65f6442eb1ac49ada0b6e56cab45f8018c15/fileconfig/tools.py#L23-L35
train
viatoriche/microservices
microservices/http/client.py
Resource.resource
def resource(self, *resources): """Resource builder with resources url :param resources: 'one', 'two', 'three' :return: instance of Resource """ resources = tuple(self.resources) + resources return Resource(self.client, resources)
python
def resource(self, *resources): """Resource builder with resources url :param resources: 'one', 'two', 'three' :return: instance of Resource """ resources = tuple(self.resources) + resources return Resource(self.client, resources)
[ "def", "resource", "(", "self", ",", "*", "resources", ")", ":", "resources", "=", "tuple", "(", "self", ".", "resources", ")", "+", "resources", "return", "Resource", "(", "self", ".", "client", ",", "resources", ")" ]
Resource builder with resources url :param resources: 'one', 'two', 'three' :return: instance of Resource
[ "Resource", "builder", "with", "resources", "url" ]
3510563edd15dc6131b8a948d6062856cd904ac7
https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/http/client.py#L57-L64
train
pmuller/versions
versions/constraint.py
Constraint.match
def match(self, version): """Match ``version`` with the constraint. :param version: Version to match against the constraint. :type version: :ref:`version expression <version-expressions>` or \ :class:`.Version` :rtype: ``True`` if ``version`` satisfies the constraint, \ ``False`` if it doesn't. """ if isinstance(version, basestring): version = Version.parse(version) return self.operator(version, self.version)
python
def match(self, version): """Match ``version`` with the constraint. :param version: Version to match against the constraint. :type version: :ref:`version expression <version-expressions>` or \ :class:`.Version` :rtype: ``True`` if ``version`` satisfies the constraint, \ ``False`` if it doesn't. """ if isinstance(version, basestring): version = Version.parse(version) return self.operator(version, self.version)
[ "def", "match", "(", "self", ",", "version", ")", ":", "if", "isinstance", "(", "version", ",", "basestring", ")", ":", "version", "=", "Version", ".", "parse", "(", "version", ")", "return", "self", ".", "operator", "(", "version", ",", "self", ".", "version", ")" ]
Match ``version`` with the constraint. :param version: Version to match against the constraint. :type version: :ref:`version expression <version-expressions>` or \ :class:`.Version` :rtype: ``True`` if ``version`` satisfies the constraint, \ ``False`` if it doesn't.
[ "Match", "version", "with", "the", "constraint", "." ]
951bc3fd99b6a675190f11ee0752af1d7ff5b440
https://github.com/pmuller/versions/blob/951bc3fd99b6a675190f11ee0752af1d7ff5b440/versions/constraint.py#L61-L72
train
ponty/pyavrutils
pyavrutils/cli/arduino/build.py
warnings
def warnings(filename, board='pro', hwpack='arduino', mcu='', f_cpu='', extra_lib='', ver='', # home='auto', backend='arscons', ): ''' build Arduino sketch and display results ''' cc = Arduino( board=board, hwpack=hwpack, mcu=mcu, f_cpu=f_cpu, extra_lib=extra_lib, ver=ver, # home=home, backend=backend, ) cc.build(filename) print 'backend:', cc.backend print 'MCU:', cc.mcu_compiler() # print 'avr-gcc:', AvrGcc().version() print print('=============================================') print('SIZE') print('=============================================') print 'program:', cc.size().program_bytes print 'data:', cc.size().data_bytes core_warnings = [x for x in cc.warnings if 'gcc' in x] + [ x for x in cc.warnings if 'core' in x] lib_warnings = [x for x in cc.warnings if 'lib_' in x] notsketch_warnings = core_warnings + lib_warnings sketch_warnings = [x for x in cc.warnings if x not in notsketch_warnings] print print('=============================================') print('WARNINGS') print('=============================================') print print('core') print('-------------------') print('\n'.join(core_warnings)) print print('lib') print('-------------------') print('\n'.join(lib_warnings)) print print('sketch') print('-------------------') print('\n'.join(sketch_warnings))
python
def warnings(filename, board='pro', hwpack='arduino', mcu='', f_cpu='', extra_lib='', ver='', # home='auto', backend='arscons', ): ''' build Arduino sketch and display results ''' cc = Arduino( board=board, hwpack=hwpack, mcu=mcu, f_cpu=f_cpu, extra_lib=extra_lib, ver=ver, # home=home, backend=backend, ) cc.build(filename) print 'backend:', cc.backend print 'MCU:', cc.mcu_compiler() # print 'avr-gcc:', AvrGcc().version() print print('=============================================') print('SIZE') print('=============================================') print 'program:', cc.size().program_bytes print 'data:', cc.size().data_bytes core_warnings = [x for x in cc.warnings if 'gcc' in x] + [ x for x in cc.warnings if 'core' in x] lib_warnings = [x for x in cc.warnings if 'lib_' in x] notsketch_warnings = core_warnings + lib_warnings sketch_warnings = [x for x in cc.warnings if x not in notsketch_warnings] print print('=============================================') print('WARNINGS') print('=============================================') print print('core') print('-------------------') print('\n'.join(core_warnings)) print print('lib') print('-------------------') print('\n'.join(lib_warnings)) print print('sketch') print('-------------------') print('\n'.join(sketch_warnings))
[ "def", "warnings", "(", "filename", ",", "board", "=", "'pro'", ",", "hwpack", "=", "'arduino'", ",", "mcu", "=", "''", ",", "f_cpu", "=", "''", ",", "extra_lib", "=", "''", ",", "ver", "=", "''", ",", "# home='auto',", "backend", "=", "'arscons'", ",", ")", ":", "cc", "=", "Arduino", "(", "board", "=", "board", ",", "hwpack", "=", "hwpack", ",", "mcu", "=", "mcu", ",", "f_cpu", "=", "f_cpu", ",", "extra_lib", "=", "extra_lib", ",", "ver", "=", "ver", ",", "# home=home,", "backend", "=", "backend", ",", ")", "cc", ".", "build", "(", "filename", ")", "print", "'backend:'", ",", "cc", ".", "backend", "print", "'MCU:'", ",", "cc", ".", "mcu_compiler", "(", ")", "# print 'avr-gcc:', AvrGcc().version()", "print", "print", "(", "'============================================='", ")", "print", "(", "'SIZE'", ")", "print", "(", "'============================================='", ")", "print", "'program:'", ",", "cc", ".", "size", "(", ")", ".", "program_bytes", "print", "'data:'", ",", "cc", ".", "size", "(", ")", ".", "data_bytes", "core_warnings", "=", "[", "x", "for", "x", "in", "cc", ".", "warnings", "if", "'gcc'", "in", "x", "]", "+", "[", "x", "for", "x", "in", "cc", ".", "warnings", "if", "'core'", "in", "x", "]", "lib_warnings", "=", "[", "x", "for", "x", "in", "cc", ".", "warnings", "if", "'lib_'", "in", "x", "]", "notsketch_warnings", "=", "core_warnings", "+", "lib_warnings", "sketch_warnings", "=", "[", "x", "for", "x", "in", "cc", ".", "warnings", "if", "x", "not", "in", "notsketch_warnings", "]", "print", "print", "(", "'============================================='", ")", "print", "(", "'WARNINGS'", ")", "print", "(", "'============================================='", ")", "print", "print", "(", "'core'", ")", "print", "(", "'-------------------'", ")", "print", "(", "'\\n'", ".", "join", "(", "core_warnings", ")", ")", "print", "print", "(", "'lib'", ")", "print", "(", "'-------------------'", ")", "print", "(", "'\\n'", ".", "join", "(", "lib_warnings", ")", ")", "print", "print", "(", "'sketch'", ")", "print", "(", "'-------------------'", ")", "print", "(", "'\\n'", ".", "join", "(", "sketch_warnings", ")", ")" ]
build Arduino sketch and display results
[ "build", "Arduino", "sketch", "and", "display", "results" ]
7a396a25b3ac076ede07b5cd5cbd416ebb578a28
https://github.com/ponty/pyavrutils/blob/7a396a25b3ac076ede07b5cd5cbd416ebb578a28/pyavrutils/cli/arduino/build.py#L7-L64
train
bitesofcode/projexui
projexui/dialogs/xshortcutdialog/xshortcutdialog.py
XShortcutDialog.accept
def accept( self ): """ Saves the current settings for the actions in the list and exits the dialog. """ if ( not self.save() ): return for i in range(self.uiActionTREE.topLevelItemCount()): item = self.uiActionTREE.topLevelItem(i) action = item.action() action.setShortcut( QKeySequence(item.text(1)) ) super(XShortcutDialog, self).accept()
python
def accept( self ): """ Saves the current settings for the actions in the list and exits the dialog. """ if ( not self.save() ): return for i in range(self.uiActionTREE.topLevelItemCount()): item = self.uiActionTREE.topLevelItem(i) action = item.action() action.setShortcut( QKeySequence(item.text(1)) ) super(XShortcutDialog, self).accept()
[ "def", "accept", "(", "self", ")", ":", "if", "(", "not", "self", ".", "save", "(", ")", ")", ":", "return", "for", "i", "in", "range", "(", "self", ".", "uiActionTREE", ".", "topLevelItemCount", "(", ")", ")", ":", "item", "=", "self", ".", "uiActionTREE", ".", "topLevelItem", "(", "i", ")", "action", "=", "item", ".", "action", "(", ")", "action", ".", "setShortcut", "(", "QKeySequence", "(", "item", ".", "text", "(", "1", ")", ")", ")", "super", "(", "XShortcutDialog", ",", "self", ")", ".", "accept", "(", ")" ]
Saves the current settings for the actions in the list and exits the dialog.
[ "Saves", "the", "current", "settings", "for", "the", "actions", "in", "the", "list", "and", "exits", "the", "dialog", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xshortcutdialog/xshortcutdialog.py#L77-L90
train
bitesofcode/projexui
projexui/dialogs/xshortcutdialog/xshortcutdialog.py
XShortcutDialog.clear
def clear( self ): """ Clears the current settings for the current action. """ item = self.uiActionTREE.currentItem() if ( not item ): return self.uiShortcutTXT.setText('') item.setText(1, '')
python
def clear( self ): """ Clears the current settings for the current action. """ item = self.uiActionTREE.currentItem() if ( not item ): return self.uiShortcutTXT.setText('') item.setText(1, '')
[ "def", "clear", "(", "self", ")", ":", "item", "=", "self", ".", "uiActionTREE", ".", "currentItem", "(", ")", "if", "(", "not", "item", ")", ":", "return", "self", ".", "uiShortcutTXT", ".", "setText", "(", "''", ")", "item", ".", "setText", "(", "1", ",", "''", ")" ]
Clears the current settings for the current action.
[ "Clears", "the", "current", "settings", "for", "the", "current", "action", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xshortcutdialog/xshortcutdialog.py#L103-L112
train
bitesofcode/projexui
projexui/dialogs/xshortcutdialog/xshortcutdialog.py
XShortcutDialog.updateAction
def updateAction( self ): """ Updates the action to edit based on the current item. """ item = self.uiActionTREE.currentItem() if ( item ): action = item.action() else: action = QAction() self.uiShortcutTXT.setText(action.shortcut().toString())
python
def updateAction( self ): """ Updates the action to edit based on the current item. """ item = self.uiActionTREE.currentItem() if ( item ): action = item.action() else: action = QAction() self.uiShortcutTXT.setText(action.shortcut().toString())
[ "def", "updateAction", "(", "self", ")", ":", "item", "=", "self", ".", "uiActionTREE", ".", "currentItem", "(", ")", "if", "(", "item", ")", ":", "action", "=", "item", ".", "action", "(", ")", "else", ":", "action", "=", "QAction", "(", ")", "self", ".", "uiShortcutTXT", ".", "setText", "(", "action", ".", "shortcut", "(", ")", ".", "toString", "(", ")", ")" ]
Updates the action to edit based on the current item.
[ "Updates", "the", "action", "to", "edit", "based", "on", "the", "current", "item", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xshortcutdialog/xshortcutdialog.py#L181-L191
train
damnit/pymite
pymite/utils.py
declassify
def declassify(to_remove, *args, **kwargs): """ flatten the return values of the mite api. """ def argdecorate(fn): """ enable the to_remove argument to the decorator. """ # wrap the function to get the original docstring @wraps(fn) def declassed(*args, **kwargs): # call the method ret = fn(*args, **kwargs) # catch errors that are thrown by the api try: # ensure that ret is a list if type(ret) is list: return [r[to_remove] for r in ret] return ret[to_remove] except KeyError: return ret return declassed return argdecorate
python
def declassify(to_remove, *args, **kwargs): """ flatten the return values of the mite api. """ def argdecorate(fn): """ enable the to_remove argument to the decorator. """ # wrap the function to get the original docstring @wraps(fn) def declassed(*args, **kwargs): # call the method ret = fn(*args, **kwargs) # catch errors that are thrown by the api try: # ensure that ret is a list if type(ret) is list: return [r[to_remove] for r in ret] return ret[to_remove] except KeyError: return ret return declassed return argdecorate
[ "def", "declassify", "(", "to_remove", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "argdecorate", "(", "fn", ")", ":", "\"\"\" enable the to_remove argument to the decorator. \"\"\"", "# wrap the function to get the original docstring", "@", "wraps", "(", "fn", ")", "def", "declassed", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# call the method", "ret", "=", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# catch errors that are thrown by the api", "try", ":", "# ensure that ret is a list", "if", "type", "(", "ret", ")", "is", "list", ":", "return", "[", "r", "[", "to_remove", "]", "for", "r", "in", "ret", "]", "return", "ret", "[", "to_remove", "]", "except", "KeyError", ":", "return", "ret", "return", "declassed", "return", "argdecorate" ]
flatten the return values of the mite api.
[ "flatten", "the", "return", "values", "of", "the", "mite", "api", "." ]
1e9b9bf6aef790af2d8781f9f77c098c54ca0342
https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/utils.py#L13-L32
train
damnit/pymite
pymite/utils.py
clean_dict
def clean_dict(d): """ remove the keys with None values. """ ktd = list() for k, v in d.items(): if not v: ktd.append(k) elif type(v) is dict: d[k] = clean_dict(v) for k in ktd: d.pop(k) return d
python
def clean_dict(d): """ remove the keys with None values. """ ktd = list() for k, v in d.items(): if not v: ktd.append(k) elif type(v) is dict: d[k] = clean_dict(v) for k in ktd: d.pop(k) return d
[ "def", "clean_dict", "(", "d", ")", ":", "ktd", "=", "list", "(", ")", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "not", "v", ":", "ktd", ".", "append", "(", "k", ")", "elif", "type", "(", "v", ")", "is", "dict", ":", "d", "[", "k", "]", "=", "clean_dict", "(", "v", ")", "for", "k", "in", "ktd", ":", "d", ".", "pop", "(", "k", ")", "return", "d" ]
remove the keys with None values.
[ "remove", "the", "keys", "with", "None", "values", "." ]
1e9b9bf6aef790af2d8781f9f77c098c54ca0342
https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/utils.py#L35-L45
train
bitesofcode/projexui
projexui/widgets/xorbcolumnnavigator.py
XOrbColumnItem.load
def load(self): """ Loads the children for this item. """ if self._loaded: return self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless) self._loaded = True column = self.schemaColumn() if not column.isReference(): return ref = column.referenceModel() if not ref: return columns = sorted(ref.schema().columns(), key=lambda x: x.name().strip('_')) for column in columns: XOrbColumnItem(self, column)
python
def load(self): """ Loads the children for this item. """ if self._loaded: return self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless) self._loaded = True column = self.schemaColumn() if not column.isReference(): return ref = column.referenceModel() if not ref: return columns = sorted(ref.schema().columns(), key=lambda x: x.name().strip('_')) for column in columns: XOrbColumnItem(self, column)
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "_loaded", ":", "return", "self", ".", "setChildIndicatorPolicy", "(", "self", ".", "DontShowIndicatorWhenChildless", ")", "self", ".", "_loaded", "=", "True", "column", "=", "self", ".", "schemaColumn", "(", ")", "if", "not", "column", ".", "isReference", "(", ")", ":", "return", "ref", "=", "column", ".", "referenceModel", "(", ")", "if", "not", "ref", ":", "return", "columns", "=", "sorted", "(", "ref", ".", "schema", "(", ")", ".", "columns", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", "(", ")", ".", "strip", "(", "'_'", ")", ")", "for", "column", "in", "columns", ":", "XOrbColumnItem", "(", "self", ",", "column", ")" ]
Loads the children for this item.
[ "Loads", "the", "children", "for", "this", "item", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbcolumnnavigator.py#L49-L70
train
bitesofcode/projexui
projexui/widgets/xorbcolumnnavigator.py
XOrbColumnNavigator.refresh
def refresh(self): """ Resets the data for this navigator. """ self.setUpdatesEnabled(False) self.blockSignals(True) self.clear() tableType = self.tableType() if not tableType: self.setUpdatesEnabled(True) self.blockSignals(False) return schema = tableType.schema() columns = list(sorted(schema.columns(), key=lambda x: x.name().strip('_'))) for column in columns: XOrbColumnItem(self, column) self.setUpdatesEnabled(True) self.blockSignals(False)
python
def refresh(self): """ Resets the data for this navigator. """ self.setUpdatesEnabled(False) self.blockSignals(True) self.clear() tableType = self.tableType() if not tableType: self.setUpdatesEnabled(True) self.blockSignals(False) return schema = tableType.schema() columns = list(sorted(schema.columns(), key=lambda x: x.name().strip('_'))) for column in columns: XOrbColumnItem(self, column) self.setUpdatesEnabled(True) self.blockSignals(False)
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "setUpdatesEnabled", "(", "False", ")", "self", ".", "blockSignals", "(", "True", ")", "self", ".", "clear", "(", ")", "tableType", "=", "self", ".", "tableType", "(", ")", "if", "not", "tableType", ":", "self", ".", "setUpdatesEnabled", "(", "True", ")", "self", ".", "blockSignals", "(", "False", ")", "return", "schema", "=", "tableType", ".", "schema", "(", ")", "columns", "=", "list", "(", "sorted", "(", "schema", ".", "columns", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", "(", ")", ".", "strip", "(", "'_'", ")", ")", ")", "for", "column", "in", "columns", ":", "XOrbColumnItem", "(", "self", ",", "column", ")", "self", ".", "setUpdatesEnabled", "(", "True", ")", "self", ".", "blockSignals", "(", "False", ")" ]
Resets the data for this navigator.
[ "Resets", "the", "data", "for", "this", "navigator", "." ]
f18a73bec84df90b034ca69b9deea118dbedfc4d
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbcolumnnavigator.py#L185-L205
train