rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
dt = datetime.datetime.now() | dt = self._dt() | def test_deserialize_success(self): import datetime import iso8601 typ = self._makeOne() dt = datetime.datetime.now() tzinfo = iso8601.iso8601.FixedOffset(1, 0, 'myname') dt = dt.replace(tzinfo=tzinfo) iso = dt.isoformat() node = DummySchemaNode(None) result = typ.deserialize(node, iso) self.assertEqual(result.isoforma... |
import datetime typ = self._makeOne() date = datetime.date.today() | typ = self._makeOne() date = self._today() | def test_serialize_with_date(self): import datetime typ = self._makeOne() date = datetime.date.today() node = DummySchemaNode(None) result = typ.serialize(node, date) expected = date.isoformat() self.assertEqual(result, expected) |
import datetime typ = self._makeOne() dt = datetime.datetime.now() | typ = self._makeOne() dt = self._dt() | def test_serialize_with_datetime(self): import datetime typ = self._makeOne() dt = datetime.datetime.now() node = DummySchemaNode(None) result = typ.serialize(node, dt) expected = dt.date().isoformat() self.assertEqual(result, expected) |
import datetime typ = self._makeOne() date = datetime.date.today() | typ = self._makeOne() date = self._today() | def test_deserialize_success_date(self): import datetime typ = self._makeOne() date = datetime.date.today() iso = date.isoformat() node = DummySchemaNode(None) result = typ.deserialize(node, iso) self.assertEqual(result.isoformat(), iso) |
import datetime dt = datetime.datetime.now() | dt = self._dt() | def test_deserialize_success_datetime(self): import datetime dt = datetime.datetime.now() typ = self._makeOne() iso = dt.isoformat() node = DummySchemaNode(None) result = typ.deserialize(node, iso) self.assertEqual(result.isoformat(), dt.date().isoformat()) |
If it is not provided, the missing value of this node will be :attr:`colander.null`, indicating that it is considered | If it is not provided, the missing value of this node will be a special marker value, indicating that it is considered | def deserialize(self, node, cstruct): try: result = iso8601.parse_date(cstruct) result = result.date() except (iso8601.ParseError, TypeError): try: year, month, day = map(int, cstruct.split('-', 2)) result = datetime.date(year, month, day) except Exception, e: raise Invalid(node, _(self.err_template, mapping={'val':cst... |
self.assertEqual( e.msg, 'None is not a mapping type: iteration over non-sequence') | self.failUnless( e.msg.startswith('None is not a mapping type')) | def test_deserialize_not_a_mapping(self): struct = DummyStructure(None) typ = self._makeOne() e = invalid_exc(typ.deserialize, struct, None) self.assertEqual( e.msg, 'None is not a mapping type: iteration over non-sequence') |
self.assertEqual( e.msg, 'None is not a mapping type: iteration over non-sequence') | self.failUnless( e.msg.startswith('None is not a mapping type')) | def test_serialize_not_a_mapping(self): struct = DummyStructure(None) typ = self._makeOne() e = invalid_exc(typ.serialize, struct, None) self.assertEqual( e.msg, 'None is not a mapping type: iteration over non-sequence') |
def __init__(self, logger_name='baca', level=logging.DEBUG): LoggingLoggerClass.__init__(self, logger_name, level) | def __init__(self, logger_name): LoggingLoggerClass.__init__(self, logger_name) | def __init__(self, logger_name='baca', level=logging.DEBUG): LoggingLoggerClass.__init__(self, logger_name, level) |
icon_name = id[7:] | icon_name = id[8:] | def generate_icons(self): res = self.file.xpath_eval("/svg:svg" "/svg:g[@inkscape:groupmode='layer' and " " @id='Rectangles']" "/svg:rect") re_default_rect_id = re.compile(r'rect[0-9]+') inkscape = Inkscape(self.file.filename) |
fg_name = fg_id[7:] | fg_name = fg_id[8:] | def generate_app_icons(self, tile_size, fg_size): # that a way to say: "Don't try with any other size" if tile_size != 32 and tile_size != 48 and tile_size != 100: return |
fg_name = node.prop('id') | fg_id = node.prop('id') if opt_xml_id and fg_id != opt_xml_id: continue if tile_size == 32: fg_name = fg_id[7:] else: fg_name = fg_id | def generate_app_icons(self, tile_size, fg_size): # that a way to say: "Don't try with any other size" if tile_size != 32 and tile_size != 48: return |
if opt_xml_id and fg_name != opt_xml_id: continue | def generate_app_icons(self, tile_size, fg_size): # that a way to say: "Don't try with any other size" if tile_size != 32 and tile_size != 48: return | |
inkscape.export(fg_name, fg_file, fg_size, fg_size) | inkscape.export(fg_id, fg_file, fg_size, fg_size) | def generate_app_icons(self, tile_size, fg_size): # that a way to say: "Don't try with any other size" if tile_size != 32 and tile_size != 48: return |
"/svg:rect[starts-with(@id,'moblin-')]") | "/svg:rect[starts-with(@id,'netbook-')]") | def generate_app_svg(self, filename): doc = libxml2.newDoc("1.0") |
if id.startswith('moblin-'): | if id.startswith('netbook-'): | def generate_icons(self): res = self.file.xpath_eval("/svg:svg" "/svg:g[@inkscape:groupmode='layer' and " " @id='Rectangles']" "/svg:rect") re_default_rect_id = re.compile(r'rect[0-9]+') inkscape = Inkscape(self.file.filename) |
if width == 16 and id.startswith('16-'): | if width == '16' and id.startswith('16-'): | def generate_icons(self): res = self.file.xpath_eval("/svg:svg" "/svg:g[@inkscape:groupmode='layer' and " " @id='Rectangles']" "/svg:rect") re_default_rect_id = re.compile(r'rect[0-9]+') inkscape = Inkscape(self.file.filename) |
if not((width == '16' and height == '16') or (width == '24' and height == '24')): debug("Dropping " + id) continue | def generate_icons(self): res = self.file.xpath_eval("/svg:svg" "/svg:g[@inkscape:groupmode='layer' and " " @id='Rectangles']" "/svg:rect") re_default_rect_id = re.compile(r'rect[0-9]+') inkscape = Inkscape(self.file.filename) | |
id = id[7:] | icon_name = id[7:] | def generate_icons(self): res = self.file.xpath_eval("/svg:svg" "/svg:g[@inkscape:groupmode='layer' and " " @id='Rectangles']" "/svg:rect") re_default_rect_id = re.compile(r'rect[0-9]+') inkscape = Inkscape(self.file.filename) |
id = id[3:] file = os.path.join(dirs[width], id + '.png') | icon_name = id[3:] file = os.path.join(dirs[width], icon_name + '.png') | def generate_icons(self): res = self.file.xpath_eval("/svg:svg" "/svg:g[@inkscape:groupmode='layer' and " " @id='Rectangles']" "/svg:rect") re_default_rect_id = re.compile(r'rect[0-9]+') inkscape = Inkscape(self.file.filename) |
file_48 = os.path.join (output_dir_48, id + '.png') | file_48 = os.path.join (output_dir_48, icon_name + '.png') | def generate_icons(self): res = self.file.xpath_eval("/svg:svg" "/svg:g[@inkscape:groupmode='layer' and " " @id='Rectangles']" "/svg:rect") re_default_rect_id = re.compile(r'rect[0-9]+') inkscape = Inkscape(self.file.filename) |
shell=True, stdout=subprocess.PIPE, env={'LANG': 'C'}) | shell=True, stdout=subprocess.PIPE, env=env) | def _getSVNInfoOutput(self): try: proc = subprocess.Popen('svn info "%s"' % self.path, shell=True, stdout=subprocess.PIPE, env={'LANG': 'C'}) except OSError: pass else: if proc.wait() == 0: return proc.stdout return None |
Raise TypeError if no pixel data in this dataset. Raise ImportError if cannot import numpy. | :raises TypeError: if no pixel data in this dataset. :raises ImportError: if cannot import numpy. | def _PixelDataNumpy(self): """Return a NumPy array of the pixel data. |
if have_numpy: if self.BitsAllocated not in self.NumpyPixelFormats: raise NotImplementedError, "Do not have NumPy dtype for BitsAllocated=%d, please update Dataset.NumpyPixelFormats" % self.BitsAllocated numpy_format = self.NumpyPixelFormats[self.BitsAllocated] arr = numpy.fromstring(self.PixelData, numpy_format) if n... | format_str = '%sint%d' % (('u', '')[self.PixelRepresentation], self.BitsAllocated) try: numpy_format = numpy.dtype(format_str) except TypeError: raise TypeError("Data type not understood by NumPy: " "format='%s', PixelRepresentation=%d, BitsAllocated=%d" % ( numpy_format, self.PixelRepresentation, self.BitsAllocated)) ... | def _PixelDataNumpy(self): """Return a NumPy array of the pixel data. |
arr = arr.reshape(self.NumberofFrames, self.Rows, self.Columns) | raise NotImplementedError, "This code only handles SamplesPerPixel > 1 if Bits Allocated = 8" | def _PixelDataNumpy(self): """Return a NumPy array of the pixel data. |
if self.SamplesperPixel > 1: if self.BitsAllocated == 8: arr = arr.reshape(self.SamplesperPixel, self.Rows, self.Columns) else: raise NotImplementedError, "This code only handles SamplesPerPixel > 1 if Bits Allocated = 8" else: arr = arr.reshape(self.Rows, self.Columns) | arr = arr.reshape(self.Rows, self.Columns) | def _PixelDataNumpy(self): """Return a NumPy array of the pixel data. |
return GroupDataset(2) | import warnings msg = ("Dataset.file_metadata() is deprecated and will be removed" " in pydicom 1.0. Use FileDataset and its file_meta" " attribute instead.") warnings.warn(msg, DeprecationWarning) return self.GroupDataset(2) | def file_metadata(self): """Return a Dataset holding only meta information (group 2). |
is_implicit_VR = False is_little_endian = True | self._is_implicit_VR = False self._is_little_endian = True | def __init__(self, fp, stop_when=None, force=False): """Read the preambleand meta info, prepare iterator for remainder |
is_implicit_VR = True is_little_endian = True | self._is_implicit_VR = True self._is_little_endian = True | def __init__(self, fp, stop_when=None, force=False): """Read the preambleand meta info, prepare iterator for remainder |
is_implicit_VR = False is_little_endian = False | self._is_implicit_VR = False self._is_little_endian = False | def __init__(self, fp, stop_when=None, force=False): """Read the preambleand meta info, prepare iterator for remainder |
is_little_endian = True is_implicit_VR = True logger.debug("Using %s VR, %s Endian transfer syntax" %(("Explicit", "Implicit")[is_implicit_VR], ("Big", "Little")[is_little_endian])) | self._is_little_endian = True self._is_implicit_VR = True logger.debug("Using %s VR, %s Endian transfer syntax" %(("Explicit", "Implicit")[self._is_implicit_VR], ("Big", "Little")[self._is_little_endian])) | def __init__(self, fp, stop_when=None, force=False): """Read the preambleand meta info, prepare iterator for remainder |
for data_element in data_element_generator(self.fp, stop_when=self.stop_when): | for data_element in data_element_generator(self.fp, self._is_implicit_VR, self._is_little_endian, stop_when=self.stop_when): | def __iter__(self): tags = sorted(self.file_meta_info.keys()) for tag in tags: yield self.file_meta_info[tag] |
util.debug) | self.verbose) | def _update_schedules(self): interval = 0 idx = 1 # Used to index subsets for schedule overlap calculation last = None |
raise RunTimeError,message | raise RuntimeError,message | def _prune_snapshots(self, dataset, schedule): """Cleans out zero sized snapshots, kind of cautiously""" # Per schedule: We want to delete 0 sized # snapshots but we need to keep at least one around (the most # recent one) for each schedule so that that overlap is # maintained from frequent -> hourly -> daily etc. # St... |
included = [] | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... | |
finalrecursive = [] | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... | |
elif line[1] == "true": | everything.append(line[0]) if line[1] == "true": | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... |
try: included.index(line[0]) continue except ValueError: try: excluded.index(line[0]) | idx = bisect_right(everything, line[0]) if len(everything) == 0 or \ everything[idx-1] != line[0]: if line[1] == "-": | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... |
except ValueError: if line[1] == "-": continue elif line[1] == "true": included.append(line[0]) elif line[1] == "false": excluded.append(line[0]) | everything.insert(idx, line[0]) if line[1] == "true": included.insert(0, line[0]) elif line[1] == "false": excluded.append(line[0]) | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... |
dataset = ReadWritableDataset(datasetname) children = dataset.list_children() | idx = bisect_right(everything, datasetname) children = [name for name in everything[idx:] if \ name.find(datasetname) == 0] | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... |
try: excluded.index(child) | idx = bisect_left(excluded, child) if excluded[idx] == child: | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... |
except ValueError: pass | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... | |
recursive.append(datasetname) finalrecursive = [] | recursive.insert(0, datasetname) | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... |
finalrecursive.append(datasetname) | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... | |
if parent in recursive: continue | idx = bisect_right(recursive, parent) if len(recursive) > 0 and \ recursive[idx-1] == parent: continue | def create_auto_snapshot_set(self, label, tag = None): """ Create a complete set of snapshots as if this were for a standard zfs-auto-snapshot operation. Keyword arguments: label: A label to apply to the snapshot name. Cannot be None. tag: A string indicating one of the standard auto-snapshot schedules tags to check (... |
advancedBox.connect('unmap', self._avcancedbox_unmap) | advancedBox.connect('unmap', self._advancedbox_unmap) | def __init__(self, execpath): self._execPath = execpath self._datasets = zfs.Datasets() self._xml = gtk.glade.XML("%s/../../glade/time-slider-setup.glade" \ % (os.path.dirname(__file__))) |
def _avcancedbox_unmap(self, widget): | def _advancedbox_unmap(self, widget): | def _avcancedbox_unmap(self, widget): # Auto shrink the window by subtracting the frame's height # requistion from the window's height requisition myrequest = widget.size_request() toplevel = self._xml.get_widget("toplevel") toprequest = toplevel.size_request() toplevel.resize(toprequest[0], toprequest[1] - myrequest[1... |
newTargetDir = rsyncChooser.get_current_folder() | newTargetDir = rsyncChooser.get_file().get_path() | def __on_ok_clicked(self, widget): # Make sure the dictionaries are empty. self.fsintentdic = {} self.snapstatedic = {} self.rsyncstatedic = {} enabled = self.xml.get_widget("enablebutton").get_active() self.rsyncEnabled = self.xml.get_widget("rsyncbutton").get_active() if enabled == False: self.sliderSMF.disable_servi... |
line = line.split() results.append(line) | if len(line) > 1: line = line.split() results.append(line) | def list_pending_snapshots(propName): """ Lists all snaphots which have 'propName" set locally. Resulting list is returned sorted in descending order of creation time (ie.newest first). Each element in the returned list is tuple of the form: [creationtime, snapshotname] """ results = [] snaplist = [] sortsnaplist = [] ... |
mon = (tm_mon + period) % 12 | mon = (snap_tm.tm_mon + period) % 12 | def _update_schedules(self): interval = 0 idx = 1 # Used to index subsets for schedule overlap calculation last = None |
elif tm_mon + period > 12: | elif snap_tm.tm_mon + period > 12: | def _update_schedules(self): interval = 0 idx = 1 # Used to index subsets for schedule overlap calculation last = None |
if self.is_running == True: | if self.is_running() == True: | def execute(self, schedule, label): |
debug("Found disabled plugin:\t%s" + label, self.verbose) | util.debug("Found disabled plugin:\t%s" + label, self.verbose) | def refresh(self): self.plugins = [] cmd = [smfmanager.SVCSCMD, "-H", "-o", "state,FMRI", PLUGINBASEFMRI] |
oldestBackupTime, oldestBackup = self._backups[0] qTime, qItem = self._currentQueueSet[0] capacity = util.get_filesystem_capacity(self._rsyncDir) if capacity > self._cleanupThreshold: deleteables = self._find_deleteable_backups(qTime) if len(deleteables) == 0 and \ qTime < oldestBackupTime: util.debug("%s... | if len(self._backups) > 0: oldestBackupTime, oldestBackup = self._backups[0] qTime, qItem = self._currentQueueSet[0] capacity = util.get_filesystem_capacity(self._rsyncDir) if capacity > self._cleanupThreshold: deleteables = self._find_deleteable_backups(qTime) if len(deleteables) == 0 and \ qTime < oldes... | def backup_snapshot(self): # First, check to see if the rsync destination # directory is accessible. try: os.stat(self._rsyncDir) except OSError: util.debug("Backup target directory is not " \ "accessible right now: %s" \ % (self._rsyncDir), self._verbose) self._bus.rsync_unsynced(len(self._pendingList)) if self._mainL... |
capacity = util.get_filesystem_capacity(self._rsyncDir) if capacity > self._cleanupThreshold: deleteables = self._find_deleteable_backups(qTime) if warningDone == False: util.debug("Backup device capacity exceeds %d%%. " \ "Found %d deleteable backups for space " \ "recovery." \ % (capacity, len(deleteables)), sel... | if len(self._backups) > 0: capacity = util.get_filesystem_capacity(self._rsyncDir) if capacity > self._cleanupThreshold: deleteables = self._find_deleteable_backups(qTime) if warningDone == False: util.debug("Backup device capacity exceeds %d%%. " \ "Found %d deleteable backups for space " \ "recovery." \ % (capa... | def backup_snapshot(self): # First, check to see if the rsync destination # directory is accessible. try: os.stat(self._rsyncDir) except OSError: util.debug("Backup target directory is not " \ "accessible right now: %s" \ % (self._rsyncDir), self._verbose) self._bus.rsync_unsynced(len(self._pendingList)) if self._mainL... |
while True: buffer = f.read(buf_size) | result = None buffer = f.read(buf_size) while buffer or result == YAJL_INSUFFICIENT_DATA: | def c_callback(context, *args): events.append((event, func(*args))) return 1 |
if not buffer or result == YAJL_ERROR: break for event in events: yield event events = [] if result == YAJL_ERROR: error = yajl.yajl_get_error(handle, 1, buffer, len(buffer)) raise JSONError(error) | if result == YAJL_ERROR: error = yajl.yajl_get_error(handle, 1, buffer, len(buffer)) raise JSONError(error) if events: for event in events: yield event events = [] buffer = f.read(buf_size) | def c_callback(context, *args): events.append((event, func(*args))) return 1 |
yajl.yajl_get_error.restype = c_char_p | yajl.yajl_get_error.restype = c_void_p | def c_callback(context, *args): events.append((event, func(*args))) return 1 |
error = yajl.yajl_get_error(handle, 1, buffer, len(buffer)) | perror = yajl.yajl_get_error(handle, 1, buffer, len(buffer)) error = c_char_p(perror).value yajl.yajl_free_error(handle, perror) | def c_callback(context, *args): events.append((event, func(*args))) return 1 |
values = [part.strip() for part in value.split(',')] | values = [part.strip() for part in value.split(sep)] | def getcsv(self, key, sep=','): "return comma separated values as a list" value = self.get(key) values = [part.strip() for part in value.split(',')] # remove empty strings values = [part for part in values if part] return values |
userInfo = createObject('groupserver.LoggedInUser', self.context) | def handle_set(self, action, data): assert self.context assert self.form_fields assert action assert data | |
retval = url | retval = uri | def sanitise_uri(uri): '''Sanitise URI Description ----------- Adds the ``http://`` scheme (alias protocol, alias method) to the URI if none is provided. Arguments --------- ``uri`` The string containing the URI to be sanitised. Returns ------- A string containing the sanitised URI. Side Effects ------------ No... |
def validate(self, uri): saneUri = sanitise_uri(uri) return super(SaneURI, self).validate(saneUri) | def constraint(self, uri): saneUri = sanitise_uri(uri) return super(SaneURI, self).constraint(saneUri) | |
user.clear_userPasswordResetVerificationIds() | loggedInUser.user.clear_userPasswordResetVerificationIds() | def set_password(context, password): '''Set the password for the logged in user, and log the fact.''' assert context assert password assert type(password) in (str, unicode) loggedInUser = createObject('groupserver.LoggedInUser', context) assert not(loggedInUser.anonymous), 'Not logged in' loggedInUser.user.set_passwo... |
url = 'http://cheeseshop.python.org/pypi/z3c.jsontree', | url = 'http://pypi.python.org/pypi/z3c.jsontree', | def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() |
new_class = super(PolymorphicModelBase, self).__new__(self, model_name, bases, attrs) | new_class = self.call_superclass_new_method(model_name, bases, attrs) | def __new__(self, model_name, bases, attrs): #print; print '###', model_name, '- bases:', bases # create new model new_class = super(PolymorphicModelBase, self).__new__(self, model_name, bases, attrs) |
inherits all managers from the base models. An example:: | inherits all managers from its base models (but only the polymorphic base models). An example (inheriting from MyModel above):: | def get_query_set(self): return super(MyOrderedManager,self).get_query_set().order_by('some_field') |
and are incomplete, as they do not contain the additional fields of their real class. | and do not contain all fields of their real class. | def _get_real_instances(self, base_result_objects): """ Polymorphic object loader Does the same as: return [ o.get_real_instance() for o in base_result_objects ] The list base_result_objects contains the objects from the executed base class query. The class of all of them is self.model (our base model). Some, many ... |
result = [] for o in self.all(): result.append((',\n ' if result else '') + repr(o)) return '[ ' + ''.join(result) + ' ]' | result = [ repr(o) for o in self.all() ] return '[ ' + ',\n '.join(result) + ' ]' | def __repr__(self): result = [] for o in self.all(): result.append((',\n ' if result else '') + repr(o)) return '[ ' + ''.join(result) + ' ]' |
including all subclasses of these models (as we want be to the same | including all subclasses of these models (as we want to do the same | def _create_model_filter_Q(modellist, not_instance_of=False): """ Helper function for instance_of / not_instance_of Creates and returns a Q object that filters for the models in modellist, including all subclasses of these models (as we want be to the same as pythons isinstance() ). . We recursively collect all __subcl... |
modelname = name.rstrip('_ptr') model = self.__class__.sub_and_superclass_dict.get(modelname, None) | if name.endswith('_ptr'): name=name[:-4] model = self.__class__.sub_and_superclass_dict.get(name, None) | def __getattribute__(self, name): if name != '__class__': modelname = name.rstrip('_ptr') model = self.__class__.sub_and_superclass_dict.get(modelname, None) if model: id = super(PolymorphicModel, self).__getattribute__('id') attr = model.base_objects.get(id=id) return attr |
ordered_id_list.append(base_object.id) | ordered_id_list.append(base_object.pk) | def _get_real_instances(self, base_result_objects): """ Polymorphic object loader Does the same as: return [ o.get_real_instance() for o in base_result_objects ] The list base_result_objects contains the objects from the executed base class query. The class of all of them is self.model (our base model). Some, many ... |
results[base_object.id] = base_object | results[base_object.pk] = base_object | def _get_real_instances(self, base_result_objects): """ Polymorphic object loader Does the same as: return [ o.get_real_instance() for o in base_result_objects ] The list base_result_objects contains the objects from the executed base class query. The class of all of them is self.model (our base model). Some, many ... |
idlist_per_model[base_object.get_real_instance_class()].append(base_object.id) | idlist_per_model[base_object.get_real_instance_class()].append(base_object.pk) | def _get_real_instances(self, base_result_objects): """ Polymorphic object loader Does the same as: return [ o.get_real_instance() for o in base_result_objects ] The list base_result_objects contains the objects from the executed base class query. The class of all of them is self.model (our base model). Some, many ... |
for o in qs: results[o.id] = o | for o in qs: results[o.pk] = o | def _get_real_instances(self, base_result_objects): """ Polymorphic object loader Does the same as: return [ o.get_real_instance() for o in base_result_objects ] The list base_result_objects contains the objects from the executed base class query. The class of all of them is self.model (our base model). Some, many ... |
return real_model.objects.get(id=self.id) | return real_model.objects.get(pk=self.pk) | def get_real_instance(self): """Normally not needed. If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the complete object with it's real class/type and all fields may be retrieved with this method. Each method call executes one db query (if necessary).""" real_model = self.get_re... |
out = self.__class__.__name__ + ': id %d, ' % (self.id or - 1); last = self._meta.fields[-1] | out = self.__class__.__name__ + ': id %d, ' % (self.pk or - 1); last = self._meta.fields[-1] | def __repr__(self): out = self.__class__.__name__ + ': id %d, ' % (self.id or - 1); last = self._meta.fields[-1] for f in self._meta.fields: if f.name in [ 'id' ] + self.polymorphic_internal_model_fields or 'ptr' in f.name: continue out += f.name + ' (' + type(f).__name__ + ')' if f != last: out += ', ' return '<' + o... |
out = 'id %d, ' % (self.id); last = self._meta.fields[-1] | out = 'id %d, ' % (self.pk); last = self._meta.fields[-1] | def __repr__(self): out = 'id %d, ' % (self.id); last = self._meta.fields[-1] for f in self._meta.fields: if f.name in [ 'id' ] + self.polymorphic_internal_model_fields or 'ptr' in f.name: continue out += f.name if isinstance(f, (models.ForeignKey)): o = getattr(self, f.name) out += ': "' + ('None' if o == None else o.... |
self.dup_select_related(qs) | qs.dup_select_related(self) | def _get_real_instances(self, base_result_objects): """ Polymorphic object loader Does the same as: return [ o.get_real_instance() for o in base_result_objects ] The list base_result_objects contains the objects from the executed base class query. The class of all of them is self.model (our base model). Some, many ... |
cursor.execute("""DELETE FROM ticket_template_store WHERE tt_user='%(tt_user)s' AND tt_name='%(tt_name)s'""" % data) | sqlString = """DELETE FROM ticket_template_store WHERE tt_user=%s AND tt_name=%s """ cursor.execute(sqlString, (data["tt_user"], data["tt_name"], )) | def deleteCustom(cls, env, data): """Remove the tt from the database.""" db = env.get_db_cnx() cursor = db.cursor() |
cursor.execute("""SELECT tt_field, tt_value | sqlString = """SELECT tt_field, tt_value | def fetchCurrent(cls, env, data): """Retrieve an existing tt from the database by ID.""" db = env.get_db_cnx() |
WHERE tt_user = '%(tt_user)s' | WHERE tt_user = %s | def fetchCurrent(cls, env, data): """Retrieve an existing tt from the database by ID.""" db = env.get_db_cnx() |
WHERE tt_name='%(tt_name)s')""" % data) | WHERE tt_name=%s) """ cursor.execute(sqlString, (data["tt_user"], data["tt_name"], )) | def fetchCurrent(cls, env, data): """Retrieve an existing tt from the database by ID.""" db = env.get_db_cnx() |
WHERE tt_user = '%(tt_user)s' ; """ cursor.execute(sqlString % data) | WHERE tt_user = %s """ cursor.execute(sqlString, (data["tt_user"], )) | def fetchAll(cls, env, data): """Retrieve an existing tt from the database by ID. result: { "field_value_mapping":{ "default":{ "summary":"aaa", "description":"bbb", }, |
FROM ticket_template_store WHERE tt_user = '%(tt_user)s' ; """ cursor.execute(sqlString % {"tt_user": SYSTEM_USER}) | FROM ticket_template_store WHERE tt_user = %s """ cursor.execute(sqlString, (SYSTEM_USER, )) | def fetchAll(cls, env, data): """Retrieve an existing tt from the database by ID. result: { "field_value_mapping":{ "default":{ "summary":"aaa", "description":"bbb", }, |
WHERE tt_user = '%(tt_user)s' AND tt_name = '%(tt_name)s' | WHERE tt_user = %s AND tt_name = %s | def fetchAll(cls, env, data): """Retrieve an existing tt from the database by ID. result: { "field_value_mapping":{ "default":{ "summary":"aaa", "description":"bbb", }, |
WHERE tt_name = '%(tt_name)s'); """ cursor.execute(sqlString % data) | WHERE tt_name = %s) """ cursor.execute(sqlString, (data["tt_user"], data["tt_name"], data["tt_name"], )) | def fetchAll(cls, env, data): """Retrieve an existing tt from the database by ID. result: { "field_value_mapping":{ "default":{ "summary":"aaa", "description":"bbb", }, |
WHERE tt_user = '%(tt_user)s' ORDER BY tt_name """ cursor.execute(sqlString % {"tt_user": tt_user, }) | WHERE tt_user = %s ORDER BY tt_name """ cursor.execute(sqlString, (tt_user, )) | def getCustomTemplate(cls, env, tt_user): """Retrieve from the database that match the specified criteria. """ db = env.get_db_cnx() |
cursor.execute("SELECT tt_value FROM ticket_template_store WHERE tt_time=" "(SELECT max(tt_time) FROM ticket_template_store WHERE tt_name=%s and tt_field='description')", (tt_name,)) | sqlString = """SELECT tt_value FROM ticket_template_store WHERE tt_time=( SELECT max(tt_time) FROM ticket_template_store WHERE tt_name=%s and tt_field='description' ) """ cursor.execute(sqlString, (tt_name,)) | def fetch(cls, env, tt_name, db=None): """Retrieve an existing tt from the database by ID.""" if not db: db = env.get_db_cnx() |
DLL = MMLCore('../libmml.so') | def __del__(self): del self.dll | |
c = Color(DLL) ret = c.find((0, 0, 100, 100), 0) print ret ret = c.findAll((0, 0, 100, 100), 0) print ret m = Mouse(DLL) print m[(Mouse.Pos, Mouse.Left, Mouse.Right)] m[(Mouse.Pos, Mouse.Right)] = ((300,300), True) print m.getButtonStates() sleep(0.5) m.setPos((200,200)) sleep(2) m[(Mouse.Left, Mouse.Right, Mou... | if __name__ == '__main__': DLL = MMLCore('../libmml.so') c = Color(DLL) ret = c.find((0, 0, 100, 100), 0) print ret ret = c.findAll((0, 0, 100, 100), 0) print ret m = Mouse(DLL) print m[(Mouse.Pos, Mouse.Left, Mouse.Right)] m[(Mouse.Pos, Mouse.Right)] = ((300,300), True) print m.getButtonStates() sleep(0.5) m.set... | def __del__(self): del self.dll |
ret = self._mc.dll.find_color_spiral_tolerance(self._cli, byref(x), byref(y), col, *box, tol) | pass | def find_spiral(self, col, box, tol = 0): """ Find a color in a box, searching in the direction of a spiral, with a specific tolerance. Yields a tuple of x, y values of found color. """ x, y = (c_int(-1), c_int(-1)) if tol is 0: ret = self._mc.dll.find_color_spiral(self._cli, byref(x), byref(y), col, *box) else: ret = ... |
ret = self._mc.dll.find_colored_area(self._cli, byref(x), byref(y), col, *box, min_a) else: ret = self._mc.dll.find_colored_area_tolerance(self._cli, byref(x), byref(y), col, *box, min_a, tol) | pass else: pass | def find_area(self, col, box, min_a, tol = 0): """ Finds a colored area in box with min area min_a with a specific tolerance. Yields a tuple of x, y values of found area. """ x, y = (c_int(-1), c_int(-1)) if tol is 0: ret = self._mc.dll.find_colored_area(self._cli, byref(x), byref(y), col, *box, min_a) else: ret = self... |
ret = self._mc.dll.count_color_tolerance(self._cli, count, col, *box, tol) | pass | def count_color(self, count, col, box, tol = 0): """ Counts color col in box with tol. Yields integer of count. """ count = 0 if tol is 0: ret = self._mc.dll.count_color(self._cli, count, col, *box) else: ret = self._mc.dll.count_color_tolerance(self._cli, count, col, *box, tol) if ret is RESULT_OK: return count elif r... |
print i | def __getitem__(self, item): '''Can currently return the state of mouse buttons as well as the mouse position. Supports iterable arguments''' if isiterable(item): res = [] for i in item: if i == self.Pos: res.append(self._getMousePos()) elif i in self._getButtons().keys(): res.append(self._getMouseButtonState(self._but... | |
return self_getMouseButtonState(self_buttonToInt(item)) | return self._getMouseButtonState(self_buttonToInt(item)) | def __getitem__(self, item): '''Can currently return the state of mouse buttons as well as the mouse position. Supports iterable arguments''' if isiterable(item): res = [] for i in item: if i == self.Pos: res.append(self._getMousePos()) elif i in self._getButtons().keys(): res.append(self._getMouseButtonState(self._but... |
self._initialiseDLLFuncs() | self._initialise_dll_funcs() def get(self, pt): """ Gets color at pt[0], pt[1]. Yields integer. """ col = c_int(-1) self._mc.dll.get_color(self._cli, pt[0], pt[1], byref(col)) if col is RESULT_OK: return col elif ret is RESULT_ERROR: raise ColorException(self._mc.get_last_error()) return None | def __init__(self, MC, cli): """ Initialise the Color object. """ self._mc = MC self._cli = cli self._initialiseDLLFuncs() |
def findAll(self, box, color, tol = 0): | def find_all(self, box, color, tol = 0): | def findAll(self, box, color, tol = 0): """ find all colors in a box, with a specific tolerance. returned are all the matching points """ ptr, _len = PPOINT(), c_int(42) if tol is 0: self._mc.dll.find_colors(self._cli, byref(ptr), byref(_len), color, *box) else: self._mc.dll.find_colors_tolerance(self._cli, byref(ptr),... |
def _initialiseDLLFuncs(self): | def find_spiral(self, col, box, tol = 0): """ Find a color in a box, searching in the direction of a spiral, with a specific tolerance. Yields a tuple of x, y values of found color. """ x, y = (c_int(-1), c_int(-1)) if tol is 0: ret = self._mc.dll.find_color_spiral(self._cli, byref(x), byref(y), col, *box) else: ret = ... | def findAll(self, box, color, tol = 0): """ find all colors in a box, with a specific tolerance. returned are all the matching points """ ptr, _len = PPOINT(), c_int(42) if tol is 0: self._mc.dll.find_colors(self._cli, byref(ptr), byref(_len), color, *box) else: self._mc.dll.find_colors_tolerance(self._cli, byref(ptr),... |
self.fps = int(1000.0/12) | self.fps = int(1000.0/24) | def __init__(self, name="Untitled Game", fullscreen=False): log.debug("game object created at %s"%datetime.now()) self.game = self self.fps = int(1000.0/12) #12 fps |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.