rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
print '\n%d distinct words between current and new lambda:' % len(distinct_words) print distinct_words print print 'current lambda before merge' print self._words.items() print print 'new lambda before merge' print otherlambda._words.items() print | def merge(self, otherlambda, rhot): ''' fold the word counts in another DirichletWords object into this one, weighted by rhot. assumes self.num_topics is the same for both objects. ''' all_words = self._words.keys() + otherlambda._words.keys() distinct_words = list(set(all_words)) | |
print 'old lambda words: %d' % self._words.N() print 'new lambda words: %d' % otherlambda._words.N() print 'total number of words: %d' % total_words self_scale = (1-rhot)*total_words/float(self._words.N()) | self_scale = (1.0-rhot)*total_words/float(self._words.N()) | def merge(self, otherlambda, rhot): ''' fold the word counts in another DirichletWords object into this one, weighted by rhot. assumes self.num_topics is the same for both objects. ''' all_words = self._words.keys() + otherlambda._words.keys() distinct_words = list(set(all_words)) |
print ("word frequencies for %s: current: %f other: %f. weighting: %f" % (word, self._words[word], otherlambda._words[word], rhot)) | def merge(self, otherlambda, rhot): ''' fold the word counts in another DirichletWords object into this one, weighted by rhot. assumes self.num_topics is the same for both objects. ''' all_words = self._words.keys() + otherlambda._words.keys() distinct_words = list(set(all_words)) | |
def __init__(self, K, alpha, eta, tau0, kappa): | def __init__(self, K, alpha, eta, tau0, kappa, sanity_check=False): | def __init__(self, K, alpha, eta, tau0, kappa): """ Arguments: K: Number of topics alpha: Hyperparameter for prior on weight vectors theta eta: Hyperparameter for prior on topics beta tau0: A (positive) learning parameter that downweights early iterations kappa: Learning rate: exponential decay rate---should be between... |
self.sanity_check = sanity_check | def __init__(self, K, alpha, eta, tau0, kappa): """ Arguments: K: Number of topics alpha: Hyperparameter for prior on weight vectors theta eta: Hyperparameter for prior on topics beta tau0: A (positive) learning parameter that downweights early iterations kappa: Learning rate: exponential decay rate---should be between... | |
self._lambda = DirichletWords(self._K) | self._lambda = DirichletWords(self._K, sanity_check=self.sanity_check) | def __init__(self, K, alpha, eta, tau0, kappa): """ Arguments: K: Number of topics alpha: Hyperparameter for prior on weight vectors theta eta: Hyperparameter for prior on topics beta tau0: A (positive) learning parameter that downweights early iterations kappa: Learning rate: exponential decay rate---should be between... |
new_lambda = DirichletWords(self._K) | new_lambda = DirichletWords(self._K, sanity_check=self.sanity_check) | def do_e_step(self, docs): """ Given a mini-batch of documents, estimates the parameters gamma controlling the variational distribution over the topic weights for each document in the mini-batch. |
print 'alpha:' print alpha print len(alpha) if (len(alpha) == 1): | if (len(alpha.shape) == 1): | def dirichlet_expectation(alpha): """ alpha is a W by K dimensional matric. For a vector theta ~ Dir(alpha), computes E[log(theta)] given alpha. Returns a W x K matrix. """ print 'alpha:' print alpha print len(alpha) # len(alpha) for an n.random.gamma obj is k, or num topics. if (len(alpha) == 1): return(psi(alpha) - p... |
lambda_stats = n.outer(expElogthetad.T, cts/phinorm) * self._expElogbeta for wordid, ct in zip(ids, cts): for topic in self._K: stats_wk = lambda_stats[topic, word] | print 'shapes expElogthetad.T, cts, phinorm, expElogbetad' print expElogthetad.T.shape print len(cts) print phinorm print expElogbetad.shape print lambda_stats = n.outer(expElogthetad.T, cts/phinorm) * expElogbetad lambda_data = zip(ids, lambda_stats.T) print 'shape lambda_stats = %s' % str(lambda_stats.shape) ... | def do_e_step(self, docs): """ Given a mini-batch of documents, estimates the parameters gamma controlling the variational distribution over the topic weights for each document in the mini-batch. |
new_lambda.update_counts(word, topic, stats_wk) | new_lambda.update_count(word, topic, stats_wk) print "sum over stats for this word for all topics: %f" % sum(stats) | def do_e_step(self, docs): """ Given a mini-batch of documents, estimates the parameters gamma controlling the variational distribution over the topic weights for each document in the mini-batch. |
score = score + n.sum((self._eta-self._lambda)*self._Elogbeta) score = score + n.sum(gammaln(self._lambda) - gammaln(self._eta)) | score = score + n.sum((self._eta-self._lambda.as_matrix())*self._Elogbeta) score = score + n.sum(gammaln(self._lambda.as_matrix()) - gammaln(self._eta)) | def approx_bound(self, docs, gamma): """ Estimates the variational bound over *all documents* using only the documents passed in as "docs." gamma is the set of parameters to the variational distribution q(theta) corresponding to the set of documents passed in. |
gammaln(n.sum(self._lambda, 1))) | gammaln(n.sum(self._lambda.as_matrix(), 1))) | def approx_bound(self, docs, gamma): """ Estimates the variational bound over *all documents* using only the documents passed in as "docs." gamma is the set of parameters to the variational distribution q(theta) corresponding to the set of documents passed in. |
self.users.append(connection.person.nickname()); | ul = UserAndLocation(); ul.person = connection.person ul.latitude = connection.latitude ul.longitude = connection.longitude self.users.append(ul); | def dispatch(self): people_query = Connection.all(); self.users = []; for connection in people_query: self.users.append(connection.person.nickname()); people_query = Connection.all(); response = "{action: '"+self.action+"', users : "+simplejson.dumps(self.users)+"}"; for connection in people_query: channel.send_message... |
response = "{action: '"+self.action+"', users : "+simplejson.dumps(self.users)+"}"; | response = { 'action': self.action, 'users' : self.get_users_json() }; | def dispatch(self): people_query = Connection.all(); self.users = []; for connection in people_query: self.users.append(connection.person.nickname()); people_query = Connection.all(); response = "{action: '"+self.action+"', users : "+simplejson.dumps(self.users)+"}"; for connection in people_query: channel.send_message... |
channel.send_message(connection.channelKey, response); | logging.log(logging.INFO, "to " + connection.channelKey + ": " + simplejson.dumps(response)) channel.send_message(connection.channelKey, simplejson.dumps(response)); | def dispatch(self): people_query = Connection.all(); self.users = []; for connection in people_query: self.users.append(connection.person.nickname()); people_query = Connection.all(); response = "{action: '"+self.action+"', users : "+simplejson.dumps(self.users)+"}"; for connection in people_query: channel.send_message... |
user = users.get_current_user(); channel.send_message(key, "{ message : 'welcome " + user.nickname() + "' }"); | lat = self.request.get('latitude'); lng = self.request.get('longitude'); c = Connection.gql("where channelKey='" + key + "'"); for connection in c: connection.latitude = float(lat) connection.longitude = float(lng) db.put(connection) | def post(self): |
self.response.out.write(simplejson.dumps(respo)); | self.response.out.write(respo); | def get(self): people_query = Connection.all(); respo = []; for connection in people_query: respo.append(connection.person.nickname()); self.response.out.write(simplejson.dumps(respo)); |
userkey = user.user_id() connection = Connection(key_name = userkey); connection.person = user connection.channelKey = userkey; connection.put(); token = channel.create_channel(user.user_id()) | userkey = addConnection(); token = channel.create_channel(userkey) | def get(self): user = users.get_current_user() client = gdata.docs.client.DocsClient(source='eveny-nebulae-v1') client.ClientLogin("trinity.testbot@gmail.com", "!@#$qwer", client.source) documents_feed = client.GetDocList(uri='/feeds/default/private/full/-/pending') if user: url = users.create_logout_url(self.request.... |
'key': user.user_id(), | 'key': userkey, | def get(self): user = users.get_current_user() client = gdata.docs.client.DocsClient(source='eveny-nebulae-v1') client.ClientLogin("trinity.testbot@gmail.com", "!@#$qwer", client.source) documents_feed = client.GetDocList(uri='/feeds/default/private/full/-/pending') if user: url = users.create_logout_url(self.request.... |
def addConnection(): user = users.get_current_user() if user: userkey = user.user_id() connection = Connection(key_name = userkey); connection.person = user connection.channelKey = userkey; connection.position = db.GeoPt(0, 0); connection.put(); return userkey; | def get(self): user = users.get_current_user() client = gdata.docs.client.DocsClient(source='eveny-nebulae-v1') client.ClientLogin("trinity.testbot@gmail.com", "!@#$qwer", client.source) documents_feed = client.GetDocList(uri='/feeds/default/private/full/-/pending') if user: url = users.create_logout_url(self.request.... | |
'DEBUG', | def __setattr__(self, name, value): if name.startswith('_'): return object.__setattr__(self, name, value) self._wait_fn() self._wait_fn = int setattr(self._object, name, value) | |
'DEBUG', | def bundle_djvu(*component_filenames): djvu_file = temporary.file(suffix='.djvu') args = ['djvm', '-c', djvu_file.name] args += component_filenames return ipc.Proxy(djvu_file, ipc.Subprocess(args).wait, None) | |
return 'Command %r was interrputed by signal %s' % (self.args[0], signal_name) | return 'Command %r was interrupted by signal %s' % (self.args[0], signal_name) | def __str__(self): signal_name = self._signal_names.get(self.args[1], self.args[1]) return 'Command %r was interrputed by signal %s' % (self.args[0], signal_name) |
self.mask_filename = None | self.mask_filename = mask_filename | def handle_args(self, image_filename, mask_filename=None): self.image_filename = image_filename self.mask_filename = None |
'LOSS_LEVEL_MIN', 'LOSS_LEVEL_DEFAULT', 'LOSS_LEVEL_MAX', | 'LOSS_LEVEL_MIN', 'LOSS_LEVEL_CLEAN', 'LOSS_LEVEL_LOSSY', 'LOSS_LEVEL_MAX', | def bundle_djvu(*component_filenames): assert len(component_filenames) > 0 if any(c.endswith('.iff') for c in component_filenames): # We can't use ``djvm -c``. return bundle_djvu_via_indirect(*component_filenames) raise NotImplementedError else: djvu_file = temporary.file(suffix='.djvu') args = ['djvm', '-c', djvu_file... |
copy_file(tmp_output.name, output) | copy_file(tmp_output, output) | def separate_one(self, o, image_filename, output): gamera.init() bytes_in = os.path.getsize(image_filename) print >>self.log(1), '%s:' % image_filename print >>self.log(1), '- reading image' image = gamera.from_pil(Image.open(image_filename)) width, height = image.ncols, image.nrows print >>self.log(2), '- image size: ... |
mask = gamera.load_image(mask_filename) | def separate_one(self, o, image_filename, output): gamera.init() bytes_in = os.path.getsize(image_filename) print >>self.log(1), '%s:' % image_filename print >>self.log(1), '- reading image' image = gamera.from_pil(Image.open(image_filename)) width, height = image.ncols, image.nrows print >>self.log(2), '- image size: ... | |
logger.nosy(self.compression_info_template, **locals()) | logger.nosy('%s', self.compression_info_template % locals()) | def chdir(): os.chdir(minidjvu_out_dir) |
width = height = dpi = None | self.width = self.height = self.dpi = None | def _load_file(self): args = ['djvudump', self._file.name] dump = ipc.Subprocess(args, stdout=ipc.PIPE) width = height = dpi = None keys = set() try: header = dump.stdout.readline() if not header.startswith(' FORM:DJVU '): raise ValueError for line in dump.stdout: if line[:4] == ' ' and line[8:9] == ' ': key = line... |
return int.__new__(cls) | return n | def __new__(cls, n): if not (x <= n <= y): raise ValueError return int.__new__(cls) |
kwargs.setdefault('prefix', 'didjvu') | kwargs.setdefault('prefix', 'didjvu.') | def directory(*args, **kwargs): kwargs = dict(kwargs) kwargs.setdefault('prefix', 'didjvu') tmpdir = tempfile.mkdtemp(*args, **kwargs) try: yield tmpdir finally: shutil.rmtree(tmpdir) |
if v is None: continue if '+' in v: | if var is None: continue if '+' in var: | def expand_template(template, name, page): ''' >>> path = '/path/to/eggs.png' >>> expand_template('{name}', path, 0) '/path/to/eggs.png' >>> expand_template('{base}', path, 0) 'eggs.png' >>> expand_template('{name-ext}.djvu', path, 0) '/path/to/eggs.djvu' >>> expand_template('{base-ext}.djvu', path, 0) 'eggs.djvu' >>> ... |
elif '-' in v: | elif '-' in var: | def expand_template(template, name, page): ''' >>> path = '/path/to/eggs.png' >>> expand_template('{name}', path, 0) '/path/to/eggs.png' >>> expand_template('{base}', path, 0) 'eggs.png' >>> expand_template('{name-ext}.djvu', path, 0) '/path/to/eggs.djvu' >>> expand_template('{base-ext}.djvu', path, 0) 'eggs.djvu' >>> ... |
os.system('djvudump ' + index_file.name) | def bundle_djvu_via_indirect(*component_filenames): with temporary.directory() as tmpdir: pageids = [] page_sizes = [] for filename in component_filenames: pageid = os.path.basename(filename) os.symlink(filename, os.path.join(tmpdir, pageid)) pageids += [pageid] page_size = os.path.getsize(filename) if page_size >= 1 <... | |
self.offset += amount | self.address += amount | def consume(self, amount): res = memory._read(self.address, amount) self.offset += amount return res |
self.offset += len(data) | self.address += len(data) | def write(self, data): res = memory._write(self.address, data) self.offset += len(data) return res |
res = stringToNumber(getImmediate(instruction)) | imm = getImmediate(instruction) l = len(imm) ofs = stringToNumber(imm) | def getRelativeAddress(pc, instruction): res = stringToNumber(getImmediate(instruction)) pc += length(instruction) if res & 0x80000000: return pc - (0x100000000 - res) return pc + res |
if res & 0x80000000: return pc - (0x100000000 - res) return pc + res | if ofs & 0x80000000: return pc - (0x100000000 - ofs) elif (l == 2) and (ofs & 0x8000): return pc - (0x10000 - ofs) elif (l == 1) and (ofs & 0x80): return pc - (0x100 - ofs) return pc + ofs | def getRelativeAddress(pc, instruction): res = stringToNumber(getImmediate(instruction)) pc += length(instruction) if res & 0x80000000: return pc - (0x100000000 - res) return pc + res |
bs = self.blocksize() | def load(self): assert self.value is not None, 'Parent must initialize self.value' | |
block = self.source.consume(self.blocksize()) | block = self.source.consume(bs) | def load(self): assert self.value is not None, 'Parent must initialize self.value' |
if !os.path.isfile(source.outfile): command = commandBase + " -o " + source.outfile | if not os.path.isfile(source.outfile): command = commandBase + " -o " + source.outfile \ | def compileSources(commandBase, sources): for source in sources: if !os.path.isfile(source.outfile): command = commandBase + " -o " + source.outfile + " " + source.filename print command os.system(command) |
def __init__(self, path): | def __init__(self, path, ptx): | def __init__(self, path): self.filename = os.path.abspath(path) self.outfile = self.filename + ".cpp" |
self.outfile = self.filename + ".cpp" | if ptx: self.outfile = self.filename[:-3] + ".ptx" else: self.outfile = self.filename + ".cpp" | def __init__(self, path): self.filename = os.path.abspath(path) self.outfile = self.filename + ".cpp" |
def getAllCudaSources(path): | def getAllCudaSources(path, ptx): | def getAllCudaSources(path): sources = [] for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: name = os.path.join(dirpath, filename) if os.path.isfile(name): split = name.rsplit('.', 1) extension = "" if len(split) == 2: extension = split[1] if extension == "cu": sources.append(CudaSource(name... |
sources.append(CudaSource(name)) | sources.append(CudaSource(name, ptx)) | def getAllCudaSources(path): sources = [] for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: name = os.path.join(dirpath, filename) if os.path.isfile(name): split = name.rsplit('.', 1) extension = "" if len(split) == 2: extension = split[1] if extension == "cu": sources.append(CudaSource(name... |
def compileSources(commandBase, sources): | def compileSources(commandBase, sources, continueOnError): | def compileSources(commandBase, sources): for source in sources: if not os.path.isfile(source.outfile): command = commandBase + " -o " + source.outfile \ + " " + source.filename print command os.system(command) if not os.path.isfile(source.outfile): print 'error - compiling \'' + source.filename \ + '\' failed. abortin... |
command = commandBase + " -o " + source.outfile \ + " " + source.filename | command = commandBase + " -I" + os.path.dirname(source.filename) \ + " -o " + source.outfile + " " + source.filename | def compileSources(commandBase, sources): for source in sources: if not os.path.isfile(source.outfile): command = commandBase + " -o " + source.outfile \ + " " + source.filename print command os.system(command) if not os.path.isfile(source.outfile): print 'error - compiling \'' + source.filename \ + '\' failed. abortin... |
if not os.path.isfile(source.outfile): | if not os.path.isfile(source.outfile) and not continueOnError: | def compileSources(commandBase, sources): for source in sources: if not os.path.isfile(source.outfile): command = commandBase + " -o " + source.outfile \ + " " + source.filename print command os.system(command) if not os.path.isfile(source.outfile): print 'error - compiling \'' + source.filename \ + '\' failed. abortin... |
command = "nvcc --cuda " + options.arguments | if options.ptx: command = "nvcc --ptx " + options.arguments else: command = "nvcc --cuda " + options.arguments | def main(): parser = OptionParser() parser.add_option("-d", "--directory", action="store", default=".", dest="directory", help="The directory to run on.") parser.add_option("-a", "--arguments", action="store", default="-I ~/checkout/thrust -I ./sdk", dest="arguments", help="NVCC options.") parser.add_option("-c", "--c... |
sources = getAllCudaSources(options.directory) if options.clean: clean(sources) elif options.sanitize: sanitizeSources(sources) | sources = getAllCudaSources(options.directory, options.ptx) if options.ptx: compileSources(command, sources, True) | def main(): parser = OptionParser() parser.add_option("-d", "--directory", action="store", default=".", dest="directory", help="The directory to run on.") parser.add_option("-a", "--arguments", action="store", default="-I ~/checkout/thrust -I ./sdk", dest="arguments", help="NVCC options.") parser.add_option("-c", "--c... |
compileSources(command, sources) sanitizeSources(sources) | if options.clean: clean(sources) elif options.sanitize: sanitizeSources(sources) else: compileSources(command, sources, False) sanitizeSources(sources) | def main(): parser = OptionParser() parser.add_option("-d", "--directory", action="store", default=".", dest="directory", help="The directory to run on.") parser.add_option("-a", "--arguments", action="store", default="-I ~/checkout/thrust -I ./sdk", dest="arguments", help="NVCC options.") parser.add_option("-c", "--c... |
def add_folder(parts): while parts[0] not in self.folders: self.folders[parts[0]] = Folder("/".join(parts)) parts = parts[0].rsplit('/', 1) | def load_project_files(self): file_list = get_tracked_files_hg(self.root_path) | |
add_folder(parts) | def add_folder(parts): while parts[0] not in self.folders: self.folders[parts[0]] = Folder("/".join(parts)) parts = parts[0].rsplit('/', 1) | |
params["initiator"] = self.account["account"] | try: initiator = self.account["account"] except TypeError: params = self.account.Get(ACCOUNT, "Parameters") initiator = params["account"] params["initiator"] = initiator | def finish_tube_offer(self, tube): self.info("offering my tube located at %r", tube.object_path) service_name = tube.props[CHANNEL_TYPE_DBUS_TUBE + ".ServiceName"] params = self._tubes_to_offer[service_name] params["initiator"] = self.account["account"] address = tube[CHANNEL_TYPE_DBUS_TUBE].Offer(params, SOCKET_ACCESS... |
def __init__(self, path, alwaysCreate=False): static.File.__init__(self, unquote(path), alwaysCreate) | def downloadPage(url, file, contextFactory=None, *args, **kwargs): """Download a web page to a file. @param file: path to file on filesystem, or file-like object. See HTTPDownloader to see what extra args can be passed. """ scheme, host, port, path = client._parse(url) factory = HeaderAwareHTTPDownloader(url, file, *... | |
self.ctrl = None | def setup_part2(self): | |
file = gio.File(file=path_path); | file = gio.File(file=face_path); | def activate(self, shell): from twisted.internet import gtk2reactor try: gtk2reactor.install() except AssertionError, e: # sometimes it's already installed print e |
self.warning("Can't load plugin %s (%s), maybe missing dependencies..." % (entrypoint.name,msg)) | self.warning("Can't load plugin %s (%s), maybe missing dependencies..." % (plugin.name,msg)) | def __getitem__(self, key): plugin = self._plugins.__getitem__(key) if pkg_resources and isinstance(plugin, pkg_resources.EntryPoint): try: plugin = plugin.load(require=False) except (ImportError, AttributeError, pkg_resources.ResolutionError), msg: self.warning("Can't load plugin %s (%s), maybe missing dependencies...... |
i['url'] = icon.find('./{%s}url' % ns).text if i['url'].startswith('/'): i['url'] = ''.join((url_base,i['url'])) | i['url'] = self.make_fullyqualified(i['realurl']) | def parse_device(self, d): self.info("parse_device %r" %d) self.device_type = unicode(d.findtext('./{%s}deviceType' % ns)) self.friendly_device_type, self.device_type_version = \ self.device_type.split(':')[-2:] self.friendly_name = unicode(d.findtext('./{%s}friendlyName' % ns)) self.udn = d.findtext('./{%s}UDN' % ns) ... |
conn_obj = self.conn[CONNECTION] conn_obj.connect_to_signal('StatusChanged', self.status_changed_cb) conn_obj.connect_to_signal('NewChannels', self.new_channels_cb) | self.conn[CONNECTION].connect_to_signal('StatusChanged', self.status_changed_cb) | def __init__(self, manager, protocol, account, muc_id, conference_server=None, existing_client=False): log.Loggable.__init__(self) self.account = account self.existing_client = existing_client self.channel_text = None self._unsent_messages = [] self._tube_conns = {} self._tubes = {} self._channels = [] self._pending_tu... |
option.widget.style().drawControl(QtGui.QStyle.CE_ItemViewItem,option,painter) | QtGui.QApplication.style().drawControl(QtGui.QStyle.CE_ItemViewItem,option,painter) | def _drawControl(self,option,painter): option.widget.style().drawControl(QtGui.QStyle.CE_ItemViewItem,option,painter) |
try: cacheCover(elementId,size) except IOError: return None return dir+str(elementId) | if size is None: return None else: try: cacheCover(elementId,size) return dir+str(elementId) except IOError: return None else: return dir+str(elementId) | def getCoverPath(elementId,size=None): """Return the path to the cover of the element with id <elementId> in size <size>x<size> pixel or in original size, if <size> is None.""" assert isinstance(elementId,int) if size is None: dir = COVER_DIR+"large/" else: dir = COVER_DIR+"cache_{0}/".format(size) if not os.path.exis... |
criteria.searchTags = options.tags.search_tags | criteria.searchTags = [tags.get(tag) for tag in options.tags.search_tags] | def init(): """Initialize the search-module.""" global db criteria.searchTags = options.tags.search_tags db = database.get() db.query("DROP TABLE IF EXISTS {0}".format(TT_HELP)) db.query(""" CREATE TABLE IF NOT EXISTS {0} ( id MEDIUMINT UNSIGNED NOT NULL, value MEDIUMINT UNSIGNED NULL) CHARACTER SET 'utf8'; """.format(... |
tagsToSearch = tags.tagList() | tagsToSearch = tags.tagList | def getQuery(self,fromTable,columns=None): """Return a SELECT-query fetching the rows of <fromTable> which fulfill this criterion. <fromTable> must contain an 'id'-column holding container-ids. By default only the id-column of <fromTable> is selected, but you can specify a list of columns in the <column>-parameter. """... |
self.setPosition(len(self.covers)-1) | self.setPosition(len(self.coverData)-1) | def _handleCustomCoverButton(self): fileName = QtGui.QFileDialog.getOpenFileName(self,"Cover öffnen",os.path.expanduser("~"), "Bilddateien (*.png *.jpg *.bmp);;Alle Dateien (*)"); if fileName == "": # user cancelled the dialog return image = QtGui.QPixmap(fileName) if image.isNull(): QtGui.QMessageBox(QtGui.QMessageBo... |
self.setPosition(len(self.covers)-1) | self.setPosition(len(self.coverData)-1) | def _httpRequestFinished(self,text,buffer,id,error): # For some reason Qt fires this event twice, the first time with another requestId. I have no idead where that requestId comes from... if id != self.requestId: return if not error: self.requestId = None image = QtGui.QPixmap() if image.loadFromData(buffer.buffer()):... |
self.covers = [] self.texts = [] | self.coverData = [] | def clear(self): self.covers = [] self.texts = [] self.nextButton.setEnabled(False) self.prevButton.setEnabled(False) self.saveButton.setEnabled(False) self.imageLabel.setPixmap(QtGui.QPixmap()) self.textLabel.setText("") self.numberLabel.setText("") self.setPosition(None) |
"Track":"tracknumber", "Year":"date" | "track":"tracknumber", "year":"date", | def __str__(self): return repr(self.tag) |
if tag in APE_MAPPING: tag = APE_MAPPING[tag] | if tag.lower() in APE_MAPPING: tag = APE_MAPPING[tag.lower()] | def __init__(self,path): TagFile.__init__(self,path) f = self.mutagen_file for tag in f.tags: value = f.tags[tag].value.decode("utf-8") if tag in APE_MAPPING: tag = APE_MAPPING[tag] if not tag.lower() in self.tags: self.tags[tag.lower()] = [] self.tags[tag.lower()].append(value) |
"Track":"tracknumber" | "Track":"tracknumber", "Year":"date" | def __str__(self): return repr(self.tag) |
if self.type in (int, str, bool): | if self.type == bool: if value == "0" or value.lower() == "false": value = False else: value = self.type(value) elif self.type in (int, str): | def updateValue(self, value, updateFileValue = False): if not isinstance(value, self.type): if self.type in (int, str, bool): value = self.type(value) elif self.type == list and isinstance(value, str): value = [x.strip(" \t") for x in value.split(",")] else: raise ConfigError("Type of {} does not match type of this opt... |
from gui import control as controlwidget | from omg.gui import control as controlwidget | def createWidget(parent): """Create a ControlWidget and store a reference to it in this control.widget.""" from gui import control as controlwidget globals()["widget"] = controlwidget.ControlWidget(parent) return widget |
return db.query(self.createQuery) | db.query(self.createQuery) | def create(self): """Create this table by executing its createQuery.""" if self.exists(): raise DBLayoutException("Table '{0}' does already exist.".format(self.name)) return db.query(self.createQuery) |
return self.create() | self.create() | def reset(self): """Drop this table and create it without data again. All table rows will be lost!""" if self.exists(): db.query("DROP table {0}".format(self.name)) return self.create() |
return self.root.hasChildren() return self.data(index).hasChildren() | if self.root is None: return False else: return self.root.hasChildren() else: return self.data(index).hasChildren() | def hasChildren(self,index): if not index.isValid(): return self.root.hasChildren() return self.data(index).hasChildren() |
if not smallCover.save(dir+str(id)+".png"): | if not smallCover.save(dir+str(id),"png"): | def cacheCover(id,size): """Create a thumbnail of the cover of the container with the given id with <size>x<size> pixels and cache it in the appropriate cache-folder.""" size = int(size) largeCover = QtGui.QImage(COVER_DIR+"large/"+str(id)) if largeCover.isNull(): raise IOError("Cover of container {0} could not be load... |
shutil.move(dir+str(id)+".png",dir+str(id)) | def cacheCover(id,size): """Create a thumbnail of the cover of the container with the given id with <size>x<size> pixels and cache it in the appropriate cache-folder.""" size = int(size) largeCover = QtGui.QImage(COVER_DIR+"large/"+str(id)) if largeCover.isNull(): raise IOError("Cover of container {0} could not be load... | |
database.get().query("TRUNCATE TABLE ?",TT_BIG_RESULT) | database.get().query("TRUNCATE TABLE {0}".format(TT_BIG_RESULT)) | def search(self): """Search for the value in the search-box. If it is empty, display all values.""" if self.searchBox.text(): search.stdTextSearch(self.searchBox.text(),TT_BIG_RESULT) self.table = TT_BIG_RESULT else: self.table = "containers" database.get().query("TRUNCATE TABLE ?",TT_BIG_RESULT) for view in self.view... |
painter.fillRect(option.rect,background) | option.backgroundBrush = background | def paint(self,painter,option,index): if self.context is not None: # When an exception is raised in paint or sizeHint, it won't stop the programm. Paint/sizeHint is then called all the time and spams the console with unhelpful errors ("painter ended with unrestored states") which hide the exception's own error message.... |
escapeDict = { '\\': '\\\\', "'": "\\'", '"': '\\"', '\x00': '\\0', '0x1A': '\\Z', '\n': '\\n', '\r': '\\r' } if likeStatement: escapeDict.update({'%':'\%','_':'\_'}) return strutils.replace(string,escapeDict) | return _escapeString(self,string,likeStatement) | def escapeString(self,string,likeStatement=False): """Escape a string for insertion in MySql queries. This function escapes the characters which are listed in the documentation of mysql_real_escape_string and is used as a replacement for that function. But it doesn't emulate mysql_real_escape string correctly, which w... |
print >> sys.stderr, "G3 f2py support is not implemented, yet." | sys.stderr.write("G3 f2py support is not implemented, yet.\n") | def generate_f2py_py(build_dir): f2py_exe = 'f2py'+os.path.basename(sys.executable)[6:] if f2py_exe[-4:]=='.exe': f2py_exe = f2py_exe[:-4] + '.py' if 'bdist_wininst' in sys.argv and f2py_exe[-3:] != '.py': f2py_exe = f2py_exe + '.py' target = os.path.join(build_dir,f2py_exe) if newer(__file__,target): log.info('Creatin... |
print >> sys.stderr, "Unknown mode:",`mode` | sys.stderr.write("Unknown mode: '%s'\n" % mode) | def generate_f2py_py(build_dir): f2py_exe = 'f2py'+os.path.basename(sys.executable)[6:] if f2py_exe[-4:]=='.exe': f2py_exe = f2py_exe[:-4] + '.py' if 'bdist_wininst' in sys.argv and f2py_exe[-3:] != '.py': f2py_exe = f2py_exe + '.py' target = os.path.join(build_dir,f2py_exe) if newer(__file__,target): log.info('Creatin... |
except AttributeError: | except (AttributeError, TypeError): | def view(self, dtype=None, type=None): if dtype is None: if type is None: output = ndarray.view(self) else: output = ndarray.view(self, type) elif type is None: try: if issubclass(dtype, ndarray): output = ndarray.view(self, dtype) dtype = None else: output = ndarray.view(self, dtype) except TypeError: output = ndarray... |
raise NotImplementerError("_nulp not implemented for complex array") | raise NotImplementedError("_nulp not implemented for complex array") | def nulp_diff(x, y, dtype=None): """For each item in x and y, eeturn the number of representable floating points between them. Parameters ---------- x : array_like first input array y : array_like second input array Returns ------- nulp: array_like number of representable floating point numbers between each item in x... |
err_status_ini = np.geterr() np.seterr(divide='ignore', invalid='ignore') | def __call__(self, a, b, *args, **kwargs): "Execute the call behavior." # Get the data and the mask (da, db) = (getdata(a, subok=False), getdata(b, subok=False)) (ma, mb) = (getmask(a), getmask(b)) # Save the current error status err_status_ini = np.geterr() np.seterr(divide='ignore', invalid='ignore') # Get the result... | |
np.seterr(**err_status_ini) | def __call__(self, a, b, *args, **kwargs): "Execute the call behavior." # Get the data and the mask (da, db) = (getdata(a, subok=False), getdata(b, subok=False)) (ma, mb) = (getmask(a), getmask(b)) # Save the current error status err_status_ini = np.geterr() np.seterr(divide='ignore', invalid='ignore') # Get the result... | |
timesteps = np.array([date], dtype='datetime64[s]')[0].astype(int) | timesteps = np.array([date], dtype='datetime64[s]')[0].astype(np.int64) | def test_creation_overflow(self): date = '1980-03-23 20:00:00' timesteps = np.array([date], dtype='datetime64[s]')[0].astype(int) for unit in ['ms', 'us', 'ns']: timesteps *= 1000 x = np.array([date], dtype='datetime64[%s]' % unit) |
assert_equal(x[0].astype(int), 322689600000000000) | assert_equal(x[0].astype(np.int64), 322689600000000000) | def test_creation_overflow(self): date = '1980-03-23 20:00:00' timesteps = np.array([date], dtype='datetime64[s]')[0].astype(int) for unit in ['ms', 'us', 'ns']: timesteps *= 1000 x = np.array([date], dtype='datetime64[%s]' % unit) |
num /= base | num //= base | def base_repr(number, base=2, padding=0): """ Return a string representation of a number in the given base system. Parameters ---------- number : int The value to convert. Only positive values are handled. base : int, optional Convert `number` to the `base` number system. The valid range is 2-36, the default value is ... |
sys.stderr.write("Unknown mode: '%s'\n" % mode) | sys.stderr.write("Unknown mode: " + repr(mode)) | def generate_f2py_py(build_dir): f2py_exe = 'f2py'+os.path.basename(sys.executable)[6:] if f2py_exe[-4:]=='.exe': f2py_exe = f2py_exe[:-4] + '.py' if 'bdist_wininst' in sys.argv and f2py_exe[-3:] != '.py': f2py_exe = f2py_exe + '.py' target = os.path.join(build_dir,f2py_exe) if newer(__file__,target): log.info('Creatin... |
str: 'string_', | bytes: 'bytes_', | def maximum_sctype(t): """ Return the scalar type of highest precision of the same kind as the input. Parameters ---------- t : dtype or dtype specifier The input data type. This can be a `dtype` object or an object that is convertible to a `dtype`. Returns ------- out : dtype The highest precision data type of the s... |
def _python_type(t): """returns the type corresponding to a certain Python type""" if not isinstance(t, _types.TypeType): t = type(t) return allTypes[_python_types.get(t, 'object_')] | if sys.version_info[0] >= 3: def _python_type(t): """returns the type corresponding to a certain Python type""" if not isinstance(t, type): t = type(t) return allTypes[_python_types.get(t, 'object_')] else: def _python_type(t): """returns the type corresponding to a certain Python type""" if not isinstance(t, _types.Ty... | def _python_type(t): """returns the type corresponding to a certain Python type""" if not isinstance(t, _types.TypeType): t = type(t) return allTypes[_python_types.get(t, 'object_')] |
cflags = sysconfig.get_config_vars()['CFLAGS'] | try: cflags = sysconfig.get_config_vars()['CFLAGS'] except KeyError: return [] | def _c_arch_flags(self): """ Return detected arch flags from CFLAGS """ from distutils import sysconfig cflags = sysconfig.get_config_vars()['CFLAGS'] arch_re = re.compile(r"-arch\s+(\w+)") arch_flags = [] for arch in arch_re.findall(cflags): arch_flags += ['-arch', arch] return arch_flags |
with warnings.catch_warnings(): | try: | def test_log2(self): a = nx.array([4.5, 2.3, 6.5]) out = nx.zeros(a.shape, float) tgt = nx.array([2.169925, 1.20163386, 2.70043972]) with warnings.catch_warnings(): warnings.filterwarnings("ignore",category=DeprecationWarning) res = ufl.log2(a) assert_almost_equal(res, tgt) res = ufl.log2(a, out) assert_almost_equal(re... |
raise ValueError, "Input must be >= 2-d." | raise ValueError("Input must be >= 2-d.") | def fliplr(m): """ Flip array in the left/right direction. Flip the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array. Returns ------- f : ndarray A view of `m` with the columns reversed. Since a view... |
raise ValueError, "Input must be >= 1-d." | raise ValueError("Input must be >= 1-d.") | def flipud(m): """ Flip array in the up/down direction. Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array. Returns ------- out : array_like A view of `m` with the rows reversed. Since a view is ... |
raise ValueError, "Input must >= 2-d." | raise ValueError("Input must >= 2-d.") | def rot90(m, k=1): """ Rotate an array by 90 degrees in the counter-clockwise direction. The first two dimensions are rotated; therefore, the array must be at least 2-D. Parameters ---------- m : array_like Array of two or more dimensions. k : integer Number of times the array is rotated by 90 degrees. Returns -----... |
raise ValueError, "Input must be 1- or 2-d." def diagflat(v,k=0): | raise ValueError("Input must be 1- or 2-d.") def diagflat(v, k=0): | def diag(v, k=0): """ Extract a diagonal or construct a diagonal array. Parameters ---------- v : array_like If `v` is a 2-D array, return a copy of its `k`-th diagonal. If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th diagonal. k : int, optional Diagonal in question. The default is 0. Use `k>0` for di... |
Sets the size of the arrays for which the returned indices will be valid. | The row dimension of the square arrays for which the returned indices will be valid. | def tril_indices(n,k=0): """ Return the indices for the lower-triangle of an (n, n) array. Parameters ---------- n : int Sets the size of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `tril` for details). Returns ------- inds : tuple of arrays The indices for the tria... |
return mask_indices(n,tril,k) def tril_indices_from(arr,k=0): """ Return the indices for the lower-triangle of an (n, n) array. | return mask_indices(n, tril, k) def tril_indices_from(arr, k=0): """ Return the indices for the lower-triangle of arr. | def tril_indices(n,k=0): """ Return the indices for the lower-triangle of an (n, n) array. Parameters ---------- n : int Sets the size of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `tril` for details). Returns ------- inds : tuple of arrays The indices for the tria... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.