Форум сайта python.su
win32gui.SetForegroundWindow(program[0]) win32gui.SetActiveWindow(program[0])
def make_window_active(my_title): if sys_type=='win': toplist = [] winlist = [] def enum_callback(hwnd, results): winlist.append((hwnd, win32gui.GetWindowText(hwnd))) win32gui.EnumWindows(enum_callback, toplist) program = [(hwnd, title) for hwnd, title in winlist if my_title in title.lower()] # just grab the first window that matches if len(program)>=1: program = program[0] # use the window handle to set focus win32gui.SetForegroundWindow(program[0]) win32gui.SetActiveWindow(program[0])
# -*- coding: latin-1 -*- import os import sys import time import logging import logging.config from pysphere import VIServer from pysphere import VIException from collections import Iterable as ITER #-- Logging --# logging.config.fileConfig('log.conf') logging.getLogger('pysphere').setLevel('DEBUG') #-- VMWare SPHERE --# g_HOST = 'ip_address' g_LOGIN = 'user' g_PW = 'password' #-- Global variables for count --# g_SLEEP_INTERVAL = 10 g_COUNTDOWN = 5 def timer(func): def wrapper(*args, **kwargs): start_time = time.time() foo = func(*args, **kwargs) print '\n', '--' * 40 print '\n--Run-time functions: %d sec.' % (time.time() - start_time) return foo return wrapper def connection(sql_query): pass def set_query(property, network, status): '''def set_query: Query for DB ''' query = "execute procedure CHECKS_MAKETS ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}');".format( property.get('real_name'), property.get('alias_name'), property.get('OS'), property.get('parent_folder'), ';'.join(network.get('IP', 'None')), ';'.join(network.get('VLAN', 'None')), status.get('STATUS') ) connection(query) class GetInfoVM(object): '''class GetInfoVM: Get VM list from vSphere then list start in cycle then each item get property of VM: Property: Property['alias_name'] Property['real_name'] Property['OS'] Property['parent_folder'] Network: Network['IP'] Network['VLAN'] Status: Status['STATUS'] convert for SQL Base: PowerOff is 0 PowerOn is 1 and run func: set_query(Property, Network, Status) USAGE: >>> get_prop = GetInfoVM() >>> get_prop.get_VMList() >>> get_prop.server.disconnect() ''' def __init__(self): self.server = VIServer() self.server.connect(g_HOST, g_LOGIN, g_PW) self.vm_list = self.server.get_registered_vms() def get_VMList(self): '''def get_VMList: Get VM list for TVCenter ''' for vm_path in self.vm_list: vm = self.server.get_vm_by_path(vm_path) Property = self.__get_property(vm) Network = self.__get_network(vm) Status = self.__get_status(vm) ###--- Launch function create query for DB ---### set_query(Property, Network, Status) logging.info('All data were processed') def __get_property(self, vm): '''def __get_property: Get Property of VM ''' Property = {} Property['alias_name'] = vm.__get_property('name', from_cache=False) Property['real_name'] = os.path.basename(vm.__get_property('path')) Property['OS'] = vm.__get_property('guest_full_name', from_cache=False) Property['parent_folder'] = vm.properties.parent.name.decode('utf-8').encode('cp1251') return Property def __get_network(self,vm): '''def __get_network: Get network properties of VM: get IP address and get Vlan id''' Network = {} net = vm.__get_property('net', from_cache=False) if isinstance(net, ITER): extract = lambda x: x[0] if x else 'None' IP_addr = [extract(ip.get('ip_addresses')) for ip in net] Vlan_name = [str(vln.get('network', 'None')) for vln in net] else: IP_addr = ['None'] Vlan_name = ['None'] Network['IP'] = IP_addr Network['VLAN'] = Vlan_name return Network def __get_status(self, vm): '''def __get_status: Get status of VM: is POWERED OFF VM or is POWERED ON VM''' Status = {} status_vm = vm.__get_status() if status_vm == 'POWERED OFF': Status['STATUS'] = 0 # for sql trigger elif status_vm == 'POWERED ON': Status['STATUS'] = 1 # for sql trigger return Status @timer def main(count): count += 1 try: get_prop = GetInfoVM() except VIException as ex: logging.error('%s' % ex) logging.info('Sleep %s seconds' % g_SLEEP_INTERVAL) time.sleep(g_SLEEP_INTERVAL) logging.info('Try again, attempt number - %s' % count) if count == g_COUNTDOWN: logging.error('Exceed the number of requests. Program exits with code [1]') sys.exit(1) main(count) else: logging.info('Connect to vSphere is successfully') try: get_prop.get_VMList() except (VIException, Exception) as ex: logging.error('%s' % ex) logging.info('Sleep %s seconds' % g_SLEEP_INTERVAL) time.sleep(g_SLEEP_INTERVAL) logging.info('Try again, attempt number - %s' % count) if count == g_COUNTDOWN: logging.error('Exceed the number of requests. Program exits with code [1]') sys.exit(1) main(count) get_prop.server.disconnect() logging.info('Disconnect from vSphere') if __name__ == '__main__': main(0)
host_patterns = patterns('',
host(r'(www)', settings.ROOT_URLCONF, name="www"),
host(r'(?P<brand>\w+)', 'catalog.brands_urls', name='brands', callback=host_site),
)
from .views import brand_subdomain
urlpatterns = patterns('',
url(r'^$', brand_subdomain, name='view_brands'),
)
…
Symbol `PyBool_Type' has different size in shared object, consider re-linking
Symbol `PyFloat_Type' has different size in shared object, consider re-linking
…
Segmentation fault
./configure --enable-unicode --enable-shared --with-threads --with-pymalloc && make && sudo make install
@engine.async def on_button_click(self, *args): self.status_label.setText("Downloading image...") # Run single task in separate thread image_data = yield Task(self.load_url, "http://www.google.com/images/srpr/logo4w.png") pixmap = QtGui.QPixmap.fromImage(QtGui.QImage.fromData(image_data)) self.image_label.setPixmap(pixmap) self.status_label.setText("Downloading pages...") urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org'] # Run multiple task simultaneously in thread pool pages = yield [Task(self.load_url, url) for url in urls] self.status_label.setText("Done") avg_size = sum(map(len, pages)) / len(pages) self.result_label.setText("Average page size: %s" % avg_size)
def main(argv): # Step 1. Get an analytics service object. service = sample_utils.initialize_service() try: # Step 2. Get the user's first profile ID. profile_id = get_profile_id(service) if profile_id: # Step 3. Query the Core Reporting API. results = get_results(service, profile_id) # Step 4. Output the results. print_results(results) except TypeError, error: # Handle errors in constructing a query. print ('There was an error in constructing your query : %s' % error) except HttpError, error: # Handle API errors. print ('Arg, there was an API error : %s : %s' % (error.resp.status, error._get_reason())) except AccessTokenRefreshError: # Handle Auth errors. print ('The credentials have been revoked or expired, please re-run ' 'the application to re-authorize')
def get_profile_id(service): accounts = service.management().accounts().list().execute() account_list = accounts.get('items') account_list = account_list[0:10] for account in account_list: time.sleep(0.025) id = account.get('id') webproperties = service.management().webproperties().list(accountId=id).execute() webproperties = webproperties.get('items') for webproperty in webproperties: id_web = webproperty.get('id') profiles = service.management().profiles().list(accountId=id,webPropertyId=id_web).execute() profiles = profiles.get('items') for profile in profiles: profile_id = profile.get('id') return profile_id return None
def get_results(service,profile_id): return service.data().ga().get( ids='ga:' + profile_id, start_date='2013-03-23', end_date='2013-03-25', metrics='ga:visits',#ga:goalCompletionsAll,ga:pageviews',#ga:pageviewsPerVisit',#ga:timeOnSite, dimensions='ga:source',#'ga:customVarValue1', #ga:adContent', # ga:campaign', sort='-ga:visits', #filters='ga:medium==organic', #start_index='1', max_results='25')
def main(argv): # Step 1. Get an analytics service object. service = sample_utils.initialize_service() try: # Step 2. Get the user's first profile ID. profile_id = get_profile_id(service) if profile_id: # Step 3. Query the Core Reporting API. results = get_results(service, profile_id) # Step 4. Output the results. print_results(results) except TypeError, error: # Handle errors in constructing a query. print ('There was an error in constructing your query : %s' % error) except HttpError, error: # Handle API errors. print ('Arg, there was an API error : %s : %s' % (error.resp.status, error._get_reason())) except AccessTokenRefreshError: # Handle Auth errors. print ('The credentials have been revoked or expired, please re-run ' 'the application to re-authorize')
def get_profile_id(service): accounts = service.management().accounts().list().execute() account_list = accounts.get('items') account_list = account_list[0:10] for account in account_list: time.sleep(0.025) id = account.get('id') webproperties = service.management().webproperties().list(accountId=id).execute() webproperties = webproperties.get('items') for webproperty in webproperties: id_web = webproperty.get('id') profiles = service.management().profiles().list(accountId=id,webPropertyId=id_web).execute() profiles = profiles.get('items') for profile in profiles: profile_id = profile.get('id') return profile_id return None
def get_results(service,profile_id): return service.data().ga().get( ids='ga:' + profile_id, start_date='2013-03-23', end_date='2013-03-25', metrics='ga:visits',#ga:goalCompletionsAll,ga:pageviews',#ga:pageviewsPerVisit',#ga:timeOnSite, dimensions='ga:source',#'ga:customVarValue1', #ga:adContent', # ga:campaign', sort='-ga:visits', #filters='ga:medium==organic', #start_index='1', max_results='25')
class A(models.Model): source = models.ForeignKey(B, related_name='source') target = models.ForeignKey(B, related_name='target') status = models.IntegerField(default=1) class B(models.Model): name = models.CharField() compatibility = models.ManyToManyField( 'self', symmetrical=False, through='A', blank=True, null=True ) class C(models.Model): myb = models.ForeignKey(B) name = models.CharField()
q = C.objects.filter(name='blahblah').\ order_by('myb__name').\ select_related('myb').\ prefetch_related('myb__source', 'myb__target', 'myb__compatibility')
{% for q in myb.source.all %} {{ q.target.name|capfirst }} ({{ q.status }})<br/> {% endfor %}
#.... prefetch_related('myb__source')
{ "name": "Test1" "values": { "value1": "1" "value2": "2" } "id": 55 }