function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def __truediv__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__(default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)}) else: raise TypeError('%(class)s must be divided by a number' % {"class": pretty_name(self)})
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png']
kklmn/xrt
[ 63, 24, 63, 54, 1459267067 ]
def after():
kklmn/xrt
[ 63, 24, 63, 54, 1459267067 ]
def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link
compsoc-ssc/compsocssc
[ 5, 3, 5, 3, 1423901148 ]
def __str__(self): warnings.warn('''You are using a "General Variable". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name
compsoc-ssc/compsocssc
[ 5, 3, 5, 3, 1423901148 ]
def __init__(self, title): self._ax = None self.cax = None self.title = title
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def _plot(self, region=None, **kwargs): raise NotImplementedError("Subclasses need to override _plot function")
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def plot(self, region=None, **kwargs): raise NotImplementedError("Subclasses need to override plot function")
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def fig(self): return self._ax.figure
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def ax(self): if not self._ax: _, self._ax = plt.subplots() return self._ax
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def ax(self, value): self._ax = value
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, chromosome, display_scale=True): """ :param chromosome: :class:`~kaic.data.genomic.GenomicRegion` or string :param display_scale: Boolean Display distance scale at bottom right """ if isinstance(chromosome, GenomicRegion): self.chromosome = chromosome.chromosome else: self.chromosome = chromosome self.display_scale = display_scale
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __call__(self, x, pos=None): """ Return label for tick at coordinate x. Relative position of ticks can be specified with pos. First tick gets chromosome name. """ s = self._format_val(x, prec_offset=1) if pos == 0 or x == 0: return "{}:{}".format(self.chromosome, s) return s
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __call__(self): vmin, vmax = self.axis.get_view_interval() ticks = self.tick_values(vmin, vmax) # Make sure that first and last tick are the start # and the end of the genomic range plotted. If next # ticks are too close, remove them. ticks[0] = vmin ticks[-1] = vmax if ticks[1] - vmin < (vmax - vmin)/(self._nbins*3): ticks = np.delete(ticks, 1) if vmax - ticks[-2] < (vmax - vmin)/(self._nbins*3): ticks = np.delete(ticks, -2) return self.raise_if_exceeds(np.array(ticks))
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, n): self.ndivs = n
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, title): BasePlotter.__init__(self, title=title)
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def prepare_normalization(norm="lin", vmin=None, vmax=None): if isinstance(norm, mpl.colors.Normalize): norm.vmin = vmin norm.vmax = vmax return norm if norm == "log": return mpl.colors.LogNorm(vmin=vmin, vmax=vmax) elif norm == "lin": return mpl.colors.Normalize(vmin=vmin, vmax=vmax) else: raise ValueError("'{}'' not a valid normalization method.".format(norm))
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, hic_matrix, regions=None, colormap='RdBu', norm="log", vmin=None, vmax=None, show_colorbar=True, blend_masked=False): if regions is None: for i in range(hic_matrix.shape[0]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions self.hic_matrix = hic_matrix self.colormap = copy.copy(mpl.cm.get_cmap(colormap)) if blend_masked: self.colormap.set_bad(self.colormap(0)) self._vmin = vmin self._vmax = vmax self.norm = prepare_normalization(norm=norm, vmin=vmin, vmax=vmax) self.colorbar = None self.slider = None self.show_colorbar = show_colorbar
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def vmin(self): return self._vmin if self._vmin else np.nanmin(self.hic_matrix)
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def vmax(self): return self._vmax if self._vmax else np.nanmax(self.hic_matrix)
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, hic_matrix, regions=None, title='', colormap='viridis', max_dist=None, norm="log", vmin=None, vmax=None, show_colorbar=True, blend_masked=False): BasePlotter1D.__init__(self, title=title) BasePlotterHic.__init__(self, hic_matrix, regions=regions, colormap=colormap, vmin=vmin, vmax=vmax, show_colorbar=show_colorbar, norm=norm, blend_masked=blend_masked) self.max_dist = max_dist self.hicmesh = None
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def set_clim(self, vmin, vmax): self.hicmesh.set_clim(vmin=vmin, vmax=vmax) if self.colorbar is not None: self.colorbar.vmin = vmin self.colorbar.vmax = vmax self.colorbar.draw_all()
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, data, window_sizes=None, regions=None, title='', midpoint=None, colormap='coolwarm_r', vmax=None, current_window_size=0, log_y=True): if regions is None: regions = [] for i in range(data.shape[1]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions BasePlotter1D.__init__(self, title=title) self.da = data if window_sizes is None: window_sizes = [] try: l = len(data) except TypeError: l = data.shape[0] for i in range(l): window_sizes.append(i) self.window_sizes = window_sizes self.colormap = colormap self.midpoint = midpoint self.mesh = None self.vmax = vmax self.window_size_line = None self.current_window_size = current_window_size self.log_y = log_y
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def set_clim(self, vmin, vmax): self.mesh.set_clim(vmin=vmin, vmax=vmax) if self.colorbar is not None: self.colorbar.vmin = vmin self.colorbar.vmax = vmax self.colorbar.draw_all()
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, regions, title='', color='black'): BasePlotter1D.__init__(self, title=title) self.regions = regions self.color = color self.current_region = None
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def update(self, regions): self.regions = regions self.ax.cla() self.plot(region=self.current_region, ax=self.ax)
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, data, regions=None, title='', init_row=0, is_symmetric=False): BasePlotter1D.__init__(self, title=title) if regions is None: regions = [] for i in range(len(data)): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.init_row = init_row self.data = data self.sr = None self.da_sub = None self.regions = regions self.current_region = None self.line = None self.current_ix = init_row self.current_cutoff = None self.cutoff_line = None self.cutoff_line_mirror = None self.is_symmetric = is_symmetric
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def _plot(self, region=None, cax=None): self._new_region(region) bin_coords = [(x.start - 1) for x in self.sr] ds = self.da_sub[self.init_row] self.line, = self.ax.plot(bin_coords, ds) if not self.is_symmetric: self.current_cutoff = (self.ax.get_ylim()[1] - self.ax.get_ylim()[0]) / 2 + self.ax.get_ylim()[0] else: self.current_cutoff = self.ax.get_ylim()[1]/ 2 self.ax.axhline(0.0, linestyle='dashed', color='grey') self.cutoff_line = self.ax.axhline(self.current_cutoff, color='r') if self.is_symmetric: self.cutoff_line_mirror = self.ax.axhline(-1*self.current_cutoff, color='r') self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds)))
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def __init__(self, hic_matrix, regions=None, data=None, window_sizes=None, norm='lin', max_dist=3000000, max_percentile=99.99, algorithm='insulation', matrix_colormap=None, data_colormap=None, log_data=True): self.hic_matrix = hic_matrix if regions is None: regions = [] for i in range(hic_matrix.shape[0]): regions.append(GenomicRegion(chromosome='', start=i, end=i)) self.regions = regions self.norm = norm self.fig = None self.max_dist = max_dist self.algorithm = algorithm self.svmax = None self.min_value = np.nanmin(self.hic_matrix[np.nonzero(self.hic_matrix)]) self.min_value_data = None self.hic_plot = None self.tad_plot = None self.data_plot = None self.line_plot = None self.sdata = None self.data_ax = None self.line_ax = None self.da = None self.ws = None self.current_window_size = None self.window_size_text = None self.tad_cutoff_text = None self.max_percentile = max_percentile self.tad_regions = None self.current_da_ix = None self.button_save_tads = None self.button_save_vector = None self.button_save_matrix = None self.log_data = log_data if algorithm == 'insulation': self.tad_algorithm = insulation_index self.tad_calling_algorithm = call_tads_insulation_index self.is_symmetric = False if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = 'plasma' elif algorithm == 'ninsulation': self.tad_algorithm = normalised_insulation_index self.tad_calling_algorithm = call_tads_insulation_index self.is_symmetric = True if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = LinearSegmentedColormap.from_list('myreds', ['blue', 'white', 'red']) elif algorithm == 'directionality': self.tad_algorithm = directionality_index self.tad_calling_algorithm = call_tads_directionality_index self.is_symmetric = True if matrix_colormap is None: self.matrix_colormap = LinearSegmentedColormap.from_list('myreds', ['white', 'red']) if data_colormap is None: self.data_plot_color = LinearSegmentedColormap.from_list('myreds', ['blue', 'white', 'red']) if data is None: self.da, self.ws = data_array(hic_matrix=self.hic_matrix, regions=self.regions, tad_method=self.tad_algorithm, window_sizes=window_sizes) else: self.da = data if window_sizes is None: raise ValueError("window_sizes parameter cannot be None when providing data!") self.ws = window_sizes
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def data_slider_update(self, val): if self.is_symmetric: self.data_plot.set_clim(-1*val, val) else: self.data_plot.set_clim(self.min_value_data, val)
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def on_click_save_vector(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: da_sub = self.da[self.current_da_ix] with open(save_path, 'w') as o: for i, region in enumerate(self.regions): o.write("%s\t%d\t%d\t.\t%e\n" % (region.chromosome, region.start-1, region.end, da_sub[i]))
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def plot(self, region=None): # set up plotting grid self.fig = plt.figure(figsize=(10, 10)) # main plots grid_size = (32, 15) hic_vmax_slider_ax = plt.subplot2grid(grid_size, (0, 0), colspan=13) hic_ax = plt.subplot2grid(grid_size, (1, 0), rowspan=9, colspan=13) hp_cax = plt.subplot2grid(grid_size, (1, 14), rowspan=9, colspan=1) tad_ax = plt.subplot2grid(grid_size, (10, 0), rowspan=1, colspan=13, sharex=hic_ax) line_ax = plt.subplot2grid(grid_size, (12, 0), rowspan=6, colspan=13, sharex=hic_ax) line_cax = plt.subplot2grid(grid_size, (12, 13), rowspan=6, colspan=2) data_vmax_slider_ax = plt.subplot2grid(grid_size, (19, 0), colspan=13) data_ax = plt.subplot2grid(grid_size, (20, 0), rowspan=9, colspan=13, sharex=hic_ax) da_cax = plt.subplot2grid(grid_size, (20, 14), rowspan=9, colspan=1) # buttons save_tads_ax = plt.subplot2grid(grid_size, (31, 0), rowspan=1, colspan=4) self.button_save_tads = Button(save_tads_ax, 'Save TADs') self.button_save_tads.on_clicked(self.on_click_save_tads) save_vector_ax = plt.subplot2grid(grid_size, (31, 5), rowspan=1, colspan=4) self.button_save_vector = Button(save_vector_ax, 'Save current values') self.button_save_vector.on_clicked(self.on_click_save_vector) save_matrix_ax = plt.subplot2grid(grid_size, (31, 10), rowspan=1, colspan=4) self.button_save_matrix = Button(save_matrix_ax, 'Save matrix') self.button_save_matrix.on_clicked(self.on_click_save_matrix) # add subplot content max_value = np.nanpercentile(self.hic_matrix, self.max_percentile) init_value = .2*max_value # HI-C VMAX SLIDER self.svmax = Slider(hic_vmax_slider_ax, 'vmax', self.min_value, max_value, valinit=init_value, color='grey') self.svmax.on_changed(self.vmax_slider_update) # HI-C self.hic_plot = HicPlot(self.hic_matrix, self.regions, max_dist=self.max_dist, norm=self.norm, vmax=init_value, vmin=self.min_value, colormap=self.matrix_colormap) self.hic_plot.plot(region, ax=hic_ax, cax=hp_cax) # generate data array self.min_value_data = np.nanmin(self.da[np.nonzero(self.da)]) max_value_data = np.nanpercentile(self.da, self.max_percentile) init_value_data = .5*max_value_data # LINE PLOT da_ix = int(self.da.shape[0]/2) self.current_da_ix = da_ix self.line_plot = DataLinePlot(self.da, regions=self.regions, init_row=da_ix, is_symmetric=self.is_symmetric) self.line_plot.plot(region, ax=line_ax) self.line_ax = line_ax # line info self.current_window_size = self.ws[da_ix] line_cax.text(.1, .8, 'Window size', fontweight='bold') self.window_size_text = line_cax.text(.3, .6, str(self.current_window_size)) line_cax.text(.1, .4, 'TAD cutoff', fontweight='bold') self.tad_cutoff_text = line_cax.text(.3, .2, "%.5f" % self.line_plot.current_cutoff) line_cax.axis('off') # TAD PLOT self.tad_regions = self.tad_calling_algorithm(self.da[da_ix], self.line_plot.current_cutoff, self.regions) self.tad_plot = TADPlot(self.tad_regions) self.tad_plot.plot(region=region, ax=tad_ax) # DATA ARRAY self.data_plot = DataArrayPlot(self.da, self.ws, self.regions, vmax=init_value_data, colormap=self.data_plot_color, current_window_size=self.ws[da_ix], log_y=self.log_data) self.data_plot.plot(region, ax=data_ax, cax=da_cax) # DATA ARRAY SLIDER if self.is_symmetric: self.sdata = Slider(data_vmax_slider_ax, 'vmax', 0.0, max_value_data, valinit=init_value_data, color='grey') else: self.sdata = Slider(data_vmax_slider_ax, 'vmax', self.min_value_data, max_value_data, valinit=init_value_data, color='grey') self.sdata.on_changed(self.data_slider_update) self.data_slider_update(init_value_data) # clean up hic_ax.xaxis.set_visible(False) line_ax.xaxis.set_visible(False) # enable hover self.data_ax = data_ax cid = self.fig.canvas.mpl_connect('button_press_event', self.on_click) return self.fig, (hic_vmax_slider_ax, hic_ax, line_ax, data_ax, hp_cax, da_cax)
vaquerizaslab/tadtool
[ 36, 12, 36, 7, 1459337414 ]
def _get_override_format(self): return 'JAVA_HOME="%s"'
louisq/staticguru
[ 2, 3, 2, 28, 1475196616 ]
def gauss2(fwhm, length):
sevenian3/ChromaStarPy
[ 9, 2, 9, 2, 1494513781 ]
def __init__(self): self.var = 0
github/codeql
[ 5783, 1304, 5783, 842, 1533054951 ]
def __init__(self): self.var = 1 # self.var will be overwritten C.__init__(self)
github/codeql
[ 5783, 1304, 5783, 842, 1533054951 ]
def __init__(self): self.var = 0 # self.var will be overwritten
github/codeql
[ 5783, 1304, 5783, 842, 1533054951 ]
def connect (): ''' Create the connection to the MongoDB and create 3 collections needed ''' try: # Create the connection to the local host conn = pymongo.MongoClient() print 'MongoDB Connection Successful' except pymongo.errors.ConnectionFailure, err: print 'MongoDB Connection Unsuccessful' return False
Macemann/Georgetown-Capstone
[ 3, 4, 3, 1, 1418008428 ]
def dist(a, b): return sum((i-j)**2 for i, j in zip(a, b))
Ginfung/FSSE
[ 3, 1, 3, 1, 1485895757 ]
def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str']
Trust-Code/python-cnab
[ 30, 48, 30, 9, 1474976091 ]
def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13'))
Trust-Code/python-cnab
[ 30, 48, 30, 9, 1474976091 ]
def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5)
Trust-Code/python-cnab
[ 30, 48, 30, 9, 1474976091 ]
def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy')
Trust-Code/python-cnab
[ 30, 48, 30, 9, 1474976091 ]
def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario())
Trust-Code/python-cnab
[ 30, 48, 30, 9, 1474976091 ]
def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str)
Trust-Code/python-cnab
[ 30, 48, 30, 9, 1474976091 ]
def __enter__(self): """ Syntax sugar which helps in celery tasks, cron jobs, and other scripts Usage: with Tenant.objects.get(schema_name='test') as tenant: # run some code in tenant test # run some code in previous tenant (public probably) """ connection = connections[get_tenant_database_alias()] self._previous_tenant.append(connection.tenant) self.activate() return self
tomturner/django-tenants
[ 1060, 273, 1060, 178, 1433879339 ]
def activate(self): """ Syntax sugar that helps at django shell with fast tenant changing Usage: Tenant.objects.get(schema_name='test').activate() """ connection = connections[get_tenant_database_alias()] connection.set_tenant(self)
tomturner/django-tenants
[ 1060, 273, 1060, 178, 1433879339 ]
def deactivate(cls): """ Syntax sugar, return to public schema Usage: test_tenant.deactivate() # or simpler Tenant.deactivate() """ connection = connections[get_tenant_database_alias()] connection.set_schema_to_public()
tomturner/django-tenants
[ 1060, 273, 1060, 178, 1433879339 ]
def serializable_fields(self): """ in certain cases the user model isn't serializable so you may want to only send the id """ return self
tomturner/django-tenants
[ 1060, 273, 1060, 178, 1433879339 ]
def pre_drop(self): """ This is a routine which you could override to backup the tenant schema before dropping. :return: """
tomturner/django-tenants
[ 1060, 273, 1060, 178, 1433879339 ]
def create_schema(self, check_if_exists=False, sync_schema=True, verbosity=1): """ Creates the schema 'schema_name' for this tenant. Optionally checks if the schema already exists before creating it. Returns true if the schema was created, false otherwise. """ # safety check connection = connections[get_tenant_database_alias()] _check_schema_name(self.schema_name) cursor = connection.cursor() if check_if_exists and schema_exists(self.schema_name): return False fake_migrations = get_creation_fakes_migrations() if sync_schema: if fake_migrations: # copy tables and data from provided model schema base_schema = get_tenant_base_schema() clone_schema = CloneSchema() clone_schema.clone_schema(base_schema, self.schema_name) call_command('migrate_schemas', tenant=True, fake=True, schema_name=self.schema_name, interactive=False, verbosity=verbosity) else: # create the schema cursor.execute('CREATE SCHEMA "%s"' % self.schema_name) call_command('migrate_schemas', tenant=True, schema_name=self.schema_name, interactive=False, verbosity=verbosity) connection.set_schema_to_public()
tomturner/django-tenants
[ 1060, 273, 1060, 178, 1433879339 ]
def reverse(self, request, view_name): """ Returns the URL of this tenant. """ http_type = 'https://' if request.is_secure() else 'http://' domain = get_current_site(request).domain url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name))) return url
tomturner/django-tenants
[ 1060, 273, 1060, 178, 1433879339 ]
def save(self, *args, **kwargs): # Get all other primary domains with the same tenant domain_list = self.__class__.objects.filter(tenant=self.tenant, is_primary=True).exclude(pk=self.pk) # If we have no primary domain yet, set as primary domain by default self.is_primary = self.is_primary or (not domain_list.exists()) if self.is_primary: # Remove primary status of existing domains for tenant domain_list.update(is_primary=False) super().save(*args, **kwargs)
tomturner/django-tenants
[ 1060, 273, 1060, 178, 1433879339 ]
def admin_users_page(): return render_template( 'admin_users.html', initial_date=datetime.now().isoformat(), # now, in server's time zone initial_period_start=current_period_start().isoformat(), period_duration=config['period_duration'], lock_date=config['lock_date'], )
justinbot/timecard
[ 2, 1, 2, 20, 1482543058 ]
def make_new_rsa_key_weak(bits): return RSA.generate(bits) # NOT OK
github/codeql
[ 5783, 1304, 5783, 842, 1533054951 ]
def make_new_rsa_key_strong(bits): return RSA.generate(bits) # OK
github/codeql
[ 5783, 1304, 5783, 842, 1533054951 ]
def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == openapi_schema
tiangolo/fastapi
[ 55302, 4581, 55302, 474, 1544257307 ]
def test_post_form_no_body(): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == file_required
tiangolo/fastapi
[ 55302, 4581, 55302, 474, 1544257307 ]
def test_post_file(tmp_path): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14}
tiangolo/fastapi
[ 55302, 4581, 55302, 474, 1544257307 ]
def stream(): csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8') return six.StringIO(csv)
katakumpo/nicedjango
[ 2, 1, 2, 1, 1414873038 ]
def test_reader_none(stream): r = CsvReader(stream, replacements=(), preserve_quotes=True, replace_digits=False) assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
katakumpo/nicedjango
[ 2, 1, 2, 1, 1414873038 ]
def test_reader_replace(stream): r = CsvReader(stream, replace_digits=False) assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']]
katakumpo/nicedjango
[ 2, 1, 2, 1, 1414873038 ]
def cube_func(cube): return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods))
ioos/comt
[ 1, 7, 1, 16, 1401373926 ]
def get_mesh(cube, url): ug = pyugrid.UGrid.from_ncfile(url) cube.mesh = ug cube.mesh_dimension = 1 return cube
ioos/comt
[ 1, 7, 1, 16, 1401373926 ]
def get_triang(cube): lon = cube.mesh.nodes[:, 0] lat = cube.mesh.nodes[:, 1] nv = cube.mesh.faces return tri.Triangulation(lon, lat, triangles=nv)
ioos/comt
[ 1, 7, 1, 16, 1401373926 ]
def plot_model(model): cube = cubes[model] lon = cube.mesh.nodes[:, 0] lat = cube.mesh.nodes[:, 1] ind = -1 # just take the last time index for now zcube = cube[ind] triang = tris[model] fig, ax = plt.subplots(figsize=(7, 7), subplot_kw=dict(projection=ccrs.PlateCarree())) ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()]) ax.coastlines() levs = np.arange(-1, 5, 0.2) cs = ax.tricontourf(triang, zcube.data, levels=levs) fig.colorbar(cs) ax.tricontour(triang, zcube.data, colors='k',levels=levs) tvar = cube.coord('time') tstr = tvar.units.num2date(tvar.points[ind]) gl = ax.gridlines(draw_labels=True) gl.xlabels_top = gl.ylabels_right = False title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr)) return fig, ax
ioos/comt
[ 1, 7, 1, 16, 1401373926 ]
def acquire_single_linear_frequency_span(file_name, start_freq=None, stop_freq=None, center_freq=None, span=None, nr_avg=1, sweep_mode='auto', nbr_points=101, power=-20, bandwidth=100, measure='S21', options_dict=None): """ Acquires a single trace from the VNA. Inputs: file_name (str), name of the output file. start_freq (float), starting frequency of the trace. stop_freq (float), stoping frequency of the trace. center_freq (float), central frequency of the trace. span (float), span of the trace. nbr_points (int), Number of points within the trace. power (float), power in dBm. bandwidth (float), bandwidth in Hz. measure (str), scattering parameter to measure (ie. 'S21'). Output: NONE Beware that start/stop and center/span are just two ways of configuring the same thing. """ # set VNA sweep function if start_freq != None and stop_freq != None: MC_instr.set_sweep_function(swf.ZNB_VNA_sweep(VNA_instr, start_freq=start_freq, stop_freq=stop_freq, npts=nbr_points, force_reset=True)) elif center_freq != None and span != None: MC_instr.set_sweep_function(swf.ZNB_VNA_sweep(VNA_instr, center_freq=center_freq, span=span, npts=nbr_points, force_reset=True)) # set VNA detector function MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr)) # VNA settings # VNA_instr.average_state('off') VNA_instr.bandwidth(bandwidth) # hack to measure S parameters different from S21 str_to_write = "calc:par:meas 'trc1', '%s'" % measure print(str_to_write) VNA_instr.visa_handle.write(str_to_write) VNA_instr.avg(nr_avg) VNA_instr.number_sweeps_all(nr_avg) VNA_instr.average_mode(sweep_mode) VNA_instr.power(power) VNA_instr.timeout(10**4) t_start = ma.a_tools.current_timestamp() MC_instr.run(name=file_name) t_stop = ma.a_tools.current_timestamp() t_meas = ma.a_tools.get_timestamps_in_range(t_start, t_stop, label=file_name) assert len(t_meas) == 1, "Multiple timestamps found for this measurement" t_meas = t_meas[0] # ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger') # ma.VNA_analysis(auto=True, label=file_name) ma2.VNA_analysis(auto=True, t_start=None, options_dict=options_dict)
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def acquire_linear_frequency_span_vs_power(file_name, start_freq=None, stop_freq=None, center_freq=None, start_power=None, stop_power=None, step_power=2, span=None, nbr_points=101, bandwidth=100, measure='S21'): """ Acquires a single trace from the VNA. Inputs: file_name (str), name of the output file. start_freq (float), starting frequency of the trace. stop_freq (float), stoping frequency of the trace. center_freq (float), central frequency of the trace. span (float), span of the trace. nbr_points (int), Number of points within the trace. start_power, stop_power, step_power (float), power range in dBm. bandwidth (float), bandwidth in Hz. measure (str), scattering parameter to measure (ie. 'S21'). Output: NONE Beware that start/stop and center/span are just two ways of configuring the same thing. """ # set VNA sweep function if start_freq != None and stop_freq != None: swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr, start_freq=start_freq, stop_freq=stop_freq, npts=nbr_points, force_reset=True) MC_instr.set_sweep_function(swf_fct_1D) elif center_freq != None and span != None: swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr, center_freq=center_freq, span=span, npts=nbr_points, force_reset=True) MC_instr.set_sweep_function(swf_fct_1D) if start_power != None and stop_power != None: # it prepares the sweep_points, such that it does not complain. swf_fct_1D.prepare() MC_instr.set_sweep_points(swf_fct_1D.sweep_points) MC_instr.set_sweep_function_2D(VNA_instr.power) MC_instr.set_sweep_points_2D(np.arange(start_power, stop_power+step_power/2., step_power)) else: raise ValueError('Need to define power range.') # set VNA detector function MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr)) # VNA settings VNA_instr.average_state('off') VNA_instr.bandwidth(bandwidth) # hack to measure S parameters different from S21 str_to_write = "calc:par:meas 'trc1', '%s'" % measure print(str_to_write) VNA_instr.visa_handle.write(str_to_write) VNA_instr.timeout(600) MC_instr.run(name=file_name, mode='2D')
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def acquire_2D_linear_frequency_span_vs_param(file_name, start_freq=None, stop_freq=None, center_freq=None, parameter=None, sweep_vector=None, span=None, nbr_points=101, power=-20, bandwidth=100, measure='S21'): """ Acquires a single trace from the VNA. Inputs: file_name (str), name of the output file. start_freq (float), starting frequency of the trace. stop_freq (float), stoping frequency of the trace. center_freq (float), central frequency of the trace. span (float), span of the trace. nbr_points (int), Number of points within the trace. power (float), power in dBm. bandwidth (float), bandwidth in Hz. measure (str), scattering parameter to measure (ie. 'S21'). Output: NONE Beware that start/stop and center/span are just two ways of configuring the same thing. """ # set VNA sweep function if start_freq != None and stop_freq != None: swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr, start_freq=start_freq, stop_freq=stop_freq, npts=nbr_points, force_reset=True) MC_instr.set_sweep_function(swf_fct_1D) elif center_freq != None and span != None: swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr, center_freq=center_freq, span=span, npts=nbr_points, force_reset=True) MC_instr.set_sweep_function(swf_fct_1D) if parameter is not None and sweep_vector is not None: # it prepares the sweep_points, such that it does not complain. swf_fct_1D.prepare() MC_instr.set_sweep_points(swf_fct_1D.sweep_points) MC_instr.set_sweep_function_2D(parameter) MC_instr.set_sweep_points_2D(sweep_vector) else: raise ValueError('Need to define parameter and its range.') # set VNA detector function MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr)) # VNA settings VNA_instr.power(power) VNA_instr.average_state('off') VNA_instr.bandwidth(bandwidth) # hack to measure S parameters different from S21 str_to_write = "calc:par:meas 'trc1', '%s'" % measure print(str_to_write) VNA_instr.visa_handle.write(str_to_write) VNA_instr.timeout(600) MC_instr.run(name=file_name, mode='2D')
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def acquire_disjoint_frequency_traces(file_name, list_freq_ranges, power=-20, bandwidth=100, measure='S21'): """ list_freq_ranges is a list that contains the arays defining all the ranges of interest. """ for idx, range_array in enumerate(list_freq_ranges): this_file = file_name + '_%d'%idx acquire_single_linear_frequency_span(file_name = this_file, start_freq=range_array[0], stop_freq=range_array[-1], nbr_points=len(range_array), power=power, bandwidth=bandwidth, measure=measure) packing_mmts(file_name, labels=file_name+'__', N=len(list_freq_ranges))
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def __init__(self): self.counter=0
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def wrapped_data_importing(counter): counter.counter += 1 return data_vector[:,counter.counter-1]
DiCarloLab-Delft/PycQED_py3
[ 51, 39, 51, 31, 1451987534 ]
def look_in_file(file_name, kws): """reads a file and returns only the lines that contain one of the keywords""" with open(file_name) as f: return "".join(filter(lambda line: any(kw in line for kw in kws), f))
AlManja/logs.py
[ 5, 2, 5, 1, 1485538333 ]
def __init__(self, parent=None): super(Window, self).__init__(parent) self.checks = [False]*len(checkbuttons) # initialize all buttons to False # creates a vertical box layout for the window vlayout = QtGui.QVBoxLayout() # creates the checkboxes for idx, text in enumerate(checkbuttons): checkbox = QtGui.QCheckBox(text) # connects the 'stateChanged()' signal with the 'checkbox_state_changed()' slot checkbox.stateChanged.connect(partial(self.checkbox_state_changed, idx)) vlayout.addWidget(checkbox) # adds the checkbox to the layout btn = QPushButton("&Show Info ({})".format(TMP_FILE), self) btn.clicked.connect(self.to_computer) btn.clicked.connect(self.to_editor) vlayout.addWidget(btn) vlayout.addStretch() self.setLayout(vlayout) # sets the window layout
AlManja/logs.py
[ 5, 2, 5, 1, 1485538333 ]
def to_computer(self, text): f = open(TMP_FILE, 'w') # write mode clears any previous content from the file if it exists if self.checks[0]: print("Saving: inxi to file") f.write(HEADER.format("Inxi -Fxzc0", "Listing computer information")) try: f.write(str(inxi('-Fxxxzc0'))) except: " 'inxi' not found, install it to get this info" f.write('\n') if self.checks[1]: print("Getting info about installed graphical driver") f.write(HEADER.format("Installed drivers", "Shows which graphic driver is installed")) try: f.write(str(mhwd('-li'))) except: print(" 'mhwd' not found, this is not Manjaro?") f.write('\n') if self.checks[2]: print("Getting list of all drivers supported on detected gpu's") f.write(HEADER.format("Available drivers", "list of all drivers supported on detected gpu's")) try: f.write(str(mhwd('-l'))) except: print(" 'mhwd' not found, this is not Manjaro?") # f.write('\n') if self.checks[3]: print('hwinfo -graphic card') # os.system('hwinfo --gfxcard') f.write(HEADER.format("hwinfo --gfxcard", "Show Graphic Card info")) try: f.write(str(hwinfo('--gfxcard'))) except: print('hwinfo graphic card info error') f.write('hwinfo graphic card info error') f.write('\n') if self.checks[4]: print('memory info') # os.system('free -h') f.write(HEADER.format("Memory Info", "Info about Memory and Swap")) try: f.write(str(free(' -h'))) except: print('memory info error') f.write('memory info error') f.write('\n') if self.checks[5]: print('disk info') # os.system('lsblk') f.write(HEADER.format("Disk Info", "Disks and Partitions")) try: f.write(str(lsblk())) except: print('lsblk error') f.write('lsblk error') f.write('\n') if self.checks[6]: print('free disk space') # os.system('df') f.write(HEADER.format("Free Disk Space", "Free space per pertition")) try: f.write(str(df())) except: print('free disk space error') f.write('free disk space error') f.write('\n') if self.checks[9]: print("Saving: Xorg.0.log to file") f.write(HEADER.format("Xorg.0.log", "searching for: failed, error & (WW) keywords")) try: f.write(look_in_file('/var/log/Xorg.0.log', ['failed', 'error', '(WW)'])) except FileNotFoundError: print("/var/log/Xorg.0.log not found!") f.write("Xorg.0.log not found!") f.write('\n') if self.checks[10]: print("Saving: Xorg.1.log to file") f.write(HEADER.format("Xorg.1.log", "searching for: failed, error & (WW) keywords")) try: f.write(look_in_file('/var/log/Xorg.1.log', ['failed', 'error', '(WW)'])) except FileNotFoundError: print("/var/log/Xorg.1.log not found!") f.write("Xorg.1.log not found!") f.write('\n') if self.checks[11]: print("Saving: pacman.log to file") f.write(HEADER.format("pacman.log", "searching for: pacsave, pacnew, pacorig keywords")) try: f.write(look_in_file('/var/log/pacman.log', ['pacsave', 'pacnew', 'pacorig'])) except FileNotFoundError: print("/var/log/pacman.log not found, this is not Manjaro or Arch based Linux?") f.write("pacman.log not found! Not Arch based OS?") f.write('\n') if self.checks[12]: print("Saving: journalctl (emergency) to file") os.system("journalctl -b > /tmp/journalctl.txt") f.write(HEADER.format("journalctl.txt", "Searching for: Emergency keywords")) f.write(look_in_file('/tmp/journalctl.txt', ['emergency', 'Emergency', 'EMERGENCY'])) f.write('\n') if self.checks[13]: print("Saving: journalctl (alert) to file") os.system("journalctl -b > /tmp/journalctl.txt") f.write(HEADER.format("journalctl.txt", "Searching for: Alert keywords")) f.write(look_in_file('/tmp/journalctl.txt', ['alert', 'Alert', 'ALERT'])) f.write('\n') if self.checks[14]: print("Saving: journalctl (critical) to file") os.system("journalctl -b > /tmp/journalctl.txt") f.write(HEADER.format("journalctl.txt", "Searching for: Critical keywords")) f.write(look_in_file('/tmp/journalctl.txt', ['critical', 'Critical', 'CRITICAL'])) f.write('\n') if self.checks[15]: print("Saving: journalctl (failed) to file") os.system("journalctl -b > /tmp/journalctl.txt") f.write(HEADER.format("journalctl.txt", "Searching for: Failed keywords")) f.write(look_in_file('/tmp/journalctl.txt', ['failed', 'Failed', 'FAILED'])) f.write('\n') if self.checks[16]: print("Saving: rc.log to file") f.write(HEADER.format("rc.log", "OpenRc only! searching for: WARNING: keywords")) try: f.write(look_in_file('/var/log/rc.log', ['WARNING:'])) except FileNotFoundError: print("/var/log/rc.log not found! Systemd based OS?") f.write("rc.log not found! Systemd based OS?") f.write('\n') f.close()
AlManja/logs.py
[ 5, 2, 5, 1, 1485538333 ]
def __init__(self, typ=None, intensity=0, size=0, gen=0, cho=0): self._type = typ #"n1", "n2", "bg", "ch", "ge" if intensity<0 or gen<0 or cho<0 or size<0 or intensity>1 or size>1 or gen>1 or cho>1: raise ValueError ("Invalid Values for Structure Part") self._intensity = intensity # [0-1] self._size = size # [0-1] self._genover = gen # [0-1] overlay of general type lines self._chover = cho # [0-1] overlay of chorus type lines
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def fromString(cls, string): # [n1-0.123-1-0.321-0.2] type, intensity, size, genoverlay, chooverlay while string[0] == " ": string = string[1:] while string[0] == "\n": string = string[1:] while string[-1] == " ": string = string[:-1] while string[-1] == "\0": string = string[:-1] while string[-1] == "\n": string = string[:-1] if len(string)<8: raise ValueError("Invalid Part string: "+string) if string[0] == "[" and string[-1] == "]": string = string[1:-1] else: raise ValueError("Invalid Part string: "+string) typ = string[:2] string = string[3:] if not typ in ("n1", "n2", "bg", "ch", "ge"): raise ValueError("Invalid Part Type string: "+typ) valstrings = str.split(string, "-") inten = eval(valstrings[0]) size = eval(valstrings[1]) gen = eval(valstrings[2]) cho = eval(valstrings[3]) return cls(typ, inten, size, gen, cho)
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def getTheme(self, pal): if self._type == "n1": return pal._n1 if self._type == "n2": return pal._n2 if self._type == "bg": return pal._bg if self._type == "ch": return pal._ch if self._type == "ge": return pal._ge
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def getAudio(self, pal, bpm): base = self.baseDur(pal, bpm) total = base + 3000 #extra time for last note to play nvoic = math.ceil(self._intensity * self.getTheme(pal).countVoices()) try: ngeno = math.ceil(self._genover * pal._ge.countVoices()) except: ngeno = 0 try: nchoo = math.ceil(self._chover * pal._ch.countVoices()) except: nchoo = 0
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def baseDur(self, pal, bpm): #get the base duration of this part of the song return self.getTheme(pal).baseDurForStruct(self._size, bpm)
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def __init__(self): self._parts = ()
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def __repr__(self): return "@STRUCTURE:" + str(self._parts)
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def baseDur(self, pal, bpm=None): if bpm == None: bpm = pal._bpm curTime = 0 for p in self._parts: curTime = curTime + p.baseDur(pal, bpm) return curTime
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def songAudio(self, pal, bpm=None): if bpm == None: bpm = pal._bpm total = self.baseDur(pal, bpm) + 3000 # 3 seconds for last note to play sound = AudioSegment.silent(total) curTime = 0 for p in self._parts: paudio = p.getAudio(pal, bpm) sound = sound.overlay(paudio, curTime) curTime = curTime + p.baseDur(pal, bpm) print("curTime:",curTime) return sound
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def wselect(dicti): total=0 for i in list(dicti): total = total + dicti[i] indice = total*random.random() for i in list(dicti): if dicti[i]>=indice: return i indice = indice - dicti[i] raise ValueError ("something went wrong")
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def rselect(lista): return random.choice(lista)
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def stweights(): return {"n1":5, "n2":4, "ch":2, "bg":1}
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def n2weights(): return {"n1":2, "n2":3, "ch":4, "bg":2}
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def bgweights(): return {"n1":1, "n2":1, "ch":20, "bg":8}
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def siweights(): return {0.1:1, 0.2:2, 0.3:4, 0.4:5, 0.5:5, 0.6:4, 0.7:3, 0.8:2, 0.9:1}
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def intensitySequence(size): val = wselect(siweights()) sequence = (val,) while len(sequence)<size: val = val + wselect(deltaweights()) if val<0.1: val = 0.1 if val>1: val = 1 sequence = sequence + (val,) return sequence
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def deltoweights(): return {-0.2:1, -0.1:1, 0:8, 0.1:2, 0.2:2}
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def ssweights(): return {0.2:1, 0.4:1, 0.6:1, 0.8:1, 1:16}
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def makeStruct(size = None): if size == None: size = wselect(lenweights()) types = typeSequence(size) inten = intensitySequence(size) sizes = sizeSequence(size) overl = overlaySequence(size) return joinSeqs(types, inten, sizes, overl)
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def pooptest(): for i in range(30): print(makeStruct())
joaoperfig/mikezart
[ 31, 3, 31, 1, 1499422629 ]
def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name
yourcelf/signpdf
[ 54, 31, 54, 7, 1429985356 ]
def main(): sign_pdf(parser.parse_args())
yourcelf/signpdf
[ 54, 31, 54, 7, 1429985356 ]
def atexit(): print("atexit")
nicfit/nicfit.py
[ 3, 2, 3, 42, 1480807314 ]
def find_package_data( where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories, only_in_packages=True, show_ignored=False): """ Return a dictionary suitable for use in ``package_data`` in a distutils ``setup.py`` file. The dictionary looks like:: {'package': [files]} Where ``files`` is a list of all the files in that package that don't match anything in ``exclude``. If ``only_in_packages`` is true, then top-level directories that are not packages won't be included (but directories under packages will). Directories matching any pattern in ``exclude_directories`` will be ignored; by default directories with leading ``.``, ``CVS``, and ``_darcs`` will be ignored. If ``show_ignored`` is true, then all the files that aren't included in package data are shown on stderr (for debugging purposes). Note patterns use wildcards, or can be exact paths (including leading ``./``), and all searching is case-insensitive. This function is by Ian Bicking. """ out = {} stack = [(convert_path(where), '', package, only_in_packages)] while stack: where, prefix, package, only_in_packages = stack.pop(0) for name in os.listdir(where): fn = os.path.join(where, name) if os.path.isdir(fn): bad_name = False for pattern in exclude_directories: if fnmatchcase(name, pattern) or fn.lower() == pattern.lower(): bad_name = True if show_ignored: print >> sys.stderr, ( "Directory %s ignored by pattern %s" % (fn, pattern)) break if bad_name: continue if os.path.isfile(os.path.join(fn, '__init__.py')): if not package: new_package = name else: new_package = package + '.' + name stack.append((fn, '', new_package, False)) else: stack.append((fn, prefix + name + '/', package, only_in_packages)) elif package or not only_in_packages: # is a file bad_name = False for pattern in exclude: if fnmatchcase(name, pattern) or fn.lower() == pattern.lower(): bad_name = True if show_ignored: print >> sys.stderr, ( "File %s ignored by pattern %s" % (fn, pattern)) break if bad_name: continue out.setdefault(package, []).append(prefix + name) return out
tylerbutler/engineer
[ 23, 3, 23, 1, 1331695786 ]
def get_install_requirements(requirements_file='requirements.txt'): requirements = [] with open(requirements_file) as file: temp = file.readlines() temp = [i[:-1] for i in temp] for line in temp: if line is None or line == '' or line.startswith(('#', '-e', '-r')): continue else: requirements.append(line) return requirements
tylerbutler/engineer
[ 23, 3, 23, 1, 1331695786 ]