rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
f = theano.function([a,b,c],c * 0.2*T.dot(a,b),mode=m) | f = theano.function([a,b,c],c * 0.2*T.dot(a,b),mode=mode_blas_opt) | def test_dot22scalar(): ## including does not seem to work for 'local_dot_to_dot22' and ## 'local_dot22_to_dot22scalar' ## TODO: exclude other optimizations in BlasOpt? #m = theano.compile.get_default_mode().including('local_dot_to_dot22','local_dot22_to_dot22scalar','specialize') m = theano.compile.get_default_mode().... |
m2 = m.including('canonicalize') | m2 = mode_blas_opt.including('canonicalize') | def test_dot22scalar(): ## including does not seem to work for 'local_dot_to_dot22' and ## 'local_dot22_to_dot22scalar' ## TODO: exclude other optimizations in BlasOpt? #m = theano.compile.get_default_mode().including('local_dot_to_dot22','local_dot22_to_dot22scalar','specialize') m = theano.compile.get_default_mode().... |
f = theano.function([a,b,c],0.2*c *a*T.dot(a,b),mode=m) | f = theano.function([a,b,c],0.2*c *a*T.dot(a,b),mode=mode_blas_opt) | def test_dot22scalar(): ## including does not seem to work for 'local_dot_to_dot22' and ## 'local_dot22_to_dot22scalar' ## TODO: exclude other optimizations in BlasOpt? #m = theano.compile.get_default_mode().including('local_dot_to_dot22','local_dot22_to_dot22scalar','specialize') m = theano.compile.get_default_mode().... |
r_transfered_from_storage_map = [] | r_vals_initialized = [] | def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None |
r_transfered_from_storage_map.append(r) | r_vals_initialized.append(r) | def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None |
for r in r_transfered_from_storage_map: | for r in storage_map: | def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None |
if storage_map[r][0] is None: | if r in r_vals_initialized: | def f(): debug("starting a DebugMode call") for x in no_recycling: x[0] = None |
return (0,5) | return (0,6) | def c_code_cache_version(self): return (0,5) |
if hasattr(node.outputs[00].type,"may_share_memory"): if not numpy.may_share_memory(storage_map[node.outputs[oo]][0],storage_map[node.inputs[ii[0]]][0]): | if hasattr(node.outputs[0].type,"may_share_memory"): if not node.outputs[0].type.may_share_memory(storage_map[node.outputs[oo]][0],storage_map[node.inputs[ii[0]]][0]): | def _check_inputs(node, storage_map, r_vals, dr_vals, active_nodes, clobber_dr_vals=True, perform=None, warn_input_not_reused=True): """Raise BadDestroyMap if necessary, update dr_vals""" destroyed_idx_list = [] destroy_map = getattr(node.op, 'destroy_map', {}) for o_pos, i_pos_list in destroy_map.iteritems(): destroye... |
print >> file, prefix, a.op, id(a) | if len(a.outputs) == 1: print >> file, '%s%s [@%i]' % (prefix, a.op, id(r)) else: print >> file, '%s%s.%i [@%i]' % (prefix, a.op, a.outputs.index(r), id(r)) | def debugprint(r, prefix='', depth=-1, done=None, file=sys.stdout): """Print the graph leading to `r` to given depth. :param r: Variable instance :param prefix: prefix to each line (typically some number of spaces) :param depth: maximum recursion depth (Default -1 for unlimited). :param done: set of Apply instances th... |
debugprint(i, prefix+' ', depth=depth-1, done=done, file=file) | debugprint(i, prefix+' |', depth=depth-1, done=done, file=file) | def debugprint(r, prefix='', depth=-1, done=None, file=sys.stdout): """Print the graph leading to `r` to given depth. :param r: Variable instance :param prefix: prefix to each line (typically some number of spaces) :param depth: maximum recursion depth (Default -1 for unlimited). :param done: set of Apply instances th... |
print >> file, prefix, r, id(r) | print >> file, '%s%s [@%i]' % (prefix, r, id(r)) | def debugprint(r, prefix='', depth=-1, done=None, file=sys.stdout): """Print the graph leading to `r` to given depth. :param r: Variable instance :param prefix: prefix to each line (typically some number of spaces) :param depth: maximum recursion depth (Default -1 for unlimited). :param done: set of Apply instances th... |
indices = numpy.asarray(indices, dtype='int32') | indices = numpy.asarray(indices).view(numpy.int32) | def make_node(self, data, indices, indptr, shape): """Build a SparseVariable from the internal parametrization :param data: :param indices: :param indptr: :type data: 1-d tensor :type indices: 1-d tensor of ints :type indptr: 1-d tensor of ints |
indptr = numpy.asarray(indptr, dtype='int32') | indptr = numpy.asarray(indptr).view(numpy.int32) | def make_node(self, data, indices, indptr, shape): """Build a SparseVariable from the internal parametrization :param data: :param indices: :param indptr: :type data: 1-d tensor :type indices: 1-d tensor of ints :type indptr: 1-d tensor of ints |
shape = numpy.asarray(shape, dtype='int32') | shape = numpy.asarray(shape).view(numpy.int32) | def make_node(self, data, indices, indptr, shape): """Build a SparseVariable from the internal parametrization :param data: :param indices: :param indptr: :type data: 1-d tensor :type indices: 1-d tensor of ints :type indptr: 1-d tensor of ints |
elif 'key.pkl' in files and (time_now - last_access_time(module_name_from_dir(root)))<self.age_thresh_use: key_pkl = os.path.join(root, 'key.pkl') debug('refresh adding', key_pkl) | elif 'key.pkl' in files: | def refresh(self): """Update self.entry_from_key by walking the cache directory structure. |
key = cPickle.load(open(key_pkl, 'rb')) except: info("ModuleCache.refresh() Failed to unpickle cache key", key_pkl) if 0: info("Erasing broken cache directory", key_pkl) shutil.rmtree(root) else: pass continue if not key[0]: warning("ModuleCache.refresh() Found unversioned key in cache, deleting it.", key_pkl) | entry = module_name_from_dir(root) except ValueError: warning("ModuleCache.refresh() Found key without dll in cache, deleting it.", key_pkl) | def refresh(self): """Update self.entry_from_key by walking the cache directory structure. |
if key not in self.entry_from_key: | if (time_now - last_access_time(module_name_from_dir(root)))<self.age_thresh_use: key_pkl = os.path.join(root, 'key.pkl') debug('refresh adding', key_pkl) | def refresh(self): """Update self.entry_from_key by walking the cache directory structure. |
entry = module_name_from_dir(root) except ValueError: warning("ModuleCache.refresh() Found key without dll in cache, deleting it.", key_pkl) | key = cPickle.load(open(key_pkl, 'rb')) except: info("ModuleCache.refresh() Failed to unpickle cache key", key_pkl) if 0: info("Erasing broken cache directory", key_pkl) shutil.rmtree(root) else: pass continue if not key[0]: warning("ModuleCache.refresh() Found unversioned key in cache, deleting it.", key_pkl) | def refresh(self): """Update self.entry_from_key by walking the cache directory structure. |
self.entry_from_key[key] = entry assert entry not in self.module_from_name self.loaded_key_pkl.add(key_pkl) | if key not in self.entry_from_key: self.entry_from_key[key] = entry assert entry not in self.module_from_name self.loaded_key_pkl.add(key_pkl) | def refresh(self): """Update self.entry_from_key by walking the cache directory structure. |
npy_old_val = numpy.asarray(self.old_val) npy_new_val = numpy.asarray(self.new_val) | sio = StringIO() print >> sio, " node:", self.node print >> sio, " node.inputs:", [(str(i), id(i)) for i in self.node.inputs] print >> sio, " destroy_map:", getattr(self.node.op, 'destroy_map', {}) print >> sio, " changed input idx:", self.idx print >> sio, " changed input type:", self.node.inputs[self.idx].type p... | def __str__(self): npy_old_val = numpy.asarray(self.old_val) npy_new_val = numpy.asarray(self.new_val) try: sio = StringIO() print >> sio, " node:", self.node print >> sio, " node.inputs:", [(str(i), id(i)) for i in self.node.inputs] print >> sio, " destroy_map:", getattr(self.node.op, 'destroy_map', {}) print >> si... |
sio = StringIO() print >> sio, " node:", self.node print >> sio, " node.inputs:", [(str(i), id(i)) for i in self.node.inputs] print >> sio, " destroy_map:", getattr(self.node.op, 'destroy_map', {}) print >> sio, " changed input idx:", self.idx print >> sio, " changed input type:", self.node.inputs[self.idx].type p... | npy_old_val = numpy.asarray(self.old_val) npy_new_val = numpy.asarray(self.new_val) | def __str__(self): npy_old_val = numpy.asarray(self.old_val) npy_new_val = numpy.asarray(self.new_val) try: sio = StringIO() print >> sio, " node:", self.node print >> sio, " node.inputs:", [(str(i), id(i)) for i in self.node.inputs] print >> sio, " destroy_map:", getattr(self.node.op, 'destroy_map', {}) print >> si... |
print >> sio, " Hint: this can also be caused by a deficient values_eq_approx() or __eq__() implementation [which compared input values]" return sio.getvalue() | def __str__(self): npy_old_val = numpy.asarray(self.old_val) npy_new_val = numpy.asarray(self.new_val) try: sio = StringIO() print >> sio, " node:", self.node print >> sio, " node.inputs:", [(str(i), id(i)) for i in self.node.inputs] print >> sio, " destroy_map:", getattr(self.node.op, 'destroy_map', {}) print >> si... | |
return str(e) | print >> sio, "(Numpy-hints failed with: %s)" %str(e) print >> sio, " Hint: this can also be caused by a deficient values_eq_approx() or __eq__() implementation [which compared input values]" return sio.getvalue() | def __str__(self): npy_old_val = numpy.asarray(self.old_val) npy_new_val = numpy.asarray(self.new_val) try: sio = StringIO() print >> sio, " node:", self.node print >> sio, " node.inputs:", [(str(i), id(i)) for i in self.node.inputs] print >> sio, " destroy_map:", getattr(self.node.op, 'destroy_map', {}) print >> si... |
if new_order == range(len(new_order)): | if new_order == range(len(new_order)) and (len(new_order) == iinput.type.ndim): | def local_dimshuffle_lift(node): """ "Lifts" DimShuffle through Elemwise operations and merges consecutive DimShuffles. Basically, applies the following transformations on the whole graph: DimShuffle(Elemwise(x, y)) => Elemwise(DimShuffle(x), DimShuffle(y)) DimShuffle(DimShuffle(x)) => DimShuffle(x) After this transf... |
return self.__class__(self.type, copy(self.data), self.name) | cp = self.__class__(self.type, copy(self.data), self.name) cp.tag = copy(self.tag) return cp | def clone(self): """WRITEME""" return self.__class__(self.type, copy(self.data), self.name) |
return self.__class__(self.type, self.data, self.name) | cp = self.__class__(self.type, self.data, self.name) cp.tag = copy(self.tag) return cp | def clone(self): """ We clone this object, but we don't clone the data to lower memory requirement We suppose that the data will never change. """ return self.__class__(self.type, self.data, self.name) |
if config.floatX == 'float32' and config.floatX in self.dtypes: return theano._asarray(x, dtype='float32') | dtype = None if isinstance(x, numpy.float64) and 'float64' in self.dtypes: dtype = 'float64' elif isinstance(x, numpy.float32) and 'float32' in self.dtypes: dtype = 'float32' elif isinstance(x, float) and config.floatX in self.dtypes and config.floatX == 'float32': dtype = config.floatX if dtype: return theano._asarra... | def __call__(self, x): # change the default casting behaviour for python floats to always cast to float32 if config.floatX == 'float32' and config.floatX in self.dtypes: return theano._asarray(x, dtype='float32') for dtype in self.dtypes: x_ = theano._asarray(x, dtype=dtype) if numpy.all(x == x_): break # returns eithe... |
print >> code, ' ', ''.join('Py_INCREF(PyTuple_GET_ITEM(argtuple, %i));'%n for n in xrange(n_args)) | def instantiate_code(self, n_args): code = StringIO.StringIO() struct_name = self.struct_name print >> code, "static PyObject * instantiate(PyObject * self, PyObject *argtuple) {" print >> code, ' assert(PyTuple_Check(argtuple));' print >> code, ' if (%(n_args)i != PyTuple_Size(argtuple)){ ' %locals() print >> code, ... | |
if config.gcc.cxxflags: cmd.extend(config.gcc.cxxflags.split(' ')) | cxxflags = [flag for flag in config.gcc.cxxflags.split(' ') if flag] cmd.extend(cxxflags) | def gcc_module_compile_str(module_name, src_code, location=None, include_dirs=[], lib_dirs=[], libs=[], preargs=[]): """ :param module_name: string (this has been embedded in the src_code :param src_code: a complete c or c++ source listing for the module :param location: a pre-existing filesystem directory where the cp... |
replacement = node.env.shape_feature.scheduled[node.inputs[0]] print >> sys.stderr, "REPLACING SOMETHING" return [node.env.shape_feature.shape_of[replacement][i]] | replacement = node.env.shape_feature.scheduled[node] if len(node.env.shape_feature.shape_of[replacement])!=1: import pdb;pdb.set_trace() print >> sys.stderr, "REPLACING SOMETHING", replacement, node.env.shape_feature.shape_of[replacement] return [node.env.shape_feature.shape_of[replacement][0]] | def local_track_shape_i(node): try: shape_feature = node.env.shape_feature except: return if node in node.env.shape_feature.scheduled: assert isinstance(node.op, Shape_i) replacement = node.env.shape_feature.scheduled[node.inputs[0]] print >> sys.stderr, "REPLACING SOMETHING" return [node.env.shape_feature.shape_of[rep... |
return gz, | return [gpu_from_host(gz)] | def grad(self, inputs, (gz,)): return gz, #return [GpuFromHost()(gz)] |
return gz, | return [host_from_gpu(gz)] | def grad(self, inputs, (gz,)): return gz, #return [HostFromGpu()(gz)] |
print 'Up' self.old_val = theano.tensor.TensorType.filter_checks_isfinite | self.old_ts = theano.tensor.TensorType.filter_checks_isfinite self.old_dm = theano.compile.mode.predefined_modes['DEBUG_MODE'].check_isfinite | def setUp(self): print 'Up' self.old_val = theano.tensor.TensorType.filter_checks_isfinite |
print 'Down' theano.tensor.TensorType.filter_checks_isfinite = self.old_val | theano.tensor.TensorType.filter_checks_isfinite = self.old_ts theano.compile.mode.predefined_modes['DEBUG_MODE'].check_isfinite = self.old_dm | def tearDown(self): print 'Down' theano.tensor.TensorType.filter_checks_isfinite = self.old_val |
self.failUnlessRaises(ValueError, f, numpy.log([3, -4, 5])) self.failUnlessRaises(ValueError, f, numpy.asarray([0, 1.0, 0])/0) self.failUnlessRaises(ValueError, f, numpy.asarray([1.0, 1.0, 1.0])/0) | self.failUnlessRaises(debugmode.InvalidValueError, f, numpy.log([3, -4, 5])) self.failUnlessRaises(debugmode.InvalidValueError, f, numpy.asarray([0, 1.0, 0])/0) self.failUnlessRaises(debugmode.InvalidValueError, f, numpy.asarray([1.0, 1.0, 1.0])/0) | def test_check_isfinite(self): x = theano.tensor.vector() f = theano.function([x], (x+2) * 5, mode='DEBUG_MODE') g = theano.function([x], theano.tensor.log(x), mode='DEBUG_MODE') |
assert rnn.minimizer.step_cost(x,y) < -20 | if theano.config.mode=='DEBUG_MODE': assert rnn.minimizer.step_cost(x,y) < -.9 else: assert rnn.minimizer.step_cost(x,y) < -20 | def test_example_rnn(): minimizer_fn = sgd_minimizer(stepsize = 0.001) n_vis = 5 n_out = 3 n_hid = 4 rnn_module = ExampleRNN(n_vis, minimizer_fn) rnn = rnn_module.make() rng = N.random.RandomState(unittest_tools.fetch_seed(7722342)) x = rng.randn(10,n_vis) y = rng.randn(10,n_out) #set y to be like x with a lag of L... |
cl = CLinker().accept(e, [r for r, r2 in zip(e.outputs, node.outputs) if r2 in no_recycling]) | if self.allow_gc: node_no_recycling = e.outputs else: node_no_recycling = [r for r, r2 in zip(e.outputs, node.outputs) if r2 in no_recycling] cl = CLinker().accept(e, node_no_recycling) | def make_all(self, profiler = None, input_storage = None, output_storage = None): |
text = expand_alias(self.frame.np.config.aliases, alias) | raw = expand_alias(self.frame.np.config.aliases, alias) text = findBestEncoding(raw, ['UTF-8', 'ASCII']) | def threadAlias(self, alias): text = expand_alias(self.frame.np.config.aliases, alias) if not text: return if text[:2] == "//": text = text[1:] self.frame.np.queue.put(slskmessages.SayChatroom(self.room, ToBeEncoded(self.frame.AutoReplace(text), self.encoding))) |
i.speed = (i.currentbytes - i.lastbytes)/(curtime - i.lasttime)/1024 | try: i.speed = (i.currentbytes - i.lastbytes)/(curtime - i.lasttime)/1024 except ZeroDivisionError: i.speed = 0 | def FileDownload(self, msg): """ A file download is in progress""" needupdate = 1 config = self.eventprocessor.config.sections for i in self.downloads: if i.conn != msg.conn: continue try: if i.transfertimer is not None: i.transfertimer.cancel() curtime = time.time() i.currentbytes = msg.file.tell() if i.lastbytes is N... |
command = 'upnpc -r %s tcp' | command = 'upnpc -r $ tcp' | def miniupnpcbinary(internallanport, externallanport): if internallanport != externallanport: log.addWarning(_('UPnPc binary cannot be used since the internal port (%s) is not identical to the external port (%s)') % (internallanport, externallanport)) command = 'upnpc -r %s tcp' try: output = executeCommand(command, re... |
output = executeCommand(command, returnoutput=True) | output = executeCommand(command, replacement=str(externallanport), returnoutput=True) | def miniupnpcbinary(internallanport, externallanport): if internallanport != externallanport: log.addWarning(_('UPnPc binary cannot be used since the internal port (%s) is not identical to the external port (%s)') % (internallanport, externallanport)) command = 'upnpc -r %s tcp' try: output = executeCommand(command, re... |
def parseNetworkMessage(self, message, nozlib = 0): | def parseNetworkMessage(self, message, nozlib = False): | def __init__(self, conn, shares = None): self.conn = conn self.list = shares self.built = None |
try: self._parseNetworkMessage(message, NetworkLongLongType) except struct.error, e: try: self._parseNetworkMessage(message, NetworkIntType) except struct.error, f: lines = [] lines.append(_("Exception during parsing %(area)s: %(exception)s") % {'area':'SharedFileList1', 'exception':e}) lines.append(_("Exception during... | def parseNetworkMessage(self, message, nozlib = 0): | |
pos, size = self.getObject(message, types.LongType, pos, getsignedint = True) | pos, size = self.getObject(message, sizetype, pos, getsignedint = True, printerror=False) | def parseNetworkMessage(self, message, nozlib = 0): |
pos, ext = self.getObject(message, types.StringType, pos) pos, numattr = self.getObject(message, types.IntType, pos) | pos, ext = self.getObject(message, types.StringType, pos, printerror=False) pos, numattr = self.getObject(message, types.IntType, pos, printerror=False) | def parseNetworkMessage(self, message, nozlib = 0): |
pos, attrnum = self.getObject(message, types.IntType, pos) pos, attr = self.getObject(message, types.IntType, pos) | pos, attrnum = self.getObject(message, types.IntType, pos, printerror=False) pos, attr = self.getObject(message, types.IntType, pos, printerror=False) | def parseNetworkMessage(self, message, nozlib = 0): |
try: self.sections["ticker"]["default"] = findBestEncoding(self.sections["ticker"]["default"], ['utf-8']) except TypeError: pass | unicodes = [('ticker','default'), ('server','autoreply')] for (section, subsection) in unicodes: try: self.sections[section][subsection] = findBestEncoding(self.sections[section][subsection], ['utf-8']) except TypeError: pass | def readConfig(self): self.config_lock.acquire() |
msg = self.packObject(self.user)+self.packObject(self.token)+self.packObject(len(filelist)) | msg = (self.packObject(self.user) + self.packObject(NetworkIntType(self.token)) + self.packObject(NetworkIntType(len(filelist)))) | def makeNetworkMessage(self): filelist = [] for i in self.list: try: filelist.append(self.fileindex[str(i)]) except: pass if self.fifoqueue: queuesize = self.inqueue[0] else: count = 0 for i in filelist: if i[0][-4:].lower() == ".ogg": count += 1 else: count -= 1 if count > 0: queuesize = self.inqueue[1] else: queuesi... |
self.packObject(NetworkIntType(i[1]))) | self.packObject(NetworkLongLongType(i[1]))) | def makeNetworkMessage(self): filelist = [] for i in self.list: try: filelist.append(self.fileindex[str(i)]) except: pass if self.fifoqueue: queuesize = self.inqueue[0] else: count = 0 for i in filelist: if i[0][-4:].lower() == ".ogg": count += 1 else: count -= 1 if count > 0: queuesize = self.inqueue[1] else: queuesi... |
msg = msg + self.packObject('')+self.packObject(0) | msg += self.packObject('')+self.packObject(0) | def makeNetworkMessage(self): filelist = [] for i in self.list: try: filelist.append(self.fileindex[str(i)]) except: pass if self.fifoqueue: queuesize = self.inqueue[0] else: count = 0 for i in filelist: if i[0][-4:].lower() == ".ogg": count += 1 else: count -= 1 if count > 0: queuesize = self.inqueue[1] else: queuesi... |
msg = msg + self.packObject("mp3") + self.packObject(3) | msg += self.packObject("mp3") + self.packObject(3) | def makeNetworkMessage(self): filelist = [] for i in self.list: try: filelist.append(self.fileindex[str(i)]) except: pass if self.fifoqueue: queuesize = self.inqueue[0] else: count = 0 for i in filelist: if i[0][-4:].lower() == ".ogg": count += 1 else: count -= 1 if count > 0: queuesize = self.inqueue[1] else: queuesi... |
i.speed = (i.currentbytes - i.lastbytes)/(curtime - i.lasttime)/1024 | try: i.speed = (i.currentbytes - i.lastbytes)/(curtime - i.lasttime)/1024 except ZeroDivisionError: i.speed = 0 | def FileUpload(self, msg): """ A file upload is in progress""" needupdate = 1 for i in self.uploads: if i.conn != msg.conn: continue if i.transfertimer is not None: i.transfertimer.cancel() curtime = time.time() if i.starttime is None: i.starttime = curtime i.offset = msg.offset lastspeed = 0 if i.speed is not None: l... |
try: self._parseNetworkMessage(message, NetworkLongLongType) except struct.error, e: try: self._parseNetworkMessage(message, NetworkIntType) except struct.error, f: lines = [] lines.append(_("Exception during parsing %(area)s: %(exception)s") % {'area':'FolderContentsResponse1', 'exception':e}) lines.append(_("Exceptio... | def parseNetworkMessage(self, message): try: message = zlib.decompress(message) except Exception, error: log.addwarning(_("Exception during parsing %(area)s: %(exception)s") % {'area':'FolderContentsResponse', 'exception':error}) self.list = {} return | |
pos, name = self.getObject(message, types.StringType, pos) pos, size = self.getObject(message, types.LongType, pos, getsignedint = 1) pos, ext = self.getObject(message, types.StringType, pos) pos, numattr = self.getObject(message, types.IntType, pos) | pos, name = self.getObject(message, types.StringType, pos, printerror=False) pos, size = self.getObject(message, sizetype, pos, getsignedint = 1, printerror=False) pos, ext = self.getObject(message, types.StringType, pos, printerror=False) pos, numattr = self.getObject(message, types.IntType, pos, printerror=False) | def parseNetworkMessage(self, message): try: message = zlib.decompress(message) except Exception, error: log.addwarning(_("Exception during parsing %(area)s: %(exception)s") % {'area':'FolderContentsResponse', 'exception':error}) self.list = {} return |
pos, attrnum = self.getObject(message, types.IntType, pos) pos, attr = self.getObject(message, types.IntType, pos) | pos, attrnum = self.getObject(message, types.IntType, pos, printerror=False) pos, attr = self.getObject(message, types.IntType, pos, printerror=False) | def parseNetworkMessage(self, message): try: message = zlib.decompress(message) except Exception, error: log.addwarning(_("Exception during parsing %(area)s: %(exception)s") % {'area':'FolderContentsResponse', 'exception':error}) self.list = {} return |
if self.id in self.Searches.searches.keys(): | try: | def OnIgnore(self, widget): if self.id in self.Searches.searches.keys(): del self.Searches.searches[self.id] widget.set_sensitive(False) |
self.OnIgnore(widget) | if self.text not in self.frame.np.config.sections["server"]["autosearch"]: self.OnIgnore(widget) | def OnClose(self, widget): if not self.frame.np.config.sections["searches"]["reopen_tabs"]: self.OnIgnore(widget) self.Searches.RemoveTab(self) |
"enabletrans": self.EnableTransparent, "transtint": self.Drawing_TintColor, "transalpha": self.TintAlpha, | "enabletrans": self.EnableTransparent, "transtint": self.Drawing_TintColor, | def __init__(self, parent): self.p = parent buildFrame.__init__(self, "ColoursFrame") self.UsernameStyle_List = gtk.ListStore(gobject.TYPE_STRING) self.UsernameStyle.set_model(self.UsernameStyle_List) self.UsernameStyle.set_text_column(0) |
raise "File %s exists" % filename | raise BaseException("File %s exists" % filename) | def writeConfigBackup(self, filename=None): self.config_lock.acquire() if filename is None: filename = "%s backup %s.tar.bz2" %(self.filename, time.strftime("%Y-%m-%d %H:%M:%S") ) else: if filename[-8:-1] != ".tar.bz2": filename += ".tar.bz2" try: if os.path.exists(filename): raise "File %s exists" % filename import ... |
raise "Config file missing" | raise BaseException("Config file missing") | def writeConfigBackup(self, filename=None): self.config_lock.acquire() if filename is None: filename = "%s backup %s.tar.bz2" %(self.filename, time.strftime("%Y-%m-%d %H:%M:%S") ) else: if filename[-8:-1] != ".tar.bz2": filename += ".tar.bz2" try: if os.path.exists(filename): raise "File %s exists" % filename import ... |
stream += message.packObject('mp3') + message.packObject(3) stream += (message.packObject(0) + message.packObject(NetworkIntType(fileinfo[2][0])) + message.packObject(1) + message.packObject(NetworkIntType(fileinfo[3])) + message.packObject(2) + message.packObject(NetworkIntType(fileinfo[2][1]))) | try: msgbytes = '' msgbytes += message.packObject('mp3') + message.packObject(3) msgbytes += (message.packObject(0) + message.packObject(NetworkIntType(fileinfo[2][0])) + message.packObject(1) + message.packObject(NetworkIntType(fileinfo[3])) + message.packObject(2) + message.packObject(NetworkIntType(fileinfo[2][1])))... | def getByteStream(self, fileinfo): message = slskmessages.SlskMessage() #size = long(fileinfo[1]) #size1 = size & 0xffffffff #size2 = size >> 32 #X print "chr1-" + repr(chr(1) + message.packObject(fileinfo[0]) + message.packObject(fileinfo[1])) #X print "chr1+" + repr(chr(1) + message.packObject(fileinfo[0]) + messag... |
msg = msg+chr(1)+self.packObject(i[0].replace(os.sep,"\\"))+self.packObject(i[1]) | msg += (chr(1) + self.packObject(i[0].replace(os.sep,"\\")) + self.packObject(NetworkIntType(i[1]))) | def makeNetworkMessage(self): filelist = [] for i in self.list: try: filelist.append(self.fileindex[str(i)]) except: pass if self.fifoqueue: queuesize = self.inqueue[0] else: count = 0 for i in filelist: if i[0][-4:].lower() == ".ogg": count += 1 else: count -= 1 if count > 0: queuesize = self.inqueue[1] else: queuesi... |
msg = msg + self.packObject(0) + self.packObject(i[2][0])+self.packObject(1)+ self.packObject(i[3])+self.packObject(2)+self.packObject(i[2][1]) msg = msg+chr(self.freeulslots)+self.packObject(self.ulspeed)+self.packObject(queuesize) | msg += (self.packObject(0) + self.packObject(NetworkIntType(i[2][0])) + self.packObject(1) + self.packObject(NetworkIntType(i[3])) + self.packObject(2) + self.packObject(i[2][1])) msg += (chr(self.freeulslots) + self.packObject(NetworkIntType(self.ulspeed)) + self.packObject(NetworkIntType(queuesize))) | def makeNetworkMessage(self): filelist = [] for i in self.list: try: filelist.append(self.fileindex[str(i)]) except: pass if self.fifoqueue: queuesize = self.inqueue[0] else: count = 0 for i in filelist: if i[0][-4:].lower() == ".ogg": count += 1 else: count -= 1 if count > 0: queuesize = self.inqueue[1] else: queuesi... |
if (now - i.laststatuschange) < 10: | if (now - i.laststatuschange) < 30: | def transferNegotiating(self): # some file is being negotiated #return len([i for i in self.uploads if i.req is not None or (i.conn is not None and i.speed is None) or i.status == 'Getting status']) > 0 now = time.time() for i in self.uploads: if (now - i.laststatuschange) < 10: # if a status hasn't changed in the last... |
except (IOError, EOFError), inst: | except (IOError, EOFError, ValueError), inst: | def readConfig(self): self.config_lock.acquire() |
"filemanager": "rox $", \ | "filemanager": "xdg-open $", \ | def __init__(self, filename): self.config_lock = thread.allocate_lock() self.config_lock.acquire() self.frame = None self.filename = filename self.parser = ConfigParser.ConfigParser() self.parser.read([self.filename]) LOGDIR=os.path.join(self.filename.rsplit(os.sep, 1)[0], "logs") self.sections = { |
"default": "xmms -e $", \ | "default": "xdg-open $", \ | def __init__(self, filename): self.config_lock = thread.allocate_lock() self.config_lock.acquire() self.frame = None self.filename = filename self.parser = ConfigParser.ConfigParser() self.parser.read([self.filename]) LOGDIR=os.path.join(self.filename.rsplit(os.sep, 1)[0], "logs") self.sections = { |
lowerpart = part.lower() matches = [x for x in set(list) if x.lower().startswith(lowerpart) and len(x) >= len(part)] | matches = GetCompletions(part, list) | def GetCompletion(part, list): lowerpart = part.lower() matches = [x for x in set(list) if x.lower().startswith(lowerpart) and len(x) >= len(part)] if len(matches) == 0: return None, 0 if len(matches) == 1: return matches[0], 1 else: return commonprefix([x.lower() for x in matches]), 0 |
widget.insert_text(newnick, ix) | widget.insert_text(newnick, preix) | def OnKeyPress(self, widget, event): if event.keyval == gtk.gdk.keyval_from_name("Prior"): scrolled = self.ChatScroll.get_parent() adj = scrolled.get_vadjustment() adj.set_value(adj.value - adj.page_increment) elif event.keyval == gtk.gdk.keyval_from_name("Next"): scrolled = self.ChatScroll.get_parent() adj = scrolled.... |
dialog = gtk.FileChooserDialog(parent=parent, action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT, gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT)) | dialog = gtk.FileChooserDialog(parent=parent, action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) | def SaveFile(parent = None, initialdir = "~", initialfile = "", title=None): dialog = gtk.FileChooserDialog(parent=parent, action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT, gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT)) dialog.set_action(gtk.FILE_CHOOSER_ACTION_SAVE) dialog.set_select_multiple... |
self.eventprocessor.logMessage(_("Denied file request: %s") % str(vars(msg)), 5) | self.eventprocessor.logMessage(_("Denied file request: User %s, %s") % (user, str(vars(msg))), 5) | def TransferRequestDownloads(self, msg, user, conn, addr): for i in self.downloads: if i.filename == msg.file and user == i.user and i.status == "Queued": # Remote peer is signalling a tranfer is ready, attempting to download it i.size = msg.filesize i.req = msg.req i.status = "Waiting for download" transfertimeout = T... |
self.eventprocessor.logMessage(_("Queued upload request: %s") % str(vars(msg)), 5) | self.eventprocessor.logMessage(_("Queued upload request: User %s, %s") % (user, str(vars(msg))), 5) | def QueueUpload(self, msg): """ Peer remotely(?) queued a download (upload here) """ user = None for i in self.peerconns: if i.conn is msg.conn.conn: user = i.username if user is None: return addr = msg.conn.addr[0] if not self.fileIsQueued(user, msg.file): friend = user in [i[0] for i in self.eventprocessor.userlist.u... |
print("sf: %s" % (repr(newsharedfiles))) print("") print("st: %s" % (repr(newsharedfilesstreams))) print("") print("wi: %s" % (repr(newwordindex))) print("") print("fi: %s" % (repr(newfileindex))) print("") print("mt: %s" % (newmtimes)) | def rescandirs(self, shared_directories, oldmtimes, oldfiles, sharedfilesstreams, yieldfunction, progress=None, name="", rebuild=False): """ Check for modified or new files via OS's last mtime on a directory, or, if rebuild is True, all directories """ #returns dict in format: { Directory : mtime, ... } gobject.idle_... | |
except IOError: | except: | def removelistener(self, callback): try: self.listeners.remove(callback) except KeyError: self.add("Failed to remove listener %s, does not exist." % (callback,), 1) |
return 1 | return True | def bmpx(self): if self.bus is None: self.frame.logMessage(_("ERROR: DBus not available:")+" "+"BMPx"+ " "+ _("cannot be contacted")) return try: bmp_object = self.bus.get_object('org.beepmediaplayer.bmp', '/Core') bmp_iface = self.bus.Interface(bmp_object, 'org.beepmediaplayer.bmp') except Exception, error: self.frame... |
return 1 | return True | def mpd(self): format = self.NPFormat.child.get_text() if "$a" in format: output = self.mpd_command("%artist%") if output: self.title["artist"] = output if "$t" in format: output = self.mpd_command("%title%") if output: self.title["title"] = output if "$n" in format: output = self.mpd_command("%artist% - %title%") if o... |
return 0 | return False | def banshee(self): slist = self.NPFormat.child.get_text() if "$n" in slist: commandlist = ["--query-artist", "--query-title"] else: commandlist = [] if "$t" in slist: commandlist.append("--query-title") if "$a" in slist: commandlist.append("--query-artist") if "$b" in slist: commandlist.append("--query-album") if "$k" ... |
return 1 | return True | def banshee(self): slist = self.NPFormat.child.get_text() if "$n" in slist: commandlist = ["--query-artist", "--query-title"] else: commandlist = [] if "$t" in slist: commandlist.append("--query-title") if "$a" in slist: commandlist.append("--query-artist") if "$b" in slist: commandlist.append("--query-album") if "$k" ... |
return 1 | return True | def amarok(self): slist = self.NPFormat.child.get_text() if "$n" in slist: output = self.amarok_command("nowPlaying") if output: self.title["nowplaying"] = output if "$t" in slist: output = self.amarok_command("title") if output: self.title["title"] = output if "$l" in slist: output = self.amarok_command("totalTime") ... |
return 0 return 1 | return False return True | def audacious(self): slist = self.NPFormat.child.get_text() output = "" self.audacious_running = True if "$n" in slist: artist = self.audacious_command('current-song-tuple-data', 'artist') title = self.audacious_command('current-song-tuple-data', 'title') if artist and title: self.title["nowplaying"] = artist + ' - ' +... |
return 1 | return True | def rhythmbox(self): from dbus import Interface if self.bus is None: self.frame.logMessage(_("ERROR: DBus not available:")+" "+"Rhythmbox"+ " "+ _("cannot be contacted")) return None try: proxyobj = self.bus.get_object("org.gnome.Rhythmbox", "/org/gnome/Rhythmbox/Shell") rbshell = Interface(proxyobj, "org.gnome.Rhythm... |
def foobar(self): if HAS_WIN32GUI: wnd_ids = [ '{DA7CD0DE-1602-45e6-89A1-C2CA151E008E}', '{97E27FAA-C0B3-4b8e-A693-ED7881E99FC1}', '{E7076D1C-A7BF-4f39-B771-BCBE88F2A2A8}' ] metadata = None for wnd_id in wnd_ids: wnd_txt = GetWindowText(FindWindow(wnd_id, None)) if wnd_txt: m = re.match("(.*)\s+\[foobar.*", wnd_txt) ... | def rhythmbox(self): from dbus import Interface if self.bus is None: self.frame.logMessage(_("ERROR: DBus not available:")+" "+"Rhythmbox"+ " "+ _("cannot be contacted")) return None try: proxyobj = self.bus.get_object("org.gnome.Rhythmbox", "/org/gnome/Rhythmbox/Shell") rbshell = Interface(proxyobj, "org.gnome.Rhythm... | |
return 1 | return True | def lastfm_parse(buf): from time import time, altzone try: i = buf.index("<artist") i = buf[i+1:].index(">") + i + 2 j = buf[i:].index("<") + i |
return 1 | return True | def xmms(self): if not os.path.exists("/tmp/xmms-info"): self.frame.logMessage(_("ERROR: /tmp/xmms-info does not exist. Is the Infopipe plugin installed and is XMMS running?")) return None try: fsock = file("/tmp/xmms-info") do = fsock.read().split("\n") fsock.close() if len(do) == 0: self.frame.logMessage(_("ERROR: /... |
path = self.selected_folder | node = self.selected_folder path = self.DirStore.GetPathString(node) | def OnCopyDirURL(self, widget): if self.selected_folder is None: return path = self.selected_folder if path[:-1] != "/": path += "/" self.frame.SetClipboardURL(self.user, path) |
newsharedfilesstreams = self.getFilesStreams(newmtimes, oldmtimes, sharedfilesstreams, newsharedfiles, yieldfunction) | if win32: newsharedfilesstreams = self.getFilesStreamsUnicode(newmtimes, oldmtimes, sharedfilesstreams, newsharedfiles, yieldfunction) else: newsharedfilesstreams = self.getFilesStreams(newmtimes, oldmtimes, sharedfilesstreams, newsharedfiles, yieldfunction) | def rescandirs(self, shared_directories, oldmtimes, oldfiles, sharedfilesstreams, yieldfunction, progress=None, name="", rebuild=False): """ Check for modified or new files via OS's last mtime on a directory, or, if rebuild is True, all directories """ #returns dict in format: { Directory : mtime, ... } gobject.idle_... |
print("sf: %s" % (repr(newsharedfiles))) print("") print("st: %s" % (repr(newsharedfilesstreams))) print("") print("wi: %s" % (repr(newwordindex))) print("") print("fi: %s" % (repr(newfileindex))) print("") print("mt: %s" % (newmtimes)) | def rescandirs(self, shared_directories, oldmtimes, oldfiles, sharedfilesstreams, yieldfunction, progress=None, name="", rebuild=False): """ Check for modified or new files via OS's last mtime on a directory, or, if rebuild is True, all directories """ #returns dict in format: { Directory : mtime, ... } gobject.idle_... | |
print "Dropping missing directory %s" % directory | print "2S. Dropping missing directory %s" % directory | def getFilesStreams(self, mtimes, oldmtimes, oldstreams, newsharedfiles, yieldcall = None): streams = {} for directory in mtimes.keys(): if self.hiddenCheck(directory): continue |
if self.NP_infopipe.get_active(): result = self.xmms() elif self.NP_amarok.get_active(): result = self.amarok() elif self.NP_amarok2.get_active(): result = self.amarok2() elif self.NP_audacious.get_active(): result = self.audacious() elif self.NP_mpd.get_active(): result = self.mpd() elif self.NP_banshee.get_active(): ... | try: if self.NP_infopipe.get_active(): result = self.xmms() elif self.NP_amarok.get_active(): result = self.amarok() elif self.NP_amarok2.get_active(): result = self.amarok2() elif self.NP_audacious.get_active(): result = self.audacious() elif self.NP_mpd.get_active(): result = self.mpd() elif self.NP_banshee.get_activ... | def GetNP(self, widget, test=None, callback=None): self.title_clear() if self.NP_infopipe.get_active(): result = self.xmms() elif self.NP_amarok.get_active(): result = self.amarok() elif self.NP_amarok2.get_active(): result = self.amarok2() elif self.NP_audacious.get_active(): result = self.audacious() elif self.NP_mpd... |
print "'"+output+"'" | def banshee(self): slist = self.NPFormat.child.get_text() if "$n" in slist: commandlist = ["--query-artist", "--query-title"] else: commandlist = [] if "$t" in slist: commandlist.append("--query-title") if "$a" in slist: commandlist.append("--query-artist") if "$b" in slist: commandlist.append("--query-album") if "$k" ... | |
print matches | def banshee(self): slist = self.NPFormat.child.get_text() if "$n" in slist: commandlist = ["--query-artist", "--query-title"] else: commandlist = [] if "$t" in slist: commandlist.append("--query-title") if "$a" in slist: commandlist.append("--query-artist") if "$b" in slist: commandlist.append("--query-album") if "$k" ... | |
return executeCommand("banshee $", " ".join(commands), returnoutput=True) | return executeCommand(" ".join(["banshee"] + commands), returnoutput=True) | def banshee_command(self, commands): return executeCommand("banshee $", " ".join(commands), returnoutput=True) #return subprocess.Popen(["banshee"]+commands, stdout=subprocess.PIPE).communicate()[0] |
p = subprocess.Popen(["/usr/sbin/getenforce"], shell=True, stdout=subprocess.PIPE, close_fds=True) p.wait() if p.stdout.read().strip() == "Disabled": return False return True | try: if open("/selinux/enforce").read().strip() in ("1", "0"): return True except: pass return False | def selinuxEnabled(): p = subprocess.Popen(["/usr/sbin/getenforce"], shell=True, stdout=subprocess.PIPE, close_fds=True) p.wait() if p.stdout.read().strip() == "Disabled": return False return True |
"--exclude=proc", "--exclude=sys", "--exclude=dev", | "--exclude=./proc", "--exclude=./sys", "--exclude=./dev", | def _rootCachePostInitHook(self): try: self._rootCacheLock(shared=0) # nuke any rpmdb tmp files for tmp in glob(self.rootObj.makeChrootPath('var/lib/rpm/__db*')): os.unlink(tmp) |
log.debug("copying %s to %s" % (src, dest)) | log.info("copying %s to %s" % (src, dest)) | def main(ret): "Main executable entry point." # drop unprivleged to parse args, etc. # uidManager saves current real uid/gid which are unpriviledged (callers) # due to suid helper, our current effective uid is 0 # also supports being run by sudo # # setuid wrapper has real uid = unpriv, effective uid = 0 # s... |
mock.util.rmtree(self.basedir, selinux=self.selinux) | self._unlock_and_rm_chroot() | def clean(self): """clean out chroot with extreme prejudice :)""" self.tryLockBuildRoot() self.state("clean") self._callHooks('clean') mock.util.rmtree(self.basedir, selinux=self.selinux) self.chrootWasCleaned = True |
mock.util.rmtree(self.basedir, selinux=self.selinux) | self._unlock_and_rm_chroot() | def scrub(self, scrub_opts): """clean out chroot and/or cache dirs with extreme prejudice :)""" self.tryLockBuildRoot() self.state("clean") self._callHooks('clean') for scrub in scrub_opts: if scrub == 'all': mock.util.rmtree(self.basedir, selinux=self.selinux) self.chrootWasCleaned = True mock.util.rmtree(self.cachedi... |
if os.path.realpath(mountpoint).startswith(os.path.realpath(self.makeChrootPath() + "/")): | if os.path.realpath(mountpoint).startswith(os.path.realpath(self.makeChrootPath()) + "/"): | def _umountall(self): """umount all mounted chroot fs.""" # first try removing all expected mountpoints. for cmd in reversed(self.umountCmds): try: mock.util.do(cmd, raiseExc=1, shell=True) except mock.exception.Error, e: # the exception already contains info about the error. self.root_log.warning(e) # then remove anyt... |
def __init(self, msg): | def __init__(self, msg): | def __init(self, msg): Error.__init__(self, msg) self.msg = msg self.resultcode = 06 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.