text
stringlengths
29
850k
#!/usr/bin/env python3 # Apenas para poder manipular a linha de comando import sys # Manipulacao do historico de comandos para facilitar os testes. import readline histfile = ".history" try: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) del histfile # Importando o analizador lexico e sintático import ply.lex as lex import ply.yacc as yacc class Calc: def __init__(self, transmite_erros=False): """ Inicializador, pode receber True como segundo argumento permitindo o não tratamento de erros. """ self.transmite_erros = transmite_erros # Caso queira rodar por linha de comando os erros são repassados ao invés de tratados. self.resposta = None # Resposta self.names = { } # Nomes de variáveis lex.lex(module=self) yacc.yacc(module=self) def analisar(self, s): """ Inicializa uma análise """ self.resposta = None self.nao_vazio = False yacc.parse(s) return self.resposta # Definicao dos tokens tokens = ( 'NOME','NUMERO', 'SOM','SUB', 'MUL','DIV','ATRIB', ) def t_SOM(self, t): r'\+' self.nao_vazio = True return t def t_SUB(self, t): r'-' self.nao_vazio = True return t def t_MUL(self, t): r'\*' self.nao_vazio = True return t def t_DIV(self, t): r'/' self.nao_vazio = True return t def t_ATRIB(self, t): r'=' self.nao_vazio = True return t def t_NOME(self, t): r'[a-zA-Z_][a-zA-Z0-9_]*' self.nao_vazio = True try: self.names[t.value] except KeyError: self.names[t.value] = None return t def t_NUMERO(self, t): r'\d+\.?\d*[eE][+\-]?\d+|\d+\.?\d*' self.nao_vazio = True try: t.value = float(t.value) except ValueError: if self.transmite_erros: raise print("Por favor, digite apenas numeros validos:", t.value[0]) t.value = 0 return t # Ignorando tabulacoes t_ignore = " \t\v" def t_error(self, t): if self.transmite_erros: raise TypeError print("Caracter incorreto '%s'" % t.value) t.lexer.skip(1) # Regras de analise sintatica precedence = ( ('right', 'NOME', 'NUMERO'), ) def p_expressao(self, p): 'statement : expression' self.resposta = p[1] def p_expressao_dupla(self, p): """ expression : expression expression SOM | expression expression SUB | expression expression MUL | expression expression DIV | NOME expression ATRIB """ if p[1] is not None and p[2] is not None: if p[3] == '=': p[0] = self.names[p[1]] = p[2] elif p[3] == '+': p[0] = p[1] + p[2] elif p[3] == '-': p[0] = p[1] - p[2] elif p[3] == '*': p[0] = p[1] * p[2] elif p[3] == '/': try: p[0] = p[1] / p[2] except ZeroDivisionError: if self.transmite_erros: raise print("Divisao por zero!") def p_expressao_dupla2(self, p): """ expression : NOME expression SOM | NOME expression SUB | NOME expression MUL | NOME expression DIV """ if p[1] is not None and p[2] is not None: if p[3] == '+': p[0] = self.names[p[1]] + p[2] elif p[3] == '-': p[0] = self.names[p[1]] - p[2] elif p[3] == '*': p[0] = self.names[p[1]] * p[2] elif p[3] == '/': try: p[0] = self.names[p[1]] / p[2] except ZeroDivisionError: if self.transmite_erros: raise print("Divisao por zero!") def p_nome(self, p): 'expression : NOME' p[0] = self.names[p[1]] if self.names[p[1]] is None: if self.transmite_erros: raise KeyError print("Variavel '%s' sem atribuicao" % p[1]) def p_numero(self, p): 'expression : NUMERO' p[0] = p[1] def p_error(self, p): if self.nao_vazio: if self.transmite_erros: raise LookupError print("Erro de sintaxe!", p) if __name__ == '__main__': s = ' '.join(sys.argv[1:]) f = len(s) != 0 calc = Calc(f) while 1: r = calc.analisar(s) if r is not None: print("%.4g" % r) pass if f: break try: s = input('calc > ') except (EOFError, KeyboardInterrupt): print() break
How do you determine the timeline for closing a deal? Home / HubSpot Inbound Sales Exam Answer / How do you determine the timeline for closing a deal? Ask the prospect when they need to achieve their goal and work backwards from that date to determine when they need to sign the contract. Ask the prospect when they need to achieve their goal and have them sign the contract on that date. Recommend a deadline based on the length and complexity of your sales cycle. Allow the prospect to choose the date they think will be best for closing the deal. Previous post: Where in your presentation should you present case studies on other companies you’ve worked with? Next post: How should you begin your sales presentation?
#!/usr/bin/env python """**************************************************************************** * nodeKnock-Client 0.2 by freddyb * * this is one of many possible nodeKnock clients, and is meant to be as a * proof of concept. * ****************************************************************************""" from time import time from hashlib import sha1 from commands import getoutput from sys import exit try: execfile('nodeKnock.cfg') except: print "Error: File nodeKnock.cfg does not exist!" exit(1) # prepare command cmd1 = "ping -c 1 -p " cmd2 = " "+ config['host'] # build pattern header = "4e444b" # i.e. "NDK" t = int(time()) # timestamp-integer p_timestamp = hex(t)[2:] # hex, because ping demands this. #sha1(client_ip + secret + timestamp') p_hash = sha1( config['own_ip'] + config['secret'] + str(t)).hexdigest() # build string for execution pattern = header + p_timestamp + p_hash execStr = cmd1 + pattern + cmd2 # ping -c1 -p^ ^bytes ^host print "Executing", repr(execStr) print getoutput(execStr) #DEBUG: print [int(pattern[2*i:2*i+2],16) for i in xrange(len(pattern)/2)]
Below are some of the more popular Healthcare job descriptions that includes a brief description of job duties and typical educational requirements. Typically works in a hospital, physician's office, or outpatient facility. The admissions clerk is usually the first person the patients sees. They greet the patient, collect patient information such as name, address, and contact info as well as collect insurance information. They also set up appointments, and take insurance co-pay’s and other patient payments. The admissions clerk may also have patients fill out a variety of forms related to insurance, medical history, HIPAA privacy, etc. and reviews this paperwork to insure they are filled out and signed as needed. Clerks may also enter this information into the medical records or practice management software, scan the forms, or file this information. Education required is a minimum high school diploma. More common is the completion of an administrative assistant program offered by a vocational or community college ranging from a certificate up to a two year associates degree. Chiropractors use natural treatment methods to deal with ailments of the musculoskeletal system. This primarily includes the spine, back, and neck. The philosophy is based on the alignment of the joints and spine and the related impact on the nervous system. Chiropractors also treat patients through changes in lifestyle, exercise, and diet. Chiropractors cannot prescribe medication other than recommend herbal and over the counter medications. To become a Chiropractor requires graduating from an accredited program recognized by the Council on Chiropractic Education and earning a Doctor of Chiropractic degree. This is not the same as a medical doctor or MD degree. A bachelors degree is not a requirement for entering chiropractic school, however candidates must complete 90 semester hours to be accepted into a chiropractic program. Achieving a Doctor of Chiropractic typically takes four years. Chiropractors are required to be licensed by passing a four part test given by the National Board of Chiropractic Examiners (NBCE). Maintaining their license requires meeting continuing education requirements. Most states recognize the NBCE testing for licensure. Cardiovascular technicians help physicians diagnose and treat heart and other diseases related to blood vessels and the circulatory system. They work mostly in hospital environments. The technologist also helps in the treatment of these conditions. This could include gathering patient medical history, preparing patients for tests, keeping the patient informed on procedures and tests or assisting the physician in performing procedures. Many heart patients undergo tests which a cardiovascular technologist would assist with or administer. This would include an electrocardiogram (EKG), and the associated electrodes and monitors when performing a stress test. These procedures are frequently catheterizations which involves threading a small tube through the patients artery. The technologist may assist in monitoring the patients vital signs during these procedures. Technologists may times using imaging equipment to assist in diagnosing a patient's condition. This could include ultrasound or more advanced imaging equipment. They may also perform non-invasive tests using ultrasound to detect issues with a patients heart or circulatory system. Training for the cardiovascular technician typically involves attending a two or four year program from an accredited school. Dentists treat problems associated with the teeth and gums. They also provide preventive advice in brushing, flossing, and diet. Dentists frequently use x-rays to identify and cavities or other problems with the teeth and gums. If a suspect tooth is found, the dentist will more closely examine the integrity of the tooth. Treatment may involve removing decay, filling cavities, applying sealants, removing tooth, performing root canals, and restorative treatments such as crowns. Dentists also repair cracked or broken teeth and frequently administer anesthetics during these procedures to prevent pain. A branch of dentistry called Endodontics specializes in performing more invasive procedures such as root canals. The area of dentistry that specializes in straightening teeth and correcting bite problems is called Orthodontics. Periodontists are another common specialty responsible for treating gum diseases and the underlying bones which support the teeth. Many times a dentist will manage a small office that can include a receptionist, dental assistant, hygienist, and possible a lab technician. Dentists are require a license to practice in the United States. The American Dental Association is the professional organization which promotes the profession. Before entering dental school, a student must have at least 2 years of college education. Dental school typically lasts another four years. A dental assistant prepares the patient for dental procedures, sets up the necessary equipment, and assists the dentist during procedures. At the beginning of the visit, they seat the patient, prepare for dental procedures, and retrieve the patients files. During procedures the dental assistant handing the dentist tools, applies suction to the patients mouth, and holds instruments. They may also take x-rays, impressions, and order supplies. They also give instruction in oral hygiene and care after a dental procedure. Responsibilities may also include assisting at the front office with scheduling follow-up appointments, updating patient files, and processing insurance or patient payments. More accomplished assistants may help with dental impressions and crowns. Many states regulate the functions a dental assistant may perform without training and experience. Some dental assistants learn on the job. A formal training program offered through community colleges and vocational schools can last from 6 months to two years. A dental hygienist is less of an administrative role than the dental assistant. They are primarily responsible for patient preventive dental care and typically perform teeth cleaning and other common dental procedures and tests without the supervision of the dentist. During the cleaning process they will remove plaque from teeth, apply fluoride, and inspect teeth and gums for any signs of decay or disease. Other responsibilities include showing patients how to brush and floss and care for teeth after a procedure. Education is typically a two year associates degree from an accredited school in dental hygiene. Most states also require a license in order to practice in the field. Since they are licensed, most do not pursue certification credentials in the field. The American Dental Hygienists Association (ADHA) is the professional association that promotes the dental hygiene profession. EMT or Paramedics provide emergency medical treatment and are the first responders for medical emergencies. They provide initial treatment, assessment, and stabilization of a patient and make sure they are safely transported to the hospital. EMT job responsibilities depend on the level of training and certification. First Responder provides basic first aid and are trained in how to move patients. EMT-Basic can give prescribed medication and perform non-invasive tasks such as apply splints, control bleeding, and provide oxygen to the patient. EMT Intermediate 1985 can perform more invasive procedures. This includes administering intravenous fluids and clearing the patients airway. EMT-Intermediate 1999 can give medication to for the heart and more invasive procedures to remove internal air or fluid from a patient. EMT-Paramedic can administer medication orally or intravenously. They can also perform surgical procedures to clear the patient's airway and install catheters. Many community colleges and universities offer EMT training programs. These programs can take from six months to four years depending on the level of training and credentials. Certification for EMT’s is through the National Registry of Emergency Medical Technicians through testing and continuing education. Enter information for insurance claims including name, insurance ID, diagnosis and treatment codes with modifiers, and provider ID. Makes sure claim information is complete and accurate. Submits insurance claims to clearinghouse or insurance company electronically or by paper. Answers patient questions on patient about their accounts. May work with patients to set up a payment plan. Follows up on unpaid or rejected claims and re-submits claims. Prepares patient statements and sends them out. Posts insurance and patient payments in practice management software. Prepares secondary claims for patients with multiple insurance coverage. Follows HIPAA guidelines in handling patient information. Creates reports showing the status of insurance claims and patient accounts. Working knowledge of diagnosis and treatment codes. A medical coder analyzes patient charts and assigns appropriate diagnosis and treatment codes. The diagnoses are ICD-9-CM codes (soon to be ICD-10 codes) and the corresponding CPT treatment codes. The treatment codes may also have additional coding referred to as modifiers that more specifically defines the treatment. Once the codes are determined the coder may enter these into the practice management (or medical billing) software. These codes are important in determining the insurance company payments to the provider. There are a variety of medical coding credentials and specialties available through organizations such as American Academy of Professional Coders (AAPC) and American Health Information Management Association (AHIMA). The medical office manager has responsibility for medical office administration and operation. The duties of the office manager depend a lot on the size of the practice or facility. For a larger practice this may include supervising office staff which would include the receptionist, billing specialist, or anyone who performs administrative functions. They may also interview and hire these positions. They typically oversee medical office functions such as billing, scheduling appointments, greeting patients, managing patient files, bookkeeping, and ordering office supplies. A good medical office manager should have good leadership and organizational abilities, the ability to resolve conflict, customer service and communications skills, and the ability to multitask and prioritize work. A medical office manager will typically have as a minimum an associates or bachelors degree in business or a related field. Medical records technicians organizes and manages patient information for a health care provider or facility. They are responsible for insuring the patient records are accurate, complete, accessible, and secure. This information includes - but is not limited to - diagnosis, treatment, symptoms, tests and examinations with results, medication, etc. Most medical records are electronic requiring the technician to be familiar with electronic medical records software - also referred to as EMR (electronic medical records) or EHR (electronic health records). Before entering information into the EMR system, the medical records technician reviews forms and insures they are completed correctly, accurate, and have the proper authorizations. With the significant changes in healthcare technology and government mandated changes, the role of the medical records technician is becoming very important. Federal government initiatives such as HIPAA, Meaningful Use, and the Affordable Care Act will make the records technician a key person for these programs. Typical education needed to become a medical records technician is a minimum two year associates degree. Many vocational, community, and technical schools offer programs in health information technology. Established universities also offer four year bachelors programs for those interested in management positions in the field. Typically certification is not required for medical records jobs. The American Health Information Management Association (AHIMA) offers several types of certification in the field. Medical Secretaries perform the administrative assistant duties in a healthcare environment. Typical responsibilities are typing and use of word processors, email, and spreadsheets to prepare reports and presentations. They also must be proficient in using telephone systems, setting up meetings and video conferences, and manage the the office supply needs. Training goes beyond the typical administrative assistant curriculum to include medical terminology, procedures, and medical records as well as the nomenclature unique to their physicians field of specialty. A medical secretary will commonly have as a minimum a two year associates degree and some experience or training in the medical field. Traditional medical transcription is the process of converting voice recorded or handwritten information dictated by physicians or other health care providers into text format. The transcriptionist recognizes mistakes and inconsistencies in medical terminology, anatomy, and medication and consulting with the physician to correct. The medical transcriptionist will typically listen to recordings on headphones and enters text into a computer word processor or similar application dedicated for transcription. The transcription files received can be in either digital or analog format (like a tape recording), but most frequently digital as these files can be transmitted or downloaded electronically. Medical transcription is the primary way for a health care provider to communicate with other providers who access medical records. The transcribed reports are typically stored electronically. These documents can be physical examination reports, medical history, autopsy results, operation reports, or diagnostic studies. The transcription documents are returned to the provider for review, correction, and approval. The transcribed records may be printed on paper and maintained as part of the patient file. Medical transcriptionists typically complete as a minimum a one year certificate to a two year associates program in transcription. These can be obtained through community or vocational schools. Nurses work in a wide variety of healthcare settings. The most common are hospitals, physicians offices, clinics, nursing homes, outpatient facilities. The “RN” designation is for Registered Nurse who has completed an associates or bachelors degree and passed the nursing certification exam. The “LPN” is for Licensed Practical Nurse which has completed one year of coursework after high school. There are many different types of nurses and many different career paths in the profession. Nurses make up one of the largest professions in health care. A nurses responsibility is to carry out the treatments and medications prescribed by the physician. Nurses spend more time with the patient and work hard to make sure the patient treatment is successful. They also serve an important role in comforting and reassuring a patient during their recovery and are involved in every part of a patients care. Other duties include may include administering IV’s, injections, maintaining medical records, assisting with hygiene and preparation for surgical procedures. The American Nursing Association is the most popular nursing association. The Nursing Assistant is also referred to as an orderly. They typically work in a hospital, nursing home, or as a home health aide. Duties include assisting a patient with activities such as bathing, eating, getting dressed, or transportation within the healthcare facility. Many nursing assistants have Certified Nurse Assistant (CNA) credentials. Nursing Aides will spend a lot of time with a patient and should have good interpersonal skills. They are typically supervised or directed by a nurse or physician. Many vocational or technical colleges offer CNA programs that can be completed anywhere from 6 weeks to 3 months. Occupational therapists work with patients who have temporary or permanent disabilities to learn basic life and motor skills. These disability may be caused by illness, developmental problems, brain injury, mental disorder, or another physical issue. Typical work settings are in hospitals, nursing homes, a patient’s home, or educational facilities. The therapist will usually use physical exercises as part of the treatment plan. The Occupational Therapist must maintain very detailed records of the patients progress. An occupational therapist helps to teach and train patients how to shop at a store, dine at a restaurant, take public transportation, converse with others, tell time, and other basic skills and tasks which are necessary for the patient to have some degree of independence in life, or in work settings. Education to become an Occupational Therapist is usually either a Masters or Doctorate degree. At a minimum this could take 5 to 6 years to complete. Certification is voluntary and given by the National Board for Certifying Occupational Therapy. The credential is called the Occupational Therapist Registered (OTR) certification upon passing the certification exam. A Pharmacist is responsible for dispensing prescription medications and informing the patient about the drugs and any interactions special instruction for taking the medication. provide information about the drugs their doctors have ordered for them. They explain doctors' instructions to patients so that these individuals can use these medications safely and effectively. The pharmacist also provide advice and recommendations for over-the-counter medication. To become a pharmacist requires earning a Doctor of Pharmacy degree which typically takes 4 years to complete. This is in addition to at least two years of college study and successful completion of a Pharmacy College Admissions Test. All Pharmacists are licensed within the state that they practice and must pass the North American Pharmacist Exam which is given by the National Association of Boards of Pharmacy (NABP). Many states also require passing the Multistate Pharmacy Jurisprudence Exam which concerns pharmacy law. A physician assistant practices medicine under the supervision of a physician and perform many of the same duties as the physician. A physician assistant does not perform administrative duties like a medical assistant. The educational requirements for becoming a physician assistant is a masters degree from an institution with an accredited Physician Assistant program. This typically takes two years in addition to the four years required to complete a bachelors degree. The Physical Therapist assists patients with physical limitations that can be the result of injuries to the head or back, stroke, arthritis, or other injuries or handicaps. Physical therapy treatment begins with an evaluation of the patients needs through observation and a review of their medical history in order to develop a treatment plan. To be effective and successful in the field requires the ability to relate to a patient, a compassionate understanding of their situation, and ability to motivate them to reach their treatment goals. Physical Therapy treatment will involve exercises designed to increase mobility, coordination, range of motion, and strength. Work setting can be a hospital, nursing home, outpatient care facilities, or the patient’s home. Becoming a physical therapist requires as a minimum a bachelors degree from an accredited program and successfully passing a licensing exam. Many in the field also complete a masters degree which typically takes another two years. Maintaining licensure requires continuing education in the field.
""" Django settings for cms_example project. Generated by 'django-admin startproject' using Django 1.9.13. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '@(l@&t1_9u@5)2^0%_8jdg7yk00v^hqzj(%o$3yh9$$)xw+3a(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] #Site ID for Django CMS SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'example_plugins', ] MIDDLEWARE_CLASSES = [ 'cms.middleware.utils.ApphookReloadMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ] ROOT_URLCONF = 'cms_example.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'sekizai.context_processors.sekizai', 'cms.context_processors.cms_settings', ], }, }, ] WSGI_APPLICATION = 'cms_example.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432 } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ('de', 'German') ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' #Media is about uploads from users. In production, I'd normally use S3 for this MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CMS_TEMPLATES = [ ('home.html', 'Home page template'), ] #Easy Thumbnails Settings THUMBNAIL_HIGH_RESOLUTION = True THUMBNAIL_PROCESSORS = ( 'easy_thumbnails.processors.colorspace', 'easy_thumbnails.processors.autocrop', 'filer.thumbnail_processors.scale_and_crop_with_subject_location', 'easy_thumbnails.processors.filters' ) #Tableau Settings TABLEAU_USERNAME = 'pat@downpatproductions.com' TABLEAU_PASSWORD = 'q9zOoyulCISLYAXSxtIwH2n' TABLEAU_SITE = 'downpatproductions' TABLEAU_SERVER = 'https://us-east-1.online.tableau.com'
Hey dude! I quite agree with your opinion. I really value what you’re doing here.
""" homeassistant.components.media_player.snapcast ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides functionality to interact with Snapcast clients. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.snapcast/ """ import logging import socket from homeassistant.components.media_player import ( SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, MediaPlayerDevice) from homeassistant.const import STATE_OFF, STATE_ON SUPPORT_SNAPCAST = SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE DOMAIN = 'snapcast' REQUIREMENTS = ['snapcast==1.1.1'] _LOGGER = logging.getLogger(__name__) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the Snapcast platform. """ import snapcast.control host = config.get('host') port = config.get('port', snapcast.control.CONTROL_PORT) if not host: _LOGGER.error('No snapserver host specified') return try: server = snapcast.control.Snapserver(host, port) except socket.gaierror: _LOGGER.error('Could not connect to Snapcast server at %s:%d', host, port) return add_devices([SnapcastDevice(client) for client in server.clients]) class SnapcastDevice(MediaPlayerDevice): """ Represents a Snapcast client device. """ # pylint: disable=abstract-method def __init__(self, client): self._client = client @property def name(self): """ Device name. """ return self._client.identifier @property def volume_level(self): """ Volume level. """ return self._client.volume / 100 @property def is_volume_muted(self): """ Volume muted. """ return self._client.muted @property def supported_media_commands(self): """ Flags of media commands that are supported. """ return SUPPORT_SNAPCAST @property def state(self): """ State of the player. """ if self._client.connected: return STATE_ON return STATE_OFF def mute_volume(self, mute): """ Mute status. """ self._client.muted = mute def set_volume_level(self, volume): """ Volume level. """ self._client.volume = round(volume * 100)
We sell and install many types of commercial flooring, including: Acoustic Flooring. Linoleum, LVT, Vinyl & Safety Floors, Carpet Tiles, Double Glue Down Carpet. Call us today at 310-479-3761 or fill out our convenient Contact Form to request your free commercial flooring consultation. Barry Carpet – Proudly serving the Los Angeles commercial carpet & flooring needs since 1965.
#!/usr/bin/env python # # Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import channels except ImportError: sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 200 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.5, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.5, 0) src = blocks.add_cc() channel = channels.channel_model(0.001) thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) self.snk1 = qtgui.const_sink_c(npts, "Constellation Example", 1) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, channel, thr, (self.snk1, 0)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop()
InVogueJewelry: Synthetic Opals v. Opal Simulants Shaped Like Hamsa Hands, Dolphins, Etc. Synthetic Opals v. Opal Simulants Shaped Like Hamsa Hands, Dolphins, Etc. I get all sorts of "suggestions" from Etsy, and some are great and some aren't so great. Earlier this week, one suggestion was a Hamsa hand necklace that was described as a "synthetic opal". I clicked on it because I surely have never seen any opal that was purple with all sorts of evenly disbursed speckles (like the one on the left above). It was obviously not an opal. The seller went into great detail about how this was an "actual opal" that was lab-created. So I did some research (online and in person with a gemologist) and.... sorry--buyer beware, because that's not what this is. For most people, and for most things, the word 'synethtic' means basically "fake"or made with chemicals. I think of things like synthetic grass, synthetic hair, synthetic fabrics. It means that it's not natural, but is made to look like something else. Synthetic hair looks a lot like real hair, for example, but it's not made out of hair--probably nylon fibers or something. Same with synthetic grass, like Astroturf. It LOOKS like grass, but it is made out of some sort of plastic. So for most things, synthetic means "imitation". What Does "Synthetic" Mean in Jewelry? So this is confusing, because in the jewelry industry, "synthetic" doesn't mean the same thing as everywhere else. Synthetic gemstones are man-made, in a laboratory, but they have the same EXACT chemical make-up as its natural counterpart. For example, a synthetic ruby is absolutely a genuine ruby (corundum) with the same chemical, as well as physical and optical properties, as a natural ruby---except it's grown in a lab. Even diamonds are lab-grown. These are synthetic, ACTUAL diamonds, made of carbon, but are not natural--yet they are in fact diamonds, only lab created. I like to compare synthetic gemstones to ice: you can make ice in your freezer with water, or you can find natural ice in a glacier. They're both ice (frozen water, H2O), only one is man-made and the other develops naturally. What Does "Simulated" Mean in Jewelry? Simulated jewelry means just what you think---that something is an imitation of something else. There are lots of simulated gemstones. For example, Cubic Zirconia (CZ), Swarovski crystals, Moissanite, and even glass are all diamond simulants. These are stones that are faceted and LOOK like a diamond, but when examined, do not have the same chemical properties as a genuine diamond. Glass can be colored, as can CZs, to look like rubies or emeralds or other precious or semi-precious gemstones. Even other gems can be used as a simulant---for example white topaz looks like a diamond. So, a simulated gemstone is an imitation. A synthetic gemstone is a man-made actual gemstone. What is a Synthetic Opal v. Simulated Opal? While there are some synthetic opals available (which are lab-created opals, with the identical chemical as well as physical and optical properties of natural opal), the vast number of so-called synthetics are actually just simulated or imitation opals. They look like an opal, but they do not have any water in them, and in fact are often mostly resin (plastic). What about the Japanese "Kyocera" Synthetic Opals? These were tested by the GIA and were found to contain resin and no water. Therefore, these are simulated (imitation) opals, NOT true synthetic opals. What is "Opal Block" or "Block Opal"? I looked at the imitation opal blocks in various colors at Rio Grande, and it's amazing how beautiful and "real" this material looks! Especially the "fire and ice" (like white opal). The colors really flash and glow in the light and is pretty convincing! What About All Those "Synthetic Opal" Hamsa Charms and Round Beads? They are obviously NOT true synthetic opals, but are simulated opals. These can be purchased wholesale from alibaba and Ebay and Etsy and are generally misrepresented as synthetic opal. They seem to cost about $2-$5 each for a Hamsa, and about 20 cents for a round bead, and much less depending on volume ordered. If you look at some of the wholesalers from China, even though they are calling this "Synthetic" opal, as you scroll down the page, they explain that it is resin-filled or "stabilized". That is all you need to know that this is NOT an opal, but is an imitation opal. An opal cannot be both "synthetic" and stabilized! If it's stabilized (or plastic-filled), it's not an a actual opal. Synthetic opal (GIA: Polymer Impregnated synthetic opal) is impregnated in laboratory in around a year and has similar properties as that of natural opal. Our synthetic opal is a beautiful opal with perfect color dynamicity - revealed the beauty of Precious Opal. So although this particular wholesaler is describing this product as polymer filled with "similar properties as that of natural opal", they are still very misleading by calling it "synthetic opal". Plus there is no such thing as a "polymer impregnated synthetic" anything! The GIA never stated that! You can see their site HERE. Another wholesale company in China is selling these SAME Hamsa charms, only describing them as "Ethiopian Opal" Hamsa Hands!! That is very bad. These simulated or imitation opal beads and charms, in all their colors and shapes, are very pretty. They are also very inexpensive. They are fun to wear and would make lovely gifts. Just know that these are NOT genuine opals, whether lab-grown or natural, but are mostly plastic or resin imitation opals (lookalikes) that are molded or carved into shapes. These are pretty, but at a wholesale cost of under $2 to $5 (including a chain!), are not genuine precious opals or fine jewelry by any means. That said, I think these are extremely pretty (some colors more than others), and I'm considering buying one in the white "fire and ice opal" look to wear myself! Just know that it isn't really a gem Opal, and that it's a simulated opal. As long as you know what you're buying, enjoy your jewelry!! It's pretty and FUN and that's what jewelry is all about. I found your blog when I was doing a search on Moonstones. I have had a love affair with jewelry since I was a teen and a passionate affair with oddities, Antiques and Rocks and minerals forever. I was incredibly impressed by your articles. They are well researched which, Let's face it, in the Jewelry world can be a problem. Very articulate and easy to understand for beginner jewelry addicts! Very good work. Also you are insanely sweet for answering all those questions. Kudos! Thank you for your kind words! I really appreciate it!
# # Manta - Structural Variant and Indel Caller # Copyright (c) 2013-2015 Illumina, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # """ util -- simple utilities shared by bwa/gatk workflow objects """ __author__ = "Chris Saunders" import os import re def ensureDir(d): """ make directory if it doesn't already exist, raise exception if something else is in the way: """ if os.path.exists(d): if not os.path.isdir(d) : raise Exception("Can't create directory: %s" % (d)) else : os.makedirs(d) def skipJoin(sep,a,b) : if a == "" : return b elif b == "" : return a return a+sep+b def preJoin(a,b) : return skipJoin('_',a,b) def checkFile(filename,label="") : if os.path.isfile(filename) : return if label is None : label="" if label != "" : label=" "+label.strip() raise Exception("Can't find%s file '%s'" % (label,filename) ) def checkDir(dirname,label="") : if os.path.isdir(dirname) : return if label is None : label="" if label != "" : label=" "+label.strip() raise Exception("Can't find%s directory '%s'" % (label,dirname) ) def which(searchFile) : """ search the PATH for searchFile result should be the similar to *nix 'which' utility """ for searchPath in os.environ["PATH"].split(os.pathsep): test=os.path.join(searchPath,searchFile) if os.path.isfile(test): return test return None def parseGenomeRegion(regionStr) : """ parse a samtools region string and return a (chrom,start,end) tuple missing start and end values will be entered as None """ assert(regionStr is not None) word=regionStr.strip().split(':') if (len(word) < 1) or (len(word) > 2) : raise Exception("Unexpected format in genome region string: %s" % (regionStr)) chrom=word[0] if len(chrom) == 0 : raise Exception("Unexpected format in genome region string: %s" % (regionStr)) start=None end=None if (len(word) > 1) : rangeWord=word[1].split('-') if len(rangeWord) != 2 : raise Exception("Unexpected format in genome region string: %s" % (regionStr)) start = int(rangeWord[0]) end = int(rangeWord[1]) if (end < start) or (start < 1) or (end < 1) : raise Exception("Unexpected format in genome region string: %s" % (regionStr)) return {"chrom":chrom, "start":start, "end":end} def isValidSampleId(sampleId) : return re.match("^[A-Za-z0-9_-]+$", sampleId) def getBaiFileNames(bamFile) : "return (picard bai filename,samtools bai filename)" return (bamFile[:-(len(".bam"))]+".bai",bamFile+".bai") def javaHeapMemReqest(self,javaMb,javaMinMb=None,overheadMb=None) : """ Input is the amount of memory requested for the java heap, output is the amount of java heap memory you're going to actually get, and the total process memory (heap+overhead), to request for the task. If javaMinMb is not defined, it is assumed you need to full request If overheadMb is not defined, it is set to the global javaTaskHeapOverheadMb value return (javaMb,taskMb) """ if javaMinMb is None : javaMinMb=javaMb if overheadMb is None : overheadMb=self.params.javaTaskHeapOverheadMb javaMb=(self.limitMemMb(javaMb+overheadMb)-overheadMb) if javaMb < javaMinMb : raise Exception("Could not provide minimum java heap memory request for task. Minimum requested: %s Available: %s" % (str(javaMinMb),str(javaMb))) assert (javaMb>0) taskMb=(javaMb+overheadMb) return (javaMb,taskMb) def getFastaChromOrderSize(faiFile) : """ given a fasta index file, returns (chromOrder,chromSizes) where: chromOrder -- list of chromosomes in fasta order chromSizes -- hash of chromosome sizes """ assert os.path.isfile(faiFile) chromOrder=[] chromSizes={} for line in open(faiFile) : (chrom,size)=line.strip().split("\t",2)[:2] chromOrder.append(chrom) chromSizes[chrom]=int(size) return (chromOrder,chromSizes) def getChromIntervals(chromOrder,chromSizes,segmentSize, genomeRegion = None) : """ generate chromosome intervals no greater than segmentSize chromOrder - iterable object of chromosome names chromSizes - a hash of chrom sizes genomeRegionList - optionally restrict chrom intervals to only cover a list of specified chromosome region return chromIndex,chromLabel,start,end,chromSegment where start and end are formated for use with samtools chromSegment is 0-indexed number of segment along each chromosome """ for (chromIndex, chromLabel) in enumerate(chromOrder) : chromStart=1 chromEnd=chromSizes[chromLabel] # adjust for the custom genome subsegment case: if genomeRegion is not None : if genomeRegion["chrom"] is not None : if genomeRegion["chrom"] != chromLabel : continue if genomeRegion["start"] is not None : chromStart=genomeRegion["start"] if genomeRegion["end"] is not None : chromEnd=genomeRegion["end"] chromSize=(chromEnd-chromStart+1) chromSegments=1+((chromSize-1)/segmentSize) segmentBaseSize=chromSize/chromSegments nPlusOne=chromSize%chromSegments start=chromStart for i in xrange(chromSegments) : segSize=segmentBaseSize if i<nPlusOne : segSize += 1 end=min(start+(segSize-1),chromStart+chromSize) yield (chromIndex,chromLabel,start,end,i,genomeRegion) start=end+1 class PathDigger(object) : """ Digs into a well-defined directory structure with prefixed folder names to extract all files associated with combinations of directory names. This is written primarily to go through the CASAVA 1.8 output structure. #casava 1.8 fastq example: fqDigger=FileDigger(['Project_','Sample_'],".fastq.gz") """ def __init__(self,prefixList,targetExtension=None) : """ if no target extension, then list directories at the tip of the prefix list """ self.prefixList=prefixList self.targetExtension=targetExtension def getNextPath(self,basePath,depth=0,ans=tuple()) : """ """ if depth < len(self.prefixList) : for d in os.listdir(basePath) : nextDir=os.path.join(basePath,d) if not os.path.isdir(nextDir) : continue if not d.startswith(self.prefixList[depth]) : continue value=d[len(self.prefixList[depth]):] for val in self.getNextPath(nextDir,depth+1,ans+tuple([value])) : yield val else: if self.targetExtension is None : yield ans+tuple([basePath]) else : for f in os.listdir(basePath) : nextPath=os.path.join(basePath,f) if not os.path.isfile(nextPath) : continue if not f.endswith(self.targetExtension) : continue yield ans+tuple([nextPath]) def cleanId(input_id) : """ filter id so that it's safe to use as a pyflow indentifier """ import re return re.sub(r'([^a-zA-Z0-9_\-])', "_", input_id) def getRobustChromId(chromIndex,chromLabel): return "%s_%s" % (str(chromIndex).zfill(3),cleanId(chromLabel)) class GenomeSegment(object) : """ organizes all variables which can change with each genomic segment. The genomic segment is defined by: 1. chromosome 2. begin position (1-indexed closed) 3. end position (1-indexed closed) 4. chromosome segment (ie. bin) number (0-indexed) """ def __init__(self,chromIndex,chromLabel,beginPos,endPos,binId,genomeRegion) : """ arguments are the 4 genomic interval descriptors detailed in class documentation """ self.chromLabel = chromLabel self.beginPos = beginPos self.endPos = endPos self.bamRegion = chromLabel + ':' + str(beginPos) + '-' + str(endPos) self.binId = binId self.binStr = str(binId).zfill(4) self.id = chromLabel + "_" + self.binStr regionId=cleanId(chromLabel) if genomeRegion is not None : if genomeRegion['start'] is not None : regionId += "-"+str(genomeRegion['start']) if genomeRegion['end'] is not None : regionId += "-"+str(genomeRegion['end']) self.pyflowId = "chromId_%s_%s_%s" % (str(chromIndex).zfill(3), regionId, self.binStr) def getNextGenomeSegment(params) : """ generator which iterates through all genomic segments and returns a segmentValues object for each one. """ MEGABASE = 1000000 scanSize = params.scanSizeMb * MEGABASE if params.genomeRegionList is None : for segval in getChromIntervals(params.chromOrder,params.chromSizes, scanSize) : yield GenomeSegment(*segval) else : for genomeRegion in params.genomeRegionList : for segval in getChromIntervals(params.chromOrder,params.chromSizes, scanSize, genomeRegion) : yield GenomeSegment(*segval) def cleanPyEnv() : """ clear out some potentially destabilizing env variables: """ clearList = [ "PYTHONPATH", "PYTHONHOME"] for key in clearList : if key in os.environ : del os.environ[key] def isLocalSmtp() : """ return true if a local smtp server is available """ import smtplib try : smtplib.SMTP('localhost') except : return False return True
Viral phenomenon on the Internet more frequently concern “Cats that Look like Hitler” or racy photos of Prince Harry cavorting in Las Vegas. Insurance claims rarely go viral on social media, but that changed recently with a controversial underinsured motorist claim involving Progressive Insurance Company. (Find background on the case at the following link: http://money.cnn.com/2012/08/17/technology/progressive-settlement/index.html?hpt=hp_t2 ). The sad facts here are straightforward. Progressive Insurance Company policyholder Katie Fisher died in a 2010 automobile crash in Maryland. Allegedly, the other driver ran a red light, though there was a dispute as to who had the green light and the right-of-way. The driver that struck Katie’s vehicle was under-insured. The good news: Katie had bought UIM — underinsured motorist coverage. The bad news: to collect, Katie’s family had to sue the other driver for negligence to force Progressive to pay. However, when the family sued the other driver, Progressive’s attorneys associated with the other drivers attorneys to defend the liability claim. As a result, the deceased’s brother went viral in social media rounds, complaining that Progressive used premium dollars to defend his sister’s killer in court. That makes for an arresting headline. This claim illustrates the importance of an insurance company being attuned to social media and having a social media policy. Of course, here Progressive did not stick its head in the sand. It did not ignore the social media buzz surrounding its handling of the case. Apparently, it responded but responded in a way perceived as tone-deaf. Progressive in a Lose-Lose Situation? Maybe Progressive Insurance Company was in a no-win situation. If it ignored the social media banter about its stance, consumers would accuse it of insensitivity. It entered the dialogue to justify its actions. In so doing, people accused it of being tone-deaf to consumer sensitivities. I don’t know what response Progressive could have launched on social media that would have satisfied its critics. This vignette underscores how little people understand what they buy when purchasing underinsured motorist coverage. Buying underinsured motorist coverage essentially risks putting you at odds with your own insurance company. In such a claim, your own insurance company is incentivized to show that you in fact were at fault for the accident and/or that your injuries were not the result of the negligence of an underinsured driver. People assume that the insurance company to whom they paid their premiums will always be on their side. Typically, this is the case. Typically, this is the alignment of interests. In underinsured motorist coverage and claims, however, “typical” doesn’t necessarily apply. Here, interests are aligned differently. Just because you pay your insurance company for the coverage doesn’t mean that — in a claim involving an underinsured adverse driver — your insurance company is going to act all soft and fuzzy. Of course, insurance companies would not effectively market and sell underinsured motorist coverage if they made this reality explicit and spotlighted it in the sales process. People don’t think it through. Nobody really believes deep down they will be hurt due to the fault of an underinsured driver. If they pay for the coverage, perhaps they pay for it begrudging at best. So, those who say “Shame on Progressive” for its stance adverse to its own policyholder could add, “Shame on the policyholder” for not realizing the dynamics in underinsured motorist claims. Of course, it sounds callous to be lecturing a family on the dynamics of claims-handling when they have lost their daughter in a fatal car accident. Further, there was a reasonable question of fact as to who had the right-of-way. Should Progressive and its adjusters have ignored evidence that the deceased may have been at fault in order to pay the claim? It’s difficult to fault Progressive’s adjusters here, as tempting as it may be to do so. There was a legitimate dispute as to who had the right-of-way and who ran the red light. Was Progressive wrong for exercising its legal right to seek a judicial determination of liability? Nevertheless, insurance companies now face not just bad faith risks over how their claim department handles or mishandles an automobile loss. They also face reputational risks if disgruntled consumers take to Twitter, Facebook, blogs, Tumblr, etc. to air their gripes. The Internet and social media provides a bully pulpit and cyberspace megaphone for anyone who has a beef, whether that complaint is justified or specious. On the other hand, since everyone now has electronic megaphone via the Internet, World Wide Web and social media, the cacophony of complaints can create a “white noise” effect that makes any one complaint difficult to stand out. This complaint did stand out, though, and got widespread media play. While it is tempting to say “No comment” or to say, “We won’t try our case in the media,” insurance companies — like other businesses — cannot take an ostrich approach and stick their heads in the proverbial sand. they must be able to articulate a concise yet compelling message to an often skeptical audience. It’s not enough to handle the claim conscientiously. It’s not enough to handle it in accord with the policy Conditions. It’s not enough to comply with state insurance department regulations. It’s not enough to believe that you acted in good faith. If you have an under-insured motorist claim, you must realize that your adjuster will not be perky Flo from the TV commercials. Sorry — those questions are so 2010. That no longer cuts it as a coherent social media strategy. It’s no longer enough to have a digital footprint in the social media world. The content of what companies put out on social media is vital, scrutinized, and should promote their brand. Content is king. Moreover, insurance companies must have institutionalized disciplines to monitor what is being said about them on social media so they can respond quickly and persuasively. The consumer conversation about your service and policies is going on — with you or without you. It is best that goes on with you. It’s best that you have an opportunity to be aware of customer service firestorms brewing so that you have the opportunity to squelch them, address them and nip them in the bud. You may have to justify your steps in the court of public opinion through social media or suffer the consequences of a public relations black eye if you hunker down and go incommunicado. As this case study shows, adjusters are sometimes damned if they do and damned if they don’t. Pay the claim in the face of conflicting evidence, and be second-guessed for poor decision-making by higher-ups. Contest the claim and align yourself with the other drivers insurance company, and you get criticized in the court of public opinion for callousness. No one promised adjusters a rose garden and they certainly don’t get to operate in one in the age of viral posts and social media! Kevin Quinley CPCU, AIC, ARM is a claim consultant and Principal at Quinley Risk Associates LLC near Richmond, VA. You can reach him at kevin@kevinquinley.com or at (804) 796-1939.
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 350, 100) self.setWindowTitle('Colours') self.show() def paintEvent(self, e): qp = QtGui.QPainter() qp.begin(self) self.drawRectangles(qp) qp.end() def drawRectangles(self, qp): color = QtGui.QColor(0, 0, 0) color.setNamedColor('#d4d4d4') qp.setPen(color) qp.setBrush(QtGui.QColor(200, 0, 0)) qp.drawRect(10, 15, 90, 60) qp.setBrush(QtGui.QColor(255, 80, 0, 160)) qp.drawRect(130, 15, 90, 60) qp.setBrush(QtGui.QColor(25, 0, 90, 200)) qp.drawRect(250, 15, 90, 60) def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
Pinnacle Printing began as a sole proprietorship in the basement of Rick and Ann Reinman's home in Redford in August of 1984. (They were married and purchased that home all in that same year.) Although he was still employed full time at White Graphics in Troy, Rick produced print jobs at night that Ann had sold during the day. They continued this system for over a year until the opportunity came in 1986 to rent a small space in Farmington Hills that had previously housed another printer. They quickly added staff and additional equipment purchased at auctions and at an IRS foreclosure and business grew steadily. In 1988, with a customer service person, press operator and bindery person, they incorporated as RAR Group Inc but kept their dba of Pinnacle Printing. They also invested in their first print shop software - Printer's Plus - and moved to a larger space in Bridge Industrial Park in Southfield. The shop has remained in that location to this day. They soon became members of the Southfield Chamber of Commerce, being active participants in many of the Chamber and Southfield Community events. After adding a true two-color press - an Itek 3985 in 1990 - they started printing four color process jobs in-house the hard way - two colors at a time. The press cost as much as their house did and it was unthinkable at that time to consider a four-color press! Rick and Ann have never been big risk takers, you see, and that is one of the reasons that you can always trust what they tell you - especially about completing your jobs correctly and on time. Rick always errs on the side of caution when making promises - knowing that clients are really depending on him to get their projects done on time. Ann & Rick have always considered their business direction to be "customer driven" - looking at the latest technology and innovations but not necessarily being the first to buy. As clients asked for products or services that required outside suppliers or equipment investments, the Reinmans have researched their options thoroughly and have kept up with the times - whether in software and computer hardware decisions or by adding services or totally new equipment. The adding of the digital (toner based) equipment they currently have and becoming promotional product distributors - both in 2004 - are very tangible examples of the business now called Pinnacle Printing & Promotions keeping up with the times. It seems like every company talks about the importance of customer service, but one of the lasting cornerstones of Pinnacle is the way our customers feel about doing business with us. Our dependability and reliability have become very renowned. When you work fast, hardly ever miss a deadline, have fair prices, and treat people with dignity and respect it's hard not to grow your business. We invite you to consider using Pinnacle the next time your company needs printing, copying or promotional items. There's a reason why we have survived the recession and the Michigan economy over the last three years, and we would love the opportunity to demonstrate that for you on your next printing order. You see, we do things very differently than the other printers in our community, and we believe we can provide the best all-around experience for you if you'll give us a try. If you would like to talk to one of our customer service representatives, please call 248-353-2266. We would be happy to discuss how we can help your business succeed and prosper. Feel free to ask for Ann or Rick, the owners, when you call, and to inquire about taking a 15 minute tour of our business, hosted by one of them. Ann will also be more that happy to meet with you and your office or marketing staff at your location to learn about your printing and promotional needs and help you find cost effective, sure-fire solutions.
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Yannick Vaucher, Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## import logging from odoo.http import request from odoo import models, _ from odoo.exceptions import UserError from werkzeug.exceptions import Unauthorized try: import jwt except ImportError: raise UserError(_("Please install python jwt")) logger = logging.getLogger(__name__) class IrHTTP(models.AbstractModel): _inherit = 'ir.http' @classmethod def _auth_method_oauth2(self): if request.httprequest.method == 'GET': mode = 'read' if request.httprequest.method == 'POST': mode = 'write' token_data = request.httprequest.headers.get('Authorization') if not token_data: raise Unauthorized() token_authorization = token_data.split()[0] if token_authorization != 'Bearer': raise Unauthorized() access_token = token_data.split()[1] # Token validation options = { # not sure why, you might need to do that if token is not encrypted 'verify_signature': False, 'verify_aud': False } jwt_decoded = jwt.decode(access_token, options=options) # validation # is the iss = to Compassions IDP ? if jwt_decoded.get('iss') != 'https://esther.ci.org': raise Unauthorized() # is scope read or write in scopes ? if mode not in jwt_decoded.get('scope'): raise Unauthorized() client_id = jwt_decoded.get('client_id') logger.info("TOKEN CLIENT IS -----------------> " + client_id) user = request.env['res.users'].sudo().search( [('login', '=', client_id)]) if user: request.uid = user.id else: raise Unauthorized()
Whew, I misunderstood you! Glad to hear. I could tell you a few horror stories from my time that pushed me to decide to quit. Oooh no did it come across like a telling off? I apologise, not intended at all. They are allowed to talk to each other but not to discuss the evidence until they are sent out for deliberation. Robert Black was also a known serial offender yet escaped for years.
# -*- coding: utf-8 -*- """ Created on Wed May 6 17:07:00 2015 """ import numpy as np from scipy.optimize import newton _author__ = 'Julien Milli' class Dust_distribution(object): """This class represents the dust distribution """ def __init__(self,density_dico={'name':'2PowerLaws', 'ain':5, 'aout':-5, 'a':60, 'e':0, 'ksi0':1., 'gamma':2., 'beta':1.,'amin':0.,'dens_at_r0':1.}): """ Constructor for the Dust_distribution class. We assume the dust density is 0 radially after it drops below 0.5% (the accuracy variable) of the peak density in the midplane, and vertically whenever it drops below 0.5% of the peak density in the midplane """ self.accuracy = 5.e-3 if not isinstance(density_dico, dict): errmsg = 'The parameters describing the dust density distribution' \ ' must be a Python dictionnary' raise TypeError(errmsg) if 'name' not in density_dico.keys(): errmsg = 'The dictionnary describing the dust density ' \ 'distribution must contain the key "name"' raise TypeError(errmsg) self.type = density_dico['name'] if self.type == '2PowerLaws': self.dust_distribution_calc = DustEllipticalDistribution2PowerLaws( self.accuracy, density_dico) else: errmsg = 'The only dust distribution implemented so far is the' \ ' "2PowerLaws"' raise TypeError(errmsg) def set_density_distribution(self,density_dico): """ Update the parameters of the density distribution. """ self.dust_distribution_calc.set_density_distribution(density_dico) def density_cylindrical(self, r, costheta, z): """ Return the particule volume density at r, theta, z. """ return self.dust_distribution_calc.density_cylindrical(r, costheta, z) def density_cartesian(self, x, y, z): """ Return the particule volume density at x,y,z, taking into account the offset of the disk. """ return self.dust_distribution_calc.density_cartesian(x, y, z) def print_info(self, pxInAu=None): """ Utility function that displays the parameters of the radial distribution of the dust Input: - pxInAu (optional): the pixel size in au """ print('----------------------------') print('Dust distribution parameters') print('----------------------------') self.dust_distribution_calc.print_info(pxInAu) class DustEllipticalDistribution2PowerLaws: """ """ def __init__(self, accuracy=5.e-3, density_dico={'ain':5,'aout':-5,\ 'a':60,'e':0,'ksi0':1.,\ 'gamma':2.,'beta':1.,\ 'amin':0.,'dens_at_r0':1.}): """ Constructor for the Dust_distribution class. We assume the dust density is 0 radially after it drops below 0.5% (the accuracy variable) of the peak density in the midplane, and vertically whenever it drops below 0.5% of the peak density in the midplane """ self.accuracy = accuracy self.set_density_distribution(density_dico) def set_density_distribution(self,density_dico): """ """ if 'ksi0' not in density_dico.keys(): ksi0 = 1. else: ksi0 = density_dico['ksi0'] if 'beta' not in density_dico.keys(): beta = 1. else: beta = density_dico['beta'] if 'gamma' not in density_dico.keys(): gamma = 1. else: gamma = density_dico['gamma'] if 'aout' not in density_dico.keys(): aout = -5. else: aout = density_dico['aout'] if 'ain' not in density_dico.keys(): ain = 5. else: ain = density_dico['ain'] if 'e' not in density_dico.keys(): e = 0. else: e = density_dico['e'] if 'a' not in density_dico.keys(): a = 60. else: a = density_dico['a'] if 'amin' not in density_dico.keys(): amin = 0. else: amin = density_dico['amin'] if 'dens_at_r0' not in density_dico.keys(): dens_at_r0=1. else: dens_at_r0=density_dico['dens_at_r0'] self.set_vertical_density(ksi0=ksi0, gamma=gamma, beta=beta) self.set_radial_density(ain=ain, aout=aout, a=a, e=e,amin=amin,dens_at_r0=dens_at_r0) def set_vertical_density(self, ksi0=1., gamma=2., beta=1.): """ Sets the parameters of the vertical density function Parameters ---------- ksi0 : float scale height in au at the reference radius (default 1 a.u.) gamma : float exponent (2=gaussian,1=exponential profile, default 2) beta : float flaring index (0=no flaring, 1=linear flaring, default 1) """ if gamma < 0.: print('Warning the vertical exponent gamma is negative') print('Gamma was changed from {0:6.2f} to 0.1'.format(gamma)) gamma = 0.1 if ksi0 < 0.: print('Warning the scale height ksi0 is negative') print('ksi0 was changed from {0:6.2f} to 0.1'.format(ksi0)) ksi0 = 0.1 if beta < 0.: print('Warning the flaring coefficient beta is negative') print('beta was changed from {0:6.2f} to 0 (flat disk)'.format(beta)) beta = 0. self.ksi0 = float(ksi0) self.gamma = float(gamma) self.beta = float(beta) self.zmax = ksi0*(-np.log(self.accuracy))**(1./gamma) def set_radial_density(self, ain=5., aout=-5., a=60., e=0.,amin=0.,dens_at_r0=1.): """ Sets the parameters of the radial density function Parameters ---------- ain : float slope of the power-low distribution in the inner disk. It must be positive (default 5) aout : float slope of the power-low distribution in the outer disk. It must be negative (default -5) a : float reference radius in au (default 60) e : float eccentricity (default 0) amin: float minimim semi-major axis: the dust density is 0 below this value (default 0) """ if ain < 0.1: print('Warning the inner slope is greater than 0.1') print('ain was changed from {0:6.2f} to 0.1'.format(ain)) ain = 0.1 if aout > -0.1: print('Warning the outer slope is greater than -0.1') print('aout was changed from {0:6.2f} to -0.1'.format(aout)) aout = -0.1 if e < 0: print('Warning the eccentricity is negative') print('e was changed from {0:6.2f} to 0'.format(e)) e = 0. if e >= 1: print('Warning the eccentricity is greater or equal to 1') print('e was changed from {0:6.2f} to 0.99'.format(e)) e = 0.99 if a < 0: raise ValueError('Warning the semi-major axis a is negative') if amin < 0: raise ValueError('Warning the minimum radius a is negative') print('amin was changed from {0:6.2f} to 0.'.format(amin)) amin = 0. if dens_at_r0 <0: raise ValueError('Warning the reference dust density at r0 is negative') print('It was changed from {0:6.2f} to 1.'.format(dens_at_r0)) dens_at_r0 = 1. self.ain = float(ain) self.aout = float(aout) self.a = float(a) self.e = float(e) self.p = self.a*(1-self.e**2) self.amin = float(amin) self.pmin = self.amin*(1-self.e**2) ## we assume the inner hole is also elliptic (convention) self.dens_at_r0 = float(dens_at_r0) try: # maximum distance of integration, AU self.rmax = self.a*self.accuracy**(1/self.aout) if self.ain != self.aout: self.apeak = self.a * np.power(-self.ain/self.aout, 1./(2.*(self.ain-self.aout))) Gamma_in = self.ain+self.beta Gamma_out = self.aout+self.beta self.apeak_surface_density = self.a * np.power(-Gamma_in/Gamma_out, 1./(2.*(Gamma_in-Gamma_out))) else: self.apeak = self.a self.apeak_surface_density = self.a except OverflowError: print('The error occured during the calculation of rmax or apeak') print('Inner slope: {0:.6e}'.format(self.ain)) print('Outer slope: {0:.6e}'.format(self.aout)) print('Accuracy: {0:.6e}'.format(self.accuracy)) raise OverflowError except ZeroDivisionError: print('The error occured during the calculation of rmax or apeak') print('Inner slope: {0:.6e}'.format(self.ain)) print('Outer slope: {0:.6e}'.format(self.aout)) print('Accuracy: {0:.6e}'.format(self.accuracy)) raise ZeroDivisionError self.itiltthreshold = np.rad2deg(np.arctan(self.rmax/self.zmax)) def print_info(self, pxInAu=None): """ Utility function that displays the parameters of the radial distribution of the dust Input: - pxInAu (optional): the pixel size in au """ def rad_density(r): return np.sqrt(2/(np.power(r/self.a,-2*self.ain) + np.power(r/self.a,-2*self.aout))) half_max_density = lambda r:rad_density(r)/rad_density(self.apeak)-1./2. try: if self.aout < -3: a_plus_hwhm = newton(half_max_density,self.apeak*1.04) else: a_plus_hwhm = newton(half_max_density,self.apeak*1.1) except RuntimeError: a_plus_hwhm = np.nan try: if self.ain < 2: a_minus_hwhm = newton(half_max_density,self.apeak*0.5) else: a_minus_hwhm = newton(half_max_density,self.apeak*0.95) except RuntimeError: a_minus_hwhm = np.nan if pxInAu is not None: msg = 'Reference semi-major axis: {0:.1f}au or {1:.1f}px' print(msg.format(self.a,self.a/pxInAu)) msg2 = 'Semi-major axis at maximum dust density in plane z=0: {0:.1f}au or ' \ '{1:.1f}px (same as ref sma if ain=-aout)' print(msg2.format(self.apeak,self.apeak/pxInAu)) msg3 = 'Semi-major axis at half max dust density in plane z=0: {0:.1f}au or ' \ '{1:.1f}px for the inner edge ' \ '/ {2:.1f}au or {3:.1f}px for the outer edge, with a FWHM of ' \ '{4:.1f}au or {5:.1f}px' print(msg3.format(a_minus_hwhm,a_minus_hwhm/pxInAu,a_plus_hwhm,\ a_plus_hwhm/pxInAu,a_plus_hwhm-a_minus_hwhm,\ (a_plus_hwhm-a_minus_hwhm)/pxInAu)) msg4 = 'Semi-major axis at maximum dust surface density: {0:.1f}au or ' \ '{1:.1f}px (same as ref sma if ain=-aout)' print(msg4.format(self.apeak_surface_density,self.apeak_surface_density/pxInAu)) msg5 = 'Ellipse p parameter: {0:.1f}au or {1:.1f}px' print(msg5.format(self.p,self.p/pxInAu)) else: print('Reference semi-major axis: {0:.1f}au'.format(self.a)) msg = 'Semi-major axis at maximum dust density in plane z=0: {0:.1f}au (same ' \ 'as ref sma if ain=-aout)' print(msg.format(self.apeak)) msg3 = 'Semi-major axis at half max dust density: {0:.1f}au ' \ '/ {1:.1f}au for the inner/outer edge, or a FWHM of ' \ '{2:.1f}au' print(msg3.format(a_minus_hwhm,a_plus_hwhm,a_plus_hwhm-a_minus_hwhm)) print('Ellipse p parameter: {0:.1f}au'.format(self.p)) print('Ellipticity: {0:.3f}'.format(self.e)) print('Inner slope: {0:.2f}'.format(self.ain)) print('Outer slope: {0:.2f}'.format(self.aout)) print('Density at the reference semi-major axis: {0:4.3e} (arbitrary unit'.format(self.dens_at_r0)) if self.amin>0: print('Minimum radius (sma): {0:.2f}au'.format(self.amin)) if pxInAu is not None: msg = 'Scale height: {0:.1f}au or {1:.1f}px at {2:.1f}' print(msg.format(self.ksi0,self.ksi0/pxInAu,self.a)) else: print('Scale height: {0:.2f} au at {1:.2f}'.format(self.ksi0, self.a)) print('Vertical profile index: {0:.2f}'.format(self.gamma)) msg = 'Disc vertical FWHM: {0:.2f} at {1:.2f}' print(msg.format(2.*self.ksi0*np.power(np.log10(2.), 1./self.gamma), self.a)) print('Flaring coefficient: {0:.2f}'.format(self.beta)) print('------------------------------------') print('Properties for numerical integration') print('------------------------------------') print('Requested accuracy {0:.2e}'.format(self.accuracy)) # print('Minimum radius for integration: {0:.2f} au'.format(self.rmin)) print('Maximum radius for integration: {0:.2f} au'.format(self.rmax)) print('Maximum height for integration: {0:.2f} au'.format(self.zmax)) msg = 'Inclination threshold: {0:.2f} degrees' print(msg.format(self.itiltthreshold)) return def density_cylindrical(self, r, costheta, z): """ Returns the particule volume density at r, theta, z """ radial_ratio = r/(self.p/(1-self.e*costheta)) den = (np.power(radial_ratio, -2*self.ain) + np.power(radial_ratio,-2*self.aout)) radial_density_term = np.sqrt(2./den)*self.dens_at_r0 if self.pmin>0: radial_density_term[r/(self.pmin/(1-self.e*costheta)) <= 1]=0 den2 = (self.ksi0*np.power(radial_ratio,self.beta)) vertical_density_term = np.exp(-np.power(np.abs(z)/den2, self.gamma)) return radial_density_term*vertical_density_term def density_cartesian(self, x, y, z): """ Returns the particule volume density at x,y,z, taking into account the offset of the disk """ r = np.sqrt(x**2+y**2) if r == 0: costheta=0 else: costheta = x/r return self.density_cylindrical(r,costheta,z) if __name__ == '__main__': """ Main of the class for debugging """ test = DustEllipticalDistribution2PowerLaws() test.set_radial_density(ain=5., aout=-5., a=60., e=0.) test.print_info() costheta = 0. z = 0. for a in np.linspace(60-5,60+5,11): t = test.density_cylindrical(a, costheta, z) print('r={0:.1f} density={1:.4f}'.format(a, t))
Rita Booth , Company and Director Search. This is perfect timing so that the 55 duos registered to date, as well as two tandems with wild card status—Mitch and Rita Booth and Enrique Figueroa and Ruben Booth—to get their bearings out on the water before moving on to the more serious task at hand. ... performer in the 1880s, trouping with her mother, Rita Booth, a stage actress who believed herself to be the daughter of John Wilkes Booth. Ogarita Booth Henderson was an actress. Her career lasted from to Ogarita was given the name Ogarita Elizabeth Bellows on October 23rd, in Providence, Rhode Island, U.S. Ogarita is also known as Ogarita Wilkes and Rita Booth. South Bund Soft Spinning Material Market: Joyce and Rita Booth See 619 traveller reviews, 207 candid photos, and great deals for Shanghai, China, at TripAdvisor. HONEYBOURNE is staging its first ever village show to launch an exciting fundraising project for a new community centre. ON Thursday 1st October we enjoyed listening to Sue Burn from Batsford Arboretum which is open every day of the year apart from Christmas Day. Google Groups: dog breed stamps-help?? Maureen Rita Booth currently holds the position of a Secretary (RETIRED) in 63 SOUTH TERRACE RESIDENTS LIMITED. She has been a Secretary (RETIRED) of 63 SOUTH TERRACE RESIDENTS LIMITED for 15 years. For more details contact Rita Booth How to book. Use the calendar to find and select a date. Looking below the calendar, choose the start and finish times. Fill out your contact information and function description. Accept the Terms & Conditions. Click the Book Now button. Full-time conductor Mr Scholes and colleague Rita Booth would become customer relations staff. YVONNE Leeming was one housewife who did not complain when her husband brought his work home - her kitchen was on fire and he was driving the fire engine. While visiting the Atlanta’s AmericasMart Gift Show last month, we stopped by the Wine-A-Rita booth. We spoke with Donna Griffin, co-founder of the company, and she introduced us to their latest frozen drink mix: Berry Pom-A-Rita . Free company director information for Pauline Rita Booth including date of birth, company appointments, shareholding, LinkedIn, and contact details. Bretforton Garden Club. Bretforton. Evesham. Worcestershire. WR United Kingdom. Contact name: Rita Booth. Contact .uk. Sailor Classification Group No ISAF Sailor Classification. Classification Expiry Date. PERSONAL INFORMATION. GENERAL INTEREST. IMAGES. RESULTS. HONEYBOURNE'S first ever village show attracted more than 600 visitors and has raised £2,700 for a new community centre. surname and all names starting with the letter R.
from __future__ import absolute_import from unittest import TestCase import os import importlib import inspect from plotly.basedatatypes import BasePlotlyType, BaseFigure datatypes_root = "plotly/graph_objs" datatype_modules = [ dirpath.replace("/", ".") for dirpath, _, _ in os.walk(datatypes_root) if not dirpath.endswith("__pycache__") ] class HierarchyTest(TestCase): def test_construct_datatypes(self): for datatypes_module in datatype_modules: module = importlib.import_module(datatypes_module) for name in getattr(module, "__all__", []): if name.startswith("_") or name[0].islower() or name == "FigureWidget": continue obj = getattr(module, name) try: v = obj() except Exception: print( "Failed to construct {obj} in module {module}".format( obj=obj, module=datatypes_module ) ) raise if obj.__module__ == "plotly.graph_objs._deprecations": self.assertTrue(isinstance(v, list) or isinstance(v, dict)) obj() elif name in ("Figure", "FigureWidget"): self.assertIsInstance(v, BaseFigure) else: self.assertIsInstance(v, BasePlotlyType)
What are my spousal benefits? If I was married for 10 years or more, and now divorced, can I claim on my ex-spouses Social Security history? Will they know? What if I want to keep working? What if I've already applied? How much will my benefit be? How can I coordinate spousal benefits? What's the best long-term strategy for my situation? For more information on What's New with Social Security, please click here. If you have interest simply click here to schedule a meeting with me. I will run any of these you would like. Thank for your interest. Michael J. MacDonald is a Registered Investment Advisor offering Advisory Services through Michael MacDonald Financial Management.
# # Copyright 2013 Geodelic # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # import logging logger = logging.getLogger(__name__) import psutil from psutil._pslinux import wrap_exceptions from arke.collect import Collect class ExProcess(psutil.Process): @property def _process_name(self): return self._platform_impl._process_name @property @wrap_exceptions def oom_score(self): with open('/proc/%i/oom_score' % self.pid, 'r') as f: return int(f.readline().strip()) class system(Collect): default_config = {'interval': 30, } def collect(self): return dict( cpu_times=psutil.cpu_times()._asdict(), mem=dict( total_phymem=psutil.TOTAL_PHYMEM, avail_phymem=psutil.avail_phymem(), avail_virtmem=psutil.avail_virtmem(), cached_phymem=psutil.cached_phymem(), phymem_buffers=psutil.phymem_buffers(), total_virtmem=psutil.total_virtmem(), used_phymem=psutil.used_phymem(), used_virtmem=psutil.used_virtmem(), ), processes=list(self._processes()), net=dict( ifaces=self._net_dev(), proto=self._net_proto() ), io=self._io_stats(), fs=dict(self._fs_usage()), fh=self._file_handles(), ) def _processes(self): for pid in psutil.get_pid_list(): try: process = ExProcess(pid) if not process.cmdline: continue yield dict( name=process.name, cmdline=' '.join(process.cmdline), status=str(process.status), ppid=process.ppid, pid=process.pid, cpu_times=process.get_cpu_times()._asdict(), io_counters=process.get_io_counters()._asdict(), memory=process.get_memory_info()._asdict(), oom_score=process.oom_score, num_threads=process.get_num_threads(), connections=[c._asdict() for c in process.get_connections()], open_files=[f.path for f in process.get_open_files()], ) except psutil.NoSuchProcess: continue def _file_handles(self): with open('/proc/sys/fs/file-nr', 'r') as f: o,f,m = map(int, f.readline().split()) return dict( open=o, free=f, max=m ) def _net_proto(self): protocols = {} def _parse(fn): with open(fn, 'r') as f: for line in f: proto, cols = line.split(':') cols = cols.split() nproto, data = f.next().split(':') assert proto == nproto, "the format of %s has changed!" % fn proto_data = dict(zip(cols, map(int, data.split()))) protocols[proto] = proto_data _parse('/proc/net/snmp') _parse('/proc/net/netstat') return protocols def _net_dev(self): ifaces = {} with open('/proc/net/dev', 'r') as f: f.readline() columnLine = f.readline() _, receiveCols , transmitCols = columnLine.split("|") receiveCols = map(lambda a:"recv_"+a, receiveCols.split()) transmitCols = map(lambda a:"trans_"+a, transmitCols.split()) cols = receiveCols+transmitCols for line in f: if ':' not in line: continue iface, stats = line.split(":") ifaceData = map(int, stats.split()) if not any(ifaceData): continue ifaces[iface.strip()] = dict(zip(cols, ifaceData)) return ifaces def _io_stats(self): cols = ('read_count', 'reads_merged', 'read_sectors', 'reading_ms', 'write_count', 'writes_merged', 'write_sectors', 'writing_ms', 'io_run', 'io_rms', 'io_twms') results = {} with open('/proc/diskstats', 'r') as f: for line in f: data = line.split()[2:] disk = data.pop(0) if disk.startswith('ram') or disk.startswith('loop'): continue results[disk] = dict(zip(cols, map(int, data))) return results def _fs_usage(self): for partition in psutil.disk_partitions(): usage = psutil.disk_usage(partition.mountpoint)._asdict() usage['filesystem'] = partition.device yield (partition.mountpoint, usage) if __name__ == '__main__': from pprint import pprint pprint(system(None,None,None,None).collect())
Please note: Club events are meant to bring club members together in a fun and competitive environment. All members are encouraged to participate. Changes may be made to dates and start times, notice will be provided through Club emails and posters in the Main Foyer and Locker Rooms.
# -*- coding: iso-8859-1 -*- """ MoinMoin - User-Agent Statistics This macro creates a pie chart of the type of user agents accessing the wiki. TODO: should be refactored after hitcounts. @copyright: 2002-2004 Juergen Hermann <jh@web.de>, 2007 MoinMoin:ThomasWaldmann @license: GNU GPL, see COPYING for details. """ _debug = 0 from MoinMoin import wikiutil, caching, logfile from MoinMoin.Page import Page from MoinMoin.logfile import eventlog def linkto(pagename, request, params=''): _ = request.getText if not request.cfg.chart_options: return text(pagename, request) if _debug: return draw(pagename, request) page = Page(request, pagename) # Create escaped query string from dict and params querystr = {'action': 'chart', 'type': 'useragents'} querystr = wikiutil.makeQueryString(querystr) querystr = wikiutil.escape(querystr) if params: querystr += '&amp;' + params data = {'url': page.url(request, querystr)} data.update(request.cfg.chart_options) result = ('<img src="%(url)s" width="%(width)d" height="%(height)d"' ' alt="useragents chart">') % data return result def get_data(request): # get results from cache cache = caching.CacheEntry(request, 'charts', 'useragents', scope='wiki', use_pickle=True) cache_date, data = 0, {} if cache.exists(): try: cache_date, data = cache.content() except: cache.remove() # cache gone bad log = eventlog.EventLog(request) try: new_date = log.date() except logfile.LogMissing: new_date = None if new_date is not None: log.set_filter(['VIEWPAGE', 'SAVEPAGE']) for event in log.reverse(): if event[0] <= cache_date: break ua = event[2].get('HTTP_USER_AGENT') if ua: try: pos = ua.index(" (compatible; ") ua = ua[pos:].split(';')[1].strip() except ValueError: ua = ua.split()[0] #ua = ua.replace(';', '\n') data[ua] = data.get(ua, 0) + 1 # write results to cache cache.update((new_date, data)) data = [(cnt, ua) for ua, cnt in data.items()] data.sort() data.reverse() return data def text(pagename, request): from MoinMoin.util.dataset import TupleDataset, Column from MoinMoin.widget.browser import DataBrowserWidget _ = request.getText data = get_data(request) total = 0.0 for cnt, ua in data: total += cnt agents = TupleDataset() agents.columns = [Column('agent', label=_("User agent"), align='left'), Column('value', label='%', align='right')] cnt_printed = 0 data = data[:10] if total: for cnt, ua in data: try: ua = unicode(ua) agents.addRow((ua, "%.2f" % (100.0 * cnt / total))) cnt_printed += cnt except UnicodeError: pass if total > cnt_printed: agents.addRow((_('Others'), "%.2f" % (100 * (total - cnt_printed) / total))) table = DataBrowserWidget(request) table.setData(agents) return table.render(method="GET") def draw(pagename, request): import shutil, cStringIO from MoinMoin.stats.chart import Chart, ChartData, Color _ = request.getText style = Chart.GDC_3DPIE # get data colors = ['red', 'mediumblue', 'yellow', 'deeppink', 'aquamarine', 'purple', 'beige', 'blue', 'forestgreen', 'orange', 'cyan', 'fuchsia', 'lime'] colors = ([Color(c) for c in colors]) data = get_data(request) maxdata = len(colors) - 1 if len(data) > maxdata: others = [x[0] for x in data[maxdata:]] data = data[:maxdata] + [(sum(others), _('Others').encode('iso-8859-1', 'replace'))] # gdchart can't do utf-8 # shift front to end if others is very small if data[-1][0] * 10 < data[0][0]: data = data[1:] + data[0:1] labels = [x[1] for x in data] data = [x[0] for x in data] # give us a chance to develop this if _debug: return "<p>data = %s</p>" % \ '<br>'.join([wikiutil.escape(repr(x)) for x in [labels, data]]) # create image image = cStringIO.StringIO() c = Chart() c.addData(data) title = '' if request.cfg.sitename: title = "%s: " % request.cfg.sitename title = title + _('Distribution of User-Agent Types') c.option( pie_color=colors, label_font=Chart.GDC_SMALL, label_line=1, label_dist=20, threed_depth=20, threed_angle=225, percent_labels=Chart.GDCPIE_PCT_RIGHT, title_font=c.GDC_GIANT, title=title.encode('iso-8859-1', 'replace')) # gdchart can't do utf-8 labels = [label.encode('iso-8859-1', 'replace') for label in labels] c.draw(style, (request.cfg.chart_options['width'], request.cfg.chart_options['height']), image, labels) request.content_type = 'image/gif' request.content_length = len(image.getvalue()) # copy the image image.reset() shutil.copyfileobj(image, request, 8192)
This move in ready home is located in a quiet neighborhood with no through streets. Open concept with many upgrades including stainless steel gas stove, dishwasher & microwave. Heating system includes humidifier, central air, hot tub. Everything you need is on main floor including laundry room with LG washer & dryer included. Master bedroom with walk-in closet & en-suite with dual sinks. Refinished hardwoods in kitchen, upgraded carpet throughout. Spacious 3 car garage for vehicles or toys.
#!/usr/bin/env python # $Id: $ # # FILE: test_mobusmaster.py -- # AUTHOR: Jiri Barton <jbar@swac.cz> # DATE: 14 June 2005 # # Copyright (c) 2001-2005 S.W.A.C. GmbH, Germany. # All Rights Reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import sys import time from modlib import * def server(): c = ModbusServerContext( coils_address=1, coils_count=3, discrete_inputs_address=0, discrete_inputs_count=16, holding_registers_address=17, holding_registers_count=2, input_registers_address=0, input_registers_count=8) s = ModbusTCPServer(context=c, port=10502) try: s.serve_forever() except KeyboardInterrupt: print "Ctrl+C pressed - exiting..." s.server_close() def client(): cn = TCPMasterConnection('127.0.0.1', 10502) try: c = 0 while True: #print the address space of the server for req in [ReadCoilsRequest(address=1, count=3), ReadDiscreteInputsRequest(address=0, count=16), ReadHoldingRegistersRequest(address=17, count=2), ReadInputRegistersRequest(address=0, count=8)]: name = req.__class__.__name__[4:-7].lower() tr = cn.createTransaction(req) res = tr.execute() print ' %s:' % name, if isinstance(res, ExceptionResponse): print 'exception, %d' % res.exception_code, else: if 'registers' in name: print res.registers, else: print [[0, 1][i] for i in res.bits], print time.sleep(1) #flash with a coil req = WriteSingleCoilRequest(address=3, value=bool(c%2)) tr = cn.createTransaction(req) res = tr.execute() #display the number in a holding register req = WriteSingleRegisterRequest(address=17, value=c) tr = cn.createTransaction(req) res = tr.execute() c += 1 except KeyboardInterrupt: print "Ctrl+C pressed - exiting..." cn.close() if __name__ == '__main__': if len(sys.argv) < 2 or sys.argv[1] in ['--server', '-s']: print 'Starting the ModbusTCP server...' server() elif sys.argv[1] in ['--client', '-c']: print 'Starting the ModbusTCP client...' client() else: print 'usage: %s [--server|-s|--client|-c]' % sys.argv[0] # vim: set et ts=4 sw=4 tw=76 si: # $Id: $
The solution, says Boud, is for builders to lower costs by shifting to factory-built homes they can offer at far lower prices. Homebuilders should also work with the banks to offer interest-only mortgages that would hold down monthly payments in the early years, and allow far more millennials to qualify for credit. He also notes that developers need to take steps to lower homeowner association dues that can add $200 to a family’s monthly payments. More 2,000-square-foot houses would also be welcome, but for that to happen, municipalities would need to loosen zoning laws to allow far more lots to be subdivided, far more quickly. Today, towns are trending the wrong way, towards even tighter restrictions. This article was written by Shawn Tully from FORTUNE and was legally licensed by AdvisorStream through the NewsCred publisher network.
from tqdm import tqdm_notebook from .tqdm_callback import TQDMCallback import sys class TQDMNotebookCallback(TQDMCallback): def __init__(self, outer_description="Training", inner_description_initial="Epoch {epoch}", inner_description_update="[{metrics}] ", metric_format="{name}: {value:0.3f}", separator=", ", leave_inner=False, leave_outer=True, output_file=sys.stderr, **kwargs): super(TQDMNotebookCallback, self).__init__(outer_description=outer_description, inner_description_initial=inner_description_initial, inner_description_update=inner_description_update, metric_format=metric_format, separator=separator, leave_inner=leave_inner, leave_outer=leave_outer, output_file=output_file, **kwargs) def tqdm(self, desc, total, leave): """ Extension point. Override to provide custom options to tqdm_notebook initializer. :param desc: Description string :param total: Total number of updates :param leave: Leave progress bar when done :return: new progress bar """ return tqdm_notebook(desc=desc, total=total, leave=leave)
A new series of Doctor Who is here and I have begun reviewing the episodes over at GeekNerdery. You can check out my dual review of "The Pilot"/"Smile" and the recent review that just went live today of "Thin Ice". I also appear as a guest on this week's episode of Podcastica, talking with the hosts John and Tayler about "Thin Ice"and other general Who ramblings. How are you enjoying this series of Who so far? Welcome to the official website of writer Lauren Gallo. This is the official site for Lauren Gallo, author of speculative fiction and fanciful tales.
from twisted.python import usage from ConfigParser import ConfigParser from AZTKServer import AZTKServer import Image, ImageFile, sys, errors, validation, pprint, md5, time, socket, zsp_packets from twisted.internet.protocol import Factory from twisted.internet.app import Application from twisted.internet import defer, reactor from twisted.protocols import basic from twisted.protocols import policies from cStringIO import StringIO from display_sizes import display_sizes import traceback class ZSP(basic.LineReceiver, policies.TimeoutMixin): """ Connection Protocol """ TIMEOUT = 60 #seconds def connectionMade(self): """ This is called once per instance when a client has connected to us. It sets up the timeout for this connection, and defines the available commands @return: Nothing @rtype: Nothing """ # get current version information for Zulu client self.major = int(self.factory.app.servers.zspserver._cfg_version_major) self.minor = int(self.factory.app.servers.zspserver._cfg_version_minor) self.build = int(self.factory.app.servers.zspserver._cfg_version_build) self.tag = str(self.factory.app.servers.zspserver._cfg_version_tag) self.storing = False # get a local reference to the ZSP server's log instance self.log = self.factory.log self.bin = { "buffer": StringIO(), "bytes_in_buffer": 0, "bytes_wanted": 3, } self.action_list = [] self.setTimeout(self.TIMEOUT) self.header = zsp_packets.zsp_header() remote = self.transport.getPeer() self.log.debug("got a connection from %s:%s [%s]" % (remote.host, remote.port, remote.type)) self.setRawMode() ##remote_server = self.transport.getPeer() ## self.factory.app.servers.zspserver.log.info("Received a connection from %s. Authenticating..." % remote_server[1]) self.die = False # they are in good standing so far, if we determine not to talk to them (True) kill connection self.sync_list = [] # a list of approved files (from FLAG requests) self.file = {} # a dict with info for the file ready to be received or currently receiving (from FILE requests) def connectionLost(self, reason="not sure"): """ This is called once per connection, when the socket has closed (for any reason) @param reason: reason for disconnection @type reason: String @return: Nothing @rtype: Nothing """ self.setTimeout(None) ## self.factory.app.servers.zspserver.log.info("Lost Connection: %s" % reason.getErrorMessage()) try: self.log.debug("Lost Connection: %s" % reason.getErrorMessage()) except: self.log.debug("Lost Connection: %s" % reason) def timeoutConnection(self): """ Called when the client times out for some reason @return: Nothing @rtype: Nothing """ self.setTimeout(None) self.factory.app.servers.zspserver.log.info("Client Timed out. Later, sucker.") def send(self, string): """ Simple method for sending a string to the client. It tacks on the line terminator for you. @param string: the message to send to the client @type string: string @return: Nothing @rtype: Nothing """ self.transport.write(str(string)) def rawDataReceived(self, data): """ This is used after the protocol mode has been switched from Line to Raw. L{do_FILE()} switches the mode to raw. This mode does not trim line terminators from the incoming data Data is stacked up here, until the buffer reaches the size limit defined for this file in the ITEM and FILE requests. Once the buffer hits its limit, this method will call L{do_DONE()} and reset the protocol to line mode @param data: raw data @type: String @return: Nothing @rtype: Nothing """ self.resetTimeout() if self.die: self.transport.loseConnection("TEST") return if len(self.file.keys()) > 0: # we have a file to receive... if self.file["bytes_received"] >= self.file["filesize"]: # we have the whole file, let the normal buffer get the next request # should be a DONE packet... pass else: if len(data) + self.file["bytes_received"] > self.file["filesize"]: # we got too much data, roll the buffer back a bit remainder = self.file["filesize"] - self.file["bytes_received"] assert remainder > 0 partial_packet = data[0:remainder] data = data[remainder:] self.file["bytes_received"] += len(partial_packet) self.file["buffer"].write(partial_packet) else: self.file["bytes_received"] += len(data) self.file["buffer"].write(data) return self.bin["buffer"].write(data) self.bin["bytes_in_buffer"] = len(self.bin["buffer"].getvalue()) if self.bin["bytes_in_buffer"] >= self.bin["bytes_wanted"]: try: self.header.parse(self.bin["buffer"].getvalue()) except Exception, ex: # if for any reason this doesn't work the client is sending crap # cut them off and close connection self.transport.loseConnection('OUT OF SYNC') return self.bin["bytes_wanted"] = self.header.length if self.bin["bytes_in_buffer"] >= self.header.length: d = False if self.header.type == zsp_packets.ZSP_AUTH: d = self.do_AUTH() elif self.header.type == zsp_packets.ZSP_VERSION: d = self.do_VERSION() elif self.header.type == zsp_packets.ZSP_FLAG: d = self.do_FLAG() elif self.header.type == zsp_packets.ZSP_FILE: d = self.do_FILE() elif self.header.type == zsp_packets.ZSP_DONE: d = self.do_DONE() else: error = zsp_packets.zsp_error() error.error_code = 500 error.error_string = "Unknown Packet Request" self.send(error.build()) self.transport.loseConnection() # send the response if d: d.addCallback(self.send) def do_HEARTBEAT(self): """ Sends a heartbeat packet to the client, maintaining the connection. """ if self.storing: self.log.debug("sending a heartbeat packet to the client") packet = zsp_packets.zsp_heartbeat() self.send(packet.build()) self.factory.app.reactor.callLater(2, self.do_HEARTBEAT) def do_AUTH(self): """ Checks to see if a user is authorized @return: response object @rtype: response object """ packet = zsp_packets.zsp_auth() resp = zsp_packets.zsp_auth_resp() error = zsp_packets.zsp_error() # buffer now contains any leftover data buffer = packet.parse(self.bin["buffer"].getvalue()) self.bin["buffer"] = StringIO() self.bin["buffer"].write(buffer) self.bin["bytes_wanted"] = 3 # really auth the user here... def handle_user_id(result): if result[0] != 0: resp.return_code = zsp_packets.ZSP_AUTH_BAD resp.response = "USERNAME OR PASSWORD INVALID" self.die = True self.userid = result[1] d_user = self.factory.app.api.users.get_info(self.userid, self.userid) d_user.addCallback(print_user) return d_user def print_user(result): if result[0] != 0: resp.return_code = zsp_packets.ZSP_AUTH_BAD resp.response = "USERNAME OR PASSWORD INVALID" self.die = True if not result[1]: resp.return_code = zsp_packets.ZSP_AUTH_BAD resp.response = "USERNAME OR PASSWORD INVALID" self.die = True self.user_info = result[1] if self.user_info['password'] == packet.pswd_hash: self.log.debug("user authed as %s" % packet.user_name) self.username = packet.user_name resp.return_code = zsp_packets.ZSP_AUTH_OK resp.response = "USER OK" else: self.log.debug("couldn't auth %s" % (packet.username)) resp.return_code = zsp_packets.ZSP_AUTH_BAD resp.response = "USERNAME OR PASSWORD INVALID" self.die = True def bad_auth(reason): self.log.debug("bad auth maybe a not found? %s" % reason) error.error_code = 500 error.error_string = "INTERNAL SERVER ERROR" self.die = True return error.build() db_d = self.factory.app.api.users.get_user_id(packet.user_name) db_d.addCallback(handle_user_id) db_d.addErrback(bad_auth) db_d.addCallback(lambda _: resp.build()) return db_d def do_VERSION(self): """ Checks the version of the client @return: response @rtype: (deferred) response object """ packet = zsp_packets.zsp_version() resp = zsp_packets.zsp_version_resp() # buffer now contains any leftover data buffer = packet.parse(self.bin["buffer"].getvalue()) self.bin["buffer"] = StringIO() self.bin["buffer"].write(buffer) self.bin["bytes_wanted"] = 3 client_version = "%s.%s.%s" % (packet.vers_maj, packet.vers_min, packet.vers_build) if self.factory.app.servers.zspserver.cfg.has_option("versions", client_version): response = self.factory.app.servers.zspserver.cfg.getint("versions", client_version) else: response = 0 if response == 410: # they're ok resp.return_code = zsp_packets.ZSP_VERS_GOOD resp.comment = "VERSION OK [%s]" % socket.gethostname() elif response == 415: # newer version is available, but still ok resp.return_code = zsp_packets.ZSP_VERS_OLD resp.comment = "%s.%s.%s %s" % (self.major, self.minor, self.build, self.tag) elif response == 420: # obsolete, forced update resp.return_code = zsp_packets.ZSP_VERS_BAD resp.comment = "%s.%s.%s %s" % (self.major, self.minor, self.build, self.tag) self.die = True elif response == 425: # obsolete, show error dialog (no auto-update) resp.return_code = zsp_packets.ZSP_VERS_FUBAR resp.comment = "%s.%s.%s %s" % (self.major, self.minor, self.build, self.tag) self.die = True elif response == -1: # drop connection self.log.debug("unknown version") self.transport.loseConnection("") self.die = True return None else: self.factory.app.log.warning("client version %s tried to connect, but isn't in the config file" % client_version) self.log.warning("someone connected with version %s which isn't in the config file" % client_version) # drop connection self.transport.loseConnection("") self.die = True return None d = defer.Deferred() d.addCallback(lambda _: resp.build()) d.callback(0) return d def do_FLAG(self): """ foo """ packet = zsp_packets.zsp_flag() resp = zsp_packets.zsp_flag_resp() error = zsp_packets.zsp_error() # buffer now contains any leftover data buffer = packet.parse(self.bin["buffer"].getvalue()) self.bin["buffer"] = StringIO() self.bin["buffer"].write(buffer) self.bin["bytes_wanted"] = 3 try: checksum = packet.image_id filesize = packet.image_size filetype = packet.image_format filename = packet.image_name filedate = packet.image_date except: # we couldn't get the right info from the packet... error.error_code = 314 error.error_string = "Malformed FLAG request" if error.error_code: d = defer.Deferred() d.addCallback(lambda _: error.build()) d.callback(0) return d else: resp.image_id = checksum self.sync_list.append(checksum) d_flags = self.factory.app.api.images.image_exists(checksum) def check_exists(exists): if exists: self.log.debug("Image [%s] already uploaded" % checksum) resp.image_needed = 0 self.storing = True self.do_HEARTBEAT() d_set = self.factory.app.api.images.set_user_image(self.userid, checksum, filename, 'ZULU Client', '', '') d_set.addCallback(check_set_success) return d_set else: resp.image_needed = 1 def check_set_success(result): self.storing = False if result[0] != 0: raise Exception(result[1]) d_flags.addCallback(check_exists) d_flags.addCallback(lambda _: resp.build()) return d_flags def do_FILE(self): """ foo """ packet = zsp_packets.zsp_file() resp = zsp_packets.zsp_file_resp() # buffer now contains any leftover data buffer = packet.parse(self.bin["buffer"].getvalue()) self.bin["buffer"] = StringIO() self.bin["buffer"].write(buffer) self.bin["bytes_wanted"] = 3 error = zsp_packets.zsp_error() try: image_id = packet.image_id filetype = packet.image_format filesize = packet.image_size filedate = packet.image_date filename = packet.image_name except: # we couldn't get the right info from the packet... error.error_code = zsp_packets.ZSP_FILE_BAD error.error_string = "Malformed FILE request" if image_id not in self.sync_list: error.error_code = zsp_packets.ZSP_FILE_NO_FLAG error.error_string = "image %s was not approved via FLAG request" % image_id # setup a struct for the incoming file self.file = { "image_id": image_id, "buffer": StringIO(), "filename": filename, "filedate": filedate, "filesize": filesize, "bytes_received": 0, } #pprint.pprint(self.file) d = defer.Deferred() if error.error_code: d.addCallback(lambda _: error.build()) else: resp.return_code = zsp_packets.ZSP_FILE_OK resp.image_id = image_id resp.return_string = "FILE OK" d.addCallback(lambda _: resp.build()) d.callback(0) return d def do_DONE(self): """ DONT FORGET TO CLEAR self.sync_list and self.files! @return: Unknown @rtype: Unknown """ packet = zsp_packets.zsp_done() resp = zsp_packets.zsp_done_resp() # buffer now contains any leftover data buffer = packet.parse(self.bin["buffer"].getvalue()) binary = self.file['buffer'] binary.seek(0) self.bin["buffer"] = StringIO() self.bin["buffer"].write(buffer) self.bin["bytes_wanted"] = 3 error = zsp_packets.zsp_error() checksum = md5.md5(binary.getvalue()).hexdigest() if checksum != self.file["image_id"]: error.error_code = zsp_packets.ZSP_DONE_BAD_SUM error.error_string = "CHECKSUM MISMATCH" try: parser = ImageFile.Parser() parser.feed(binary.getvalue()) img = parser.close() except IOError, e: self.factory.app.servers.zspserver.log.critical("Image couldn't be parsed %s" % e) error.error_code = zsp_packets.ZSP_DONE_BAD_SYNC error.error_string = "FILE OUT OF SYNC" try: img.verify() except: self.factory.app.servers.zspserver.log.critical("Decoded Image is corrupted") error.error_code = zsp_packets.ZSP_DONE_BAD_SYNC2 error.error_string = "FILE OUT OF SYNC" try: image = Image.open(binary) except (TypeError, IOError, ValueError): self.log.warning("Image can't be loaded: %s [%d bytes]" % (checksum, len(binary.getvalue()))) error.error_code = zsp_packets.ZSP_DONE_CORRUPT error.error_string = "UNSUPPORTED/CORRUPT FILE" try: exif = validation.exifdata(image._getexif()) except: exif = {} if not exif: exif = {} if exif: has_exif = 1 else: has_exif = 0 if error.error_code: d = defer.Deferred() d.callback(error.build()) return d def worked(result): if result[0] == 0: self.log.debug("Successfully stored image") resp.return_code = zsp_packets.ZSP_DONE_OK resp.return_string = "FILE SYNCHRONIZED OK" self.sync_list.remove(self.file["image_id"]) self.file = {} self.storing = False return resp.build() else: raise Exception(result[1]) def failed(failure): stack = failure.value self.log.warning("file not inserted: %s %s\n%s" % (stack.exception, stack.message, stack.trace())) resp.return_code = zsp_packets.ZSP_DONE_BAD_WRITE #resp.return_string = "FILE ALREADY EXISTS ON SERVER" resp.return_string = failure.getErrorMessage() # dont remove from the sync list incase they want to retry self.file = {} return error.build() self.storing = True self.do_HEARTBEAT() d_insert = self.factory.app.api.images.add( self.userid, self.file["filename"], binary.getvalue(), \ 'ZULU Client', '', '') d_insert.addCallback(worked) d_insert.addErrback(failed) return d_insert def do_QUIT(self): """ The client calls this command when they are exiting. As a courtesy, tell the client goodbye. @return: Nothing @rtype: Nothing """ d.callback("190 GOODBYE") self.transport.loseConnection() class ZSPFactory(Factory): protocol = ZSP def __init__(self, application, log): """ Start the factory with out given protocol @param application: our reference to the running app (so we can use the DB and API) @type application: L{Application} @param log: a reference to the ZSP server's log instance @type log: L{Logger} instance (see lib/aztk_main.py) @return: Nothing @rtype: Nothing """ self.app = application self.log = log class ZSPServer(AZTKServer): enable_broker = False enable_node = True def start(self): """ Starts L{ZSPFactory}, reactor and configuration """ self.cfg = ConfigParser() #TODO: NO HARDCODED PATHS! self.cfg.read("/zoto/aztk/etc/uploader_versions.cfg") factory = ZSPFactory(self.app, self.log) ip = self.app.cfg_setup.get("interfaces", self.app.host) self.app.reactor.listenTCP(int(self._cfg_port), factory, interface=ip)
This week The Western Producer takes a look at the scary prospect of African swine fever being found in Canada. “I go to these meetings all the time and we only talk about the bad stuff, how bad things could be. It tends to be a very negative discussion,” Ross said in late March, after a day of meetings in the United States with American pork producers. Canada may have an excellent system but it’s difficult for pork producers to relax right now. There are no vaccines or treatments for ASF, a viral disease that causes fever, internal bleeding and high death rates in swine. It has been spreading in China and Eastern Europe and is now in Vietnam. Jack Shere, chief veterinary officer for the U.S. Department of Agriculture, believes it will soon be present in all of Southeast Asia. Other experts are convinced it will eventually move into Germany and most of Western Europe. The priority for the Canadian Food Inspection Agency and the pork council is keeping it out of Canada. But pork industry representatives and veterinarians are also discussing what would happen if ASF arrived, how to respond and how it would affect pork exports. “It’s a far more of a serious issue for us than the rest of the world,” said Ted Bilyea, who worked for Maple Leaf Foods for 34 years. Estimating the impact of something before it happens is nearly impossible. However, there’s a fear that a positive case of ASF could prompt foreign buyers to stop importing pork from Canada. Canada has an agreement with the U.S., and is working on a similar deal with Japan, where it would be possible to have ASF and export pork to those countries. In January 2013 the federal government announced that Canada and the U.S. had signed a deal on animal disease zoning. The agreement recognizes that both countries are capable of dealing with a foreign animal disease outbreak and are able to contain it within a certain region. If an ASF outbreak happened, say in Quebec, the U.S. chief veterinary officer would have the authority to recognize Canada’s disease control measures and zoning and then approve pork imports from parts of Canada that were free from the virus. The agreement has already been used. When avian influenza was detected on North American poultry farms a few years ago, Canada accepted U.S. zoning for the disease and vice-versa. The Canadian government has a similar agreement with the European Union. That’s why Canada continues to import pork from Poland, which has dozens of farms with ASF. If Canada lost faith in Poland’s ability to control the disease, the government could reject imports of Polish pork. For now, Canada continues to recognize zones that are free from ASF in Poland. The U.S. deal is critical because Canada sold $1.25 billion in pork to the U.S. last year. The other big pork market for Canada is Japan, worth $1.27 billion in 2018. An industry source said the federal government is pushing hard for a bilateral zoning deal with Japan, so pork exports could continue if ASF arrived. Even with such agreements in place there’s a chance of political interference, in which a U.S. senator from a pork-producing state or President Donald Trump refused to honour the zoning deal. But science, evidence and strong relationships between the decision makers on both sides of the border should make a difference, Ross said. A USDA official said in an email that the chief veterinarians would likely be the decision makers. If ASF is found in Canada in an area with a high concentration of hog barns, managing an outbreak would be trickier. “Do I have it in a hog-dense area or an area that’s very isolated? Did I find it in the first week or had it for a month?” Ross said.
import Image, glob, ImageChops, ImageMath, ImageEnhance files = glob.glob("arrow_*_4.png") def incrange(start, stop, step): if step > 0: return range(start, stop+1, step) else: return range(start, stop-1, step) def channelMap(f, image): return Image.merge(image.mode, [f(chan) for chan in image.split()]) #pun not intended class NotBrokenRGBA: """ grrr PIL. """ def __init__(self, size): self.white = Image.new("RGB", size, (255,255,255)) self.black = Image.new("RGB", size, (0,0,0)) def paste(self, *args): self.white.paste(*args) self.black.paste(*args) def pasteRGBA(self, pasta, location): self.paste(pasta, location, pasta) def create(self): mask = ImageChops.subtract(self.white, self.black, -1, 255) maskgray = mask.convert("L") #out = self.black.convert("RGBA") # this doesn't premultiply alpha correctly? #this better? def divide(ch): env = {"val": ch, "mask": maskgray} return ImageMath.eval("val*255/mask",env).convert("L") out = channelMap(divide, self.black).convert("RGBA") out.putalpha(maskgray) return out def save(self, *args): self.create().save(*args) for filename in files: filesuffix = filename.replace("arrow","",1) im = Image.open(filename) im_alpha = (im.copy().split())[-1] im_bright = ImageEnhance.Brightness(im).enhance(2) im_dark = ImageEnhance.Brightness(im).enhance(.5) im_weak = ImageEnhance.Color(im_dark).enhance(.2) im_bright.putalpha(im_alpha) im_weak.putalpha(im_alpha) im_dark.putalpha(im_alpha) im_middle = im_weak # depends on active/inactive? (imw, imh) = im.size skippix = 4 # should be factor of imh (typically 64) holdtypes = {"_active": im_bright, "_inactive": im_dark, "_dead": im_weak} for im_middle_name, im_middle in holdtypes.iteritems(): # stepmania has bottomcap, but we're scrolling the other direction htopcap = NotBrokenRGBA((imw, imh)) #Image.new("RGBA", (imw, imh)) hbody = NotBrokenRGBA((imw, 2*imh)) # Image.new("RGB", (imw, 2*imh)) for y in incrange(imh*2, 0, -skippix): htopcap.pasteRGBA(im if y==0 else im_middle, (0, y)) for y in incrange(imh*4, -imh*4, -skippix): hbody.pasteRGBA(im_middle, (0, y)) hbody.save("hbody" + im_middle_name + filesuffix, "PNG") htopcap.save("htopcap" + im_middle_name + filesuffix, "PNG")
106 apartments with a view. Delft Hoog is offering 106 turnkey rental apartments. From private studios to full-service apartments, each room has its distinctive style, and suitable for every budget.
# -*- coding: iso-8859-1 -*- # Copyright (C) 2000-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Store and retrieve country names for IPs. """ from . import _ConnectionPlugin import os import sys import socket from ..lock import get_lock from ..decorators import synchronized from ..strformat import unicode_safe from .. import log, LOG_PLUGIN class LocationInfo(_ConnectionPlugin): """Adds the country and if possible city name of the URL host as info. Needs GeoIP or pygeoip and a local country or city lookup DB installed.""" def __init__(self, config): """Check for geoip module.""" if not geoip: log.warn(LOG_PLUGIN, "GeoIP or pygeoip not found for LocationInfo plugin.") super(LocationInfo, self).__init__(config) def applies_to(self, url_data): """Check for validity, host existence and geoip module.""" return url_data.valid and url_data.host and geoip def check(self, url_data): """Try to ask GeoIP database for country info.""" location = get_location(url_data.host) if location: url_data.add_info(_("URL is located in %(location)s.") % {"location": _(location)}) # It is unknown if the geoip library is already thread-safe, so # no risks should be taken here by using a lock. _lock = get_lock("geoip") def get_geoip_dat (): """Find a GeoIP database, preferring city over country lookup.""" datafiles = ("GeoIPCity.dat", "GeoIP.dat") if os.name == 'nt': paths = (sys.exec_prefix, r"c:\geoip") else: paths = ("/usr/local/share/GeoIP", "/usr/share/GeoIP") for path in paths: for datafile in datafiles: filename = os.path.join(path, datafile) if os.path.isfile(filename): return filename # try importing both the C-library GeoIP and the pure-python pygeoip geoip_dat = get_geoip_dat() geoip = None if geoip_dat: try: import GeoIP geoip = GeoIP.open(geoip_dat, GeoIP.GEOIP_STANDARD) geoip_error = GeoIP.error except ImportError: try: import pygeoip geoip = pygeoip.GeoIP(geoip_dat) geoip_error = pygeoip.GeoIPError except ImportError: pass if geoip_dat.endswith('GeoIPCity.dat'): get_geoip_record = lambda host: geoip.record_by_name(host) else: get_geoip_record = lambda host: {'country_name': geoip.country_name_by_name(host)} @synchronized(_lock) def get_location (host): """Get translated country and optional city name. @return: country with optional city or an boolean False if not found """ if geoip is None: # no geoip available return None try: record = get_geoip_record(host) except (geoip_error, socket.error): log.debug(LOG_PLUGIN, "Geoip error for %r", host, exception=True) # ignore lookup errors return None value = u"" if record and record.get("city"): value += unicode_safe(record["city"]) if record and record.get("country_name"): if value: value += u", " value += unicode_safe(record["country_name"]) return value
Colin Fan, a Managing Director at Deutsche Bank, is the firm's Head of Global Credit Trading and Head of Emerging Markets Debt Trading. In both roles he serves as the global head of the respective product groups. Fan is also a member of the Global Markets Executive Committee. Previously, he was the head of all Asian equities products and businesses for Deutsche Bank, based in Hong Kong. Prior to assuming that role, he was the global head of convertibles trading and co-head of structured credit trading, based in New York. He joined Deutsche Bank as a credit trader in 1998 after working for UBS and Merrill Lynch. Fan holds a bachelor's degree in history and science from Harvard University.
from xlrd import open_workbook from person import Person from bill import Bill from datetime import date, timedelta billWorkbook = open_workbook('../bills.xls') def readPeople(sheet, columns, rows): people = [] for column in range(columns): values = [] for row in range(rows): values.append(sheet.cell(row,column).value) if values[0] == 'Name': print 'Ignoring column...' continue people += [Person(values[0])] return people def readBills(sheet, columns, rows): bills = [] for column in range(columns): values = [] for row in range(rows): values.append(sheet.cell(row,column).value) if values[0] == 'Name': print 'Ignoring column...' continue bills += [Bill(values[0],values[1],values[2],values[3],values[4],values[5])] return bills def calculateMonthlyExpenses(bills, people): monthBillStarts = [ bill.start.month for bill in bills] monthBillEnds = [ bill.end.month for bill in bills] monthsWithBills = [ (str(month),MonthlyExpense(month)) for month in monthBillStarts] if monthBillEnds[-1] not in monthBillStarts: monthsWithBills += [monthBillEnds[-1]] monthlyExpenses = dict(monthsWithBills) for bill in bills: monthlyExpenses[str(bill.start.month)] = MonthlyExpense(bill.start) def calculateDebts(bills, people): for sheet in billWorkbook.sheets(): sheetColumns = sheet.ncols sheetRows = sheet.nrows print 'Sheet: ',sheet.name print ' with ' + str(sheetRows) + ' rows and ' + str(sheetColumns) + ' columns' if sheet.name == 'Bills': the_bills = readBills(sheet, sheetColumns, sheetRows) elif sheet.name == 'People': the_people = readPeople() debts = calculateDebts(the_bills, the_people) print debts
ORDERS: This weekend, flirt with an artist. You don’t need to end in bed with him or her. Just, you know, taste God. In their work, in their eyes.
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Document' db.create_table('mmm_document', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('url', self.gf('django.db.models.fields.URLField')(unique=True, max_length=200)), ('title', self.gf('django.db.models.fields.CharField')(max_length=2000)), ('publication_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('author_names', self.gf('django.db.models.fields.CharField')(max_length=500, blank=True)), )) db.send_create_signal('mmm', ['Document']) # Adding M2M table for field req_committee on 'Document' db.create_table('mmm_document_req_committee', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('document', models.ForeignKey(orm['mmm.document'], null=False)), ('committee', models.ForeignKey(orm['committees.committee'], null=False)) )) db.create_unique('mmm_document_req_committee', ['document_id', 'committee_id']) # Adding M2M table for field req_mks on 'Document' db.create_table('mmm_document_req_mks', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('document', models.ForeignKey(orm['mmm.document'], null=False)), ('member', models.ForeignKey(orm['mks.member'], null=False)) )) db.create_unique('mmm_document_req_mks', ['document_id', 'member_id']) def backwards(self, orm): # Deleting model 'Document' db.delete_table('mmm_document') # Removing M2M table for field req_committee on 'Document' db.delete_table('mmm_document_req_committee') # Removing M2M table for field req_mks on 'Document' db.delete_table('mmm_document_req_mks') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'committees.committee': { 'Meta': {'object_name': 'Committee'}, 'aliases': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'chairpersons': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'chaired_committees'", 'blank': 'True', 'to': "orm['mks.Member']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'committees'", 'blank': 'True', 'to': "orm['mks.Member']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'portal_knesset_broadcasts_url': ('django.db.models.fields.URLField', [], {'max_length': '1000', 'blank': 'True'}), 'replacements': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'replacing_in_committees'", 'blank': 'True', 'to': "orm['mks.Member']"}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'events.event': { 'Meta': {'object_name': 'Event'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'what': ('django.db.models.fields.TextField', [], {}), 'when': ('django.db.models.fields.DateTimeField', [], {}), 'when_over': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'when_over_guessed': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'where': ('django.db.models.fields.TextField', [], {}), 'which_pk': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'which_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'event_for_event'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'who': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['persons.Person']", 'symmetrical': 'False'}) }, 'mks.member': { 'Meta': {'ordering': "['name']", 'object_name': 'Member'}, 'area_of_residence': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'average_monthly_committee_presence': ('django.db.models.fields.FloatField', [], {'null': 'True'}), 'average_weekly_presence_hours': ('django.db.models.fields.FloatField', [], {'null': 'True'}), 'backlinks_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'bills_stats_approved': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'bills_stats_first': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'bills_stats_pre': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'bills_stats_proposed': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'blog': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['planet.Blog']", 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'current_party': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'members'", 'null': 'True', 'to': "orm['mks.Party']"}), 'current_role_descriptions': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True', 'blank': 'True'}), 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_of_death': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'family_status': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'gender': ('django.db.models.fields.CharField', [], {'max_length': '1', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'img_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'is_current': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'number_of_children': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'parties': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'all_members'", 'symmetrical': 'False', 'through': "orm['mks.Membership']", 'to': "orm['mks.Party']"}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'place_of_birth': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'place_of_residence': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'place_of_residence_lat': ('django.db.models.fields.CharField', [], {'max_length': '16', 'null': 'True', 'blank': 'True'}), 'place_of_residence_lon': ('django.db.models.fields.CharField', [], {'max_length': '16', 'null': 'True', 'blank': 'True'}), 'residence_centrality': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'residence_economy': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'year_of_aliyah': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'mks.membership': { 'Meta': {'object_name': 'Membership'}, 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'member': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['mks.Member']"}), 'party': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['mks.Party']"}), 'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}) }, 'mks.party': { 'Meta': {'ordering': "('-number_of_seats',)", 'object_name': 'Party'}, 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_coalition': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'number_of_members': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'number_of_seats': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}) }, 'mmm.document': { 'Meta': {'object_name': 'Document'}, 'author_names': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'publication_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'req_committee': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'mmm_documents'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['committees.Committee']"}), 'req_mks': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'mmm_documents'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['mks.Member']"}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '2000'}), 'url': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '200'}) }, 'persons.person': { 'Meta': {'ordering': "('name',)", 'object_name': 'Person'}, 'area_of_residence': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_of_death': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'family_status': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'gender': ('django.db.models.fields.CharField', [], {'max_length': '1', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'img_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'mk': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'person'", 'null': 'True', 'to': "orm['mks.Member']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'number_of_children': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'place_of_birth': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'place_of_residence': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'place_of_residence_lat': ('django.db.models.fields.CharField', [], {'max_length': '16', 'null': 'True', 'blank': 'True'}), 'place_of_residence_lon': ('django.db.models.fields.CharField', [], {'max_length': '16', 'null': 'True', 'blank': 'True'}), 'residence_centrality': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'residence_economy': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'titles': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'persons'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['persons.Title']"}), 'year_of_aliyah': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'persons.title': { 'Meta': {'object_name': 'Title'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, 'planet.blog': { 'Meta': {'ordering': "('title', 'url')", 'object_name': 'Blog'}, 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '1024', 'db_index': 'True'}) } } complete_apps = ['mmm']
A key protection from mercury, arsenic and other toxic emissions is under attack. On Dec. 27, the U.S. Environmental Protection Agency (EPA) released its proposal to weaken the Mercury and Air Toxics Standards (MATS), which protect the public by limiting emissions of mercury, arsenic and other toxic substances from coal- and oil-burning power plants. Mercury emitted from power plants settles in nearby lakes and rivers, rendering their fish unsafe to eat. While not repealing the MATS rule outright, the EPA’s proposal would chip away at its legal foundations and make it harder to regulate hazardous emissions.
# A Magento 2 module generator library # Copyright (C) 2016 Maikel Martens # # This file is part of Mage2Gen. # # Mage2Gen is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os, locale from collections import OrderedDict from .. import Module, Phpclass, Phpmethod, Xmlnode, StaticFile, Snippet, SnippetParam, Readme from ..utils import upperfirst, lowerfirst from ..module import TEMPLATE_DIR # Long boring code to add a lot of PHP classes and xml, only go here if you feel like too bring you happiness down. # Or make your day happy that you don't maintain this code :) class InterfaceClass(Phpclass): template_file = os.path.join(TEMPLATE_DIR,'interface.tmpl') class InterfaceMethod(Phpmethod): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.template_file = os.path.join(TEMPLATE_DIR,'interfacemethod.tmpl') class ModelSnippet(Snippet): description = """ Model is used to create a easie CRUD interface to the database - **Model ame:** The name of the model, the table name wil be <module_name>_<model_name>. - **Field name:** The name of the database table field. - **Field type:** The type of database field. - **Adminhtml grid:** Add this field to the adminhtml grid layout **Model ID field**: The snippet will auto add the model id field to the database table, the field name is <model_name>_id. """ FIELD_TYPE_CHOISES = [ ('boolean','Boolean'), ('smallint','Smallint'), ('integer','Integer'), ('bigint', 'Bigint'), ('float', 'Float'), ('numeric', 'Numeric'), ('decimal', 'Decimal'), ('date', 'Date'), ('timestamp', 'Timestamp'), ('datetime', 'Datetime'), ('text', 'Text'), ('blob', 'Blob'), ('varchar','Varchar') ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.count = 0 def add(self, model_name, field_name, field_type='text', adminhtml_grid=False, adminhtml_form=False,web_api=False, extra_params=False): self.count += 1 extra_params = extra_params if extra_params else {} model_table = '{}_{}_{}'.format(self._module.package.lower(), self._module.name.lower(), model_name.lower()) model_id = '{}_id'.format(model_name.lower()) field_element_type = 'input' split_field_name = field_name.split('_') field_name_capitalized = ''.join(upperfirst(item) for item in split_field_name) split_model_name = model_name.split('_') model_name_capitalized = ''.join(upperfirst(item) for item in split_model_name) model_name_capitalized_after = model_name_capitalized[0].lower() + model_name_capitalized[1:] split_model_id = model_id.split('_') model_id_capitalized = ''.join(upperfirst(item) for item in split_model_id) model_id_capitalized_after = model_id_capitalized[0].lower() + model_id_capitalized[1:] collection_model_class_name = "\\{}\\{}\\Model\\ResourceModel\\{}\\Collection".format(self._module.package, self._module.name, model_name_capitalized.replace('_', '\\') ) extension_interface_class_name = "\\{}\\{}\\Api\\Data\\{}ExtensionInterface".format(self._module.package, self._module.name, model_name_capitalized.replace('_', '\\') ) if field_type == 'boolean': field_element_type = 'checkbox' elif field_type == 'date' or field_type == 'timestamp': field_element_type = 'date' elif field_type == 'text': field_element_type = 'textarea' top_level_menu = extra_params.get('top_level_menu', True) column_nodes = [] # add model id field column_nodes.append(Xmlnode('column', attributes={ 'xsi:type': "{}".format('smallint'), 'name': "{}".format(model_id), 'padding': "{}".format('6'), 'unsigned': "{}".format('true'), 'nullable': "{}".format('false'), 'identity': "{}".format('true'), 'comment': "{}".format('Entity Id') })) # create options required = False attributes = { 'name': "{}".format(field_name), 'nullable': "true", 'xsi:type': field_type } if field_type == 'integer' or field_type == 'bigint': attributes['xsi:type'] = "int" elif field_type == 'numeric': attributes['xsi:type'] = "real" if extra_params.get('default'): attributes['default'] = "{}".format(extra_params.get('default')) if not extra_params.get('nullable'): attributes['nullable'] = 'false' required = not attributes['nullable'] if field_type in {'mallint','integer','bigint'}: attributes['identity'] = 'false' if extra_params.get('identity'): attributes['identity'] = 'true' if extra_params.get('unsigned'): attributes['unsigned'] = 'true' if extra_params.get('precision'): attributes['precision'] = extra_params.get('precision') if extra_params.get('scale'): attributes['scale'] = extra_params.get('scale') if extra_params.get('field_size'): attributes['length'] = '{}'.format(extra_params.get('field_size')) elif field_type == 'decimal': attributes['scale'] = '4' attributes['precision'] = '12' elif field_type == 'varchar' and not extra_params.get('field_size'): attributes['length'] = '255' # Create db_schema.xml declaration self.add_xml('etc/db_schema.xml', Xmlnode('schema', attributes={ 'xsi:noNamespaceSchemaLocation': "urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"}, nodes=[ Xmlnode('table', attributes={ 'name': "{}".format(model_table), 'resource': "default", 'engine': "innodb", 'comment': "{} Table".format(model_table) }, nodes=[ Xmlnode('column', attributes={ 'xsi:type': "{}".format('smallint'), 'name': "{}".format(model_id), 'padding': "{}".format('6'), 'unsigned': "{}".format('true'), 'nullable': "{}".format('false'), 'identity': "{}".format('true'), 'comment': "{}".format('Entity Id') }), Xmlnode('constraint', attributes={ 'xsi:type': "primary", 'referenceId': "PRIMARY".format(model_id) }, nodes=[ Xmlnode('column', attributes={ 'name': "{}".format(model_id) }) ]), Xmlnode('column', attributes=attributes) ]) ])) # Create resource class resource_model_class = Phpclass('Model\\ResourceModel\\' + model_name_capitalized.replace('_', '\\'), extends='\\Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb') resource_model_class.add_method(Phpmethod('_construct', access=Phpmethod.PROTECTED, body="$this->_init('{}', '{}');".format(model_table, model_id), docstring=[ 'Define resource model', '', '@return void', ])) self.add_class(resource_model_class) # Create api data interface class api_data_class = InterfaceClass('Api\\Data\\' + model_name_capitalized.replace('_', '\\') + 'Interface', extends='\\Magento\\Framework\\Api\\ExtensibleDataInterface', attributes=[ "const {} = '{}';".format(field_name.upper(),field_name),"const {} = '{}';".format(model_id.upper(),model_id) ]) api_data_class.add_method(InterfaceMethod('get'+model_id_capitalized,docstring=['Get {}'.format(model_id),'@return {}'.format('string|null')])) self.add_class(api_data_class) api_data_class.add_method(InterfaceMethod('set'+model_id_capitalized,params=['${}'.format(model_id_capitalized_after)],docstring=['Set {}'.format(model_id),'@param string ${}'.format(model_id_capitalized_after),'@return \{}'.format(api_data_class.class_namespace)])) self.add_class(api_data_class) api_data_class.add_method(InterfaceMethod('get'+field_name_capitalized,docstring=['Get {}'.format(field_name),'@return {}'.format('string|null')])) self.add_class(api_data_class) api_data_class.add_method(InterfaceMethod('set'+field_name_capitalized,params=['${}'.format(lowerfirst(field_name_capitalized))],docstring=['Set {}'.format(field_name),'@param string ${}'.format(lowerfirst(field_name_capitalized)),'@return \{}'.format(api_data_class.class_namespace)])) self.add_class(api_data_class) api_data_class.add_method(InterfaceMethod('getExtensionAttributes', docstring=['Retrieve existing extension attributes object or create a new one.','@return ' + extension_interface_class_name + '|null'])) api_data_class.add_method(InterfaceMethod('setExtensionAttributes', params=[extension_interface_class_name + ' $extensionAttributes'], docstring=['Set an extension attributes object.','@param ' + extension_interface_class_name +' $extensionAttributes','@return $this'])) self.add_class(api_data_class) # Create api data interface class api_data_search_class = InterfaceClass('Api\\Data\\' + model_name_capitalized.replace('_', '\\') + 'SearchResultsInterface',extends='\Magento\Framework\Api\SearchResultsInterface') api_data_search_class.add_method(InterfaceMethod('getItems',docstring=['Get {} list.'.format(model_name),'@return \{}[]'.format(api_data_class.class_namespace)])) api_data_search_class.add_method(InterfaceMethod('setItems',params=['array $items'],docstring=['Set {} list.'.format(field_name),'@param \{}[] $items'.format(api_data_class.class_namespace),'@return $this'])) self.add_class(api_data_search_class) # Create api data interface class api_repository_class = InterfaceClass('Api\\' + model_name_capitalized.replace('_', '\\') + 'RepositoryInterface',dependencies=['Magento\Framework\Api\SearchCriteriaInterface']) api_repository_class.add_method(InterfaceMethod('save',params=['\{} ${}'.format(api_data_class.class_namespace,model_name_capitalized_after)],docstring=['Save {}'.format(model_name),'@param \{} ${}'.format(api_data_class.class_namespace,model_name_capitalized_after),'@return \{}'.format(api_data_class.class_namespace),'@throws \Magento\Framework\Exception\LocalizedException'])) api_repository_class.add_method(InterfaceMethod('get',params=['${}'.format(model_id_capitalized_after)],docstring=['Retrieve {}'.format(model_name),'@param string ${}'.format(model_id_capitalized_after),'@return \{}'.format(api_data_class.class_namespace),'@throws \Magento\Framework\Exception\LocalizedException'])) api_repository_class.add_method(InterfaceMethod('getList',params= ['\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria'], docstring=['Retrieve {} matching the specified criteria.'.format(model_name),'@param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria','@return \{}'.format(api_data_search_class.class_namespace),'@throws \Magento\Framework\Exception\LocalizedException'])) api_repository_class.add_method(InterfaceMethod('delete',params=['\{} ${}'.format(api_data_class.class_namespace,model_name_capitalized_after)],docstring=['Delete {}'.format(model_name),'@param \{} ${}'.format(api_data_class.class_namespace,model_name_capitalized_after),'@return bool true on success','@throws \Magento\Framework\Exception\LocalizedException'])) api_repository_class.add_method(InterfaceMethod('deleteById',params=['${}'.format(model_id_capitalized_after)],docstring=['Delete {} by ID'.format(model_name),'@param string ${}'.format(model_id_capitalized_after),'@return bool true on success','@throws \\Magento\\Framework\\Exception\\NoSuchEntityException','@throws \\Magento\\Framework\\Exception\\LocalizedException'])) self.add_class(api_repository_class) # Create model class model_class = Phpclass('Model\\' + model_name_capitalized.replace('_', '\\'), dependencies=[ api_data_class.class_namespace, api_data_class.class_namespace + 'Factory', 'Magento\\Framework\\Api\\DataObjectHelper', ], extends='\\Magento\\Framework\\Model\\AbstractModel', attributes=[ 'protected ${}DataFactory;\n'.format(model_name.lower()), 'protected $dataObjectHelper;\n', 'protected $_eventPrefix = \'{}\';'.format(model_table) ]) model_class.add_method(Phpmethod('__construct', access=Phpmethod.PUBLIC, params=[ "\Magento\Framework\Model\Context $context", "\Magento\Framework\Registry $registry", "{}InterfaceFactory ${}DataFactory".format(model_name_capitalized, model_name.lower()), "DataObjectHelper $dataObjectHelper", "\\" + resource_model_class.class_namespace + " $resource", collection_model_class_name + " $resourceCollection", "array $data = []", ], body="""$this->{variable}DataFactory = ${variable}DataFactory; $this->dataObjectHelper = $dataObjectHelper; parent::__construct($context, $registry, $resource, $resourceCollection, $data); """.format(variable=model_name.lower()), docstring=[ "@param \Magento\Framework\Model\Context $context", "@param \Magento\Framework\Registry $registry", "@param {}InterfaceFactory ${}DataFactory".format(model_name_capitalized, model_name.lower()), "@param DataObjectHelper $dataObjectHelper", "@param \\" + resource_model_class.class_namespace + " $resource", "@param " + collection_model_class_name + " $resourceCollection", "@param array $data", ] )) model_class.add_method(Phpmethod('getDataModel', access=Phpmethod.PUBLIC, body="""${variable}Data = $this->getData(); ${variable}DataObject = $this->{variable}DataFactory->create(); $this->dataObjectHelper->populateWithArray( ${variable}DataObject, ${variable}Data, {variable_upper}Interface::class ); return ${variable}DataObject; """.format(variable=model_name.lower(), variable_upper=model_name_capitalized), docstring=[ "Retrieve {} model with {} data".format(model_name.lower(), model_name.lower()), "@return {}Interface".format(model_name_capitalized), ] )) self.add_class(model_class) # Create collection collection_model_class = Phpclass('Model\\ResourceModel\\' + model_name_capitalized.replace('_', '\\') + '\\Collection', extends='\\Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection', attributes=[ "/**\n\t * @var string\n\t */\n\tprotected $_idFieldName = '{}';".format(model_id), ]) collection_model_class.add_method(Phpmethod('_construct', access=Phpmethod.PROTECTED, body="$this->_init(\n \{}::class,\n \{}::class\n);".format( model_class.class_namespace ,resource_model_class.class_namespace), docstring=[ 'Define resource model', '', '@return void', ])) self.add_class(collection_model_class) # Create Repository Class model_repository_class = Phpclass('Model\\' + model_name_capitalized.replace('_', '\\') + 'Repository', dependencies=[ api_repository_class.class_namespace, api_data_search_class.class_namespace + 'Factory', api_data_class.class_namespace + 'Factory', 'Magento\\Framework\\Api\\DataObjectHelper', 'Magento\\Framework\\Exception\\CouldNotDeleteException', 'Magento\\Framework\\Exception\\NoSuchEntityException', 'Magento\\Framework\\Exception\\CouldNotSaveException', 'Magento\\Framework\\Reflection\\DataObjectProcessor', 'Magento\\Framework\\Api\\SearchCriteria\\CollectionProcessorInterface', resource_model_class.class_namespace + ' as Resource' + model_name_capitalized, collection_model_class.class_namespace + 'Factory as '+ model_name_capitalized +'CollectionFactory', 'Magento\\Store\\Model\\StoreManagerInterface', 'Magento\\Framework\\Api\\ExtensionAttribute\\JoinProcessorInterface', 'Magento\\Framework\\Api\\ExtensibleDataObjectConverter' ], attributes=[ 'protected $resource;\n', 'protected ${}Factory;\n'.format(model_name_capitalized_after), 'protected ${}CollectionFactory;\n'.format(model_name_capitalized_after), 'protected $searchResultsFactory;\n', 'protected $dataObjectHelper;\n', 'protected $dataObjectProcessor;\n', 'protected $data{}Factory;\n'.format(model_name_capitalized), 'protected $extensionAttributesJoinProcessor;\n', 'private $storeManager;\n', 'private $collectionProcessor;\n', 'protected $extensibleDataObjectConverter;' ], implements=[model_name_capitalized.replace('_', '\\') + 'RepositoryInterface'] ) model_repository_class.add_method(Phpmethod('__construct', access=Phpmethod.PUBLIC, params=[ "Resource{} $resource".format(model_name_capitalized), "{}Factory ${}Factory".format(model_name_capitalized,model_name_capitalized_after), "{}InterfaceFactory $data{}Factory".format(model_name_capitalized,model_name_capitalized), "{}CollectionFactory ${}CollectionFactory".format(model_name_capitalized,model_name_capitalized_after), "{}SearchResultsInterfaceFactory $searchResultsFactory".format(model_name_capitalized), "DataObjectHelper $dataObjectHelper", "DataObjectProcessor $dataObjectProcessor", "StoreManagerInterface $storeManager", "CollectionProcessorInterface $collectionProcessor", "JoinProcessorInterface $extensionAttributesJoinProcessor", "ExtensibleDataObjectConverter $extensibleDataObjectConverter" ], body="""$this->resource = $resource; $this->{variable}Factory = ${variable}Factory; $this->{variable}CollectionFactory = ${variable}CollectionFactory; $this->searchResultsFactory = $searchResultsFactory; $this->dataObjectHelper = $dataObjectHelper; $this->data{variable_upper}Factory = $data{variable_upper}Factory; $this->dataObjectProcessor = $dataObjectProcessor; $this->storeManager = $storeManager; $this->collectionProcessor = $collectionProcessor; $this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor; $this->extensibleDataObjectConverter = $extensibleDataObjectConverter; """.format(variable=model_name_capitalized_after,variable_upper=model_name_capitalized), docstring=[ "@param Resource{} $resource".format(model_name_capitalized), "@param {}Factory ${}Factory".format(model_name_capitalized,model_name_capitalized_after), "@param {}InterfaceFactory $data{}Factory".format(model_name_capitalized,model_name_capitalized), "@param {}CollectionFactory ${}CollectionFactory".format(model_name_capitalized,model_name_capitalized_after), "@param {}SearchResultsInterfaceFactory $searchResultsFactory".format(model_name_capitalized), "@param DataObjectHelper $dataObjectHelper", "@param DataObjectProcessor $dataObjectProcessor", "@param StoreManagerInterface $storeManager", "@param CollectionProcessorInterface $collectionProcessor", "@param JoinProcessorInterface $extensionAttributesJoinProcessor", "@param ExtensibleDataObjectConverter $extensibleDataObjectConverter", ] )) model_repository_class.add_method(Phpmethod('save', access=Phpmethod.PUBLIC, params=['\\' + api_data_class.class_namespace + ' $' + model_name_capitalized_after], body="""/* if (empty(${variable}->getStoreId())) {{ $storeId = $this->storeManager->getStore()->getId(); ${variable}->setStoreId($storeId); }} */ ${variable}Data = $this->extensibleDataObjectConverter->toNestedArray( ${variable}, [], \{data_interface}::class ); ${variable}Model = $this->{variable}Factory->create()->setData(${variable}Data); try {{ $this->resource->save(${variable}Model); }} catch (\Exception $exception) {{ throw new CouldNotSaveException(__( 'Could not save the {variable}: %1', $exception->getMessage() )); }} return ${variable}Model->getDataModel(); """.format(data_interface=api_data_class.class_namespace, variable=model_name_capitalized_after), docstring=['{@inheritdoc}'] )) model_repository_class.add_method(Phpmethod('get', access=Phpmethod.PUBLIC, params=['${}Id'.format(model_name_capitalized_after)], body="""${variable} = $this->{variable}Factory->create(); $this->resource->load(${variable}, ${variable}Id); if (!${variable}->getId()) {{ throw new NoSuchEntityException(__('{model_name} with id "%1" does not exist.', ${variable}Id)); }} return ${variable}->getDataModel(); """.format(variable=model_name_capitalized_after,model_name=model_name), docstring=['{@inheritdoc}'] )) model_repository_class.add_method(Phpmethod('getList', access=Phpmethod.PUBLIC, params=['\Magento\Framework\Api\SearchCriteriaInterface $criteria'], body="""$collection = $this->{variable}CollectionFactory->create(); $this->extensionAttributesJoinProcessor->process( $collection, \{data_interface}::class ); $this->collectionProcessor->process($criteria, $collection); $searchResults = $this->searchResultsFactory->create(); $searchResults->setSearchCriteria($criteria); $items = []; foreach ($collection as $model) {{ $items[] = $model->getDataModel(); }} $searchResults->setItems($items); $searchResults->setTotalCount($collection->getSize()); return $searchResults; """.format(variable=model_name_capitalized_after,data_interface=api_data_class.class_namespace,variable_upper=model_name_capitalized), docstring=['{@inheritdoc}'] )) model_repository_class.add_method(Phpmethod('delete', access=Phpmethod.PUBLIC, params=['\{} ${}'.format(api_data_class.class_namespace,model_name_capitalized_after)], body="""try {{ ${variable}Model = $this->{variable}Factory->create(); $this->resource->load(${variable}Model, ${variable}->get{model_id}()); $this->resource->delete(${variable}Model); }} catch (\Exception $exception) {{ throw new CouldNotDeleteException(__( 'Could not delete the {model_name}: %1', $exception->getMessage() )); }} return true; """.format(variable=model_name_capitalized_after,model_name=model_name,model_id=model_id_capitalized), docstring=['{@inheritdoc}'] )) model_repository_class.add_method(Phpmethod('deleteById', access=Phpmethod.PUBLIC, params=['${}Id'.format(model_name_capitalized_after)], body="""return $this->delete($this->get(${variable}Id)); """.format(variable=model_name_capitalized_after,model_name=model_name), docstring=['{@inheritdoc}'] )) self.add_class(model_repository_class) # Create Data Model Class data_model_class = Phpclass('Model\\Data\\' + model_name_capitalized.replace('_', '\\'), dependencies=[api_data_class.class_namespace], extends='\\Magento\\Framework\\Api\\AbstractExtensibleObject', implements=[ api_data_class.class_name ]) data_model_class.add_method(Phpmethod('get' + model_id_capitalized, docstring=['Get {}'.format(model_id),'@return {}'.format('string|null')], body="""return $this->_get({}); """.format('self::'+model_id.upper()), )) data_model_class.add_method(Phpmethod('set' + model_id_capitalized, params=['${}'.format(model_id_capitalized_after)], docstring=['Set {}'.format(model_id),'@param string ${}'.format(model_id_capitalized_after),'@return \{}'.format(api_data_class.class_namespace)], body="""return $this->setData({}, ${}); """.format('self::' + model_id.upper(), model_id_capitalized_after) )) data_model_class.add_method(Phpmethod('get' + field_name_capitalized, docstring=['Get {}'.format(field_name),'@return {}'.format('string|null')], body="""return $this->_get({}); """.format('self::' + field_name.upper()), )) data_model_class.add_method(Phpmethod('set' + field_name_capitalized, params=['${}'.format(lowerfirst(field_name_capitalized))], docstring=['Set {}'.format(field_name),'@param string ${}'.format(lowerfirst(field_name_capitalized)),'@return \{}'.format(api_data_class.class_namespace)], body="""return $this->setData({}, ${}); """.format('self::' + field_name.upper(), lowerfirst(field_name_capitalized)) )) data_model_class.add_method(Phpmethod('getExtensionAttributes', docstring=['Retrieve existing extension attributes object or create a new one.','@return '+ extension_interface_class_name +'|null'], body="""return $this->_getExtensionAttributes(); """ )) data_model_class.add_method(Phpmethod('setExtensionAttributes', params=[extension_interface_class_name + ' $extensionAttributes'], docstring=['Set an extension attributes object.','@param ' + extension_interface_class_name +' $extensionAttributes','@return $this'], body="""return $this->_setExtensionAttributes($extensionAttributes); """ )) self.add_class(data_model_class) # Create di.xml preferences self.add_xml('etc/di.xml', Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:framework:ObjectManager/etc/config.xsd"}, nodes=[ Xmlnode('preference', attributes={ 'for': "{}\\{}\\Api\\{}RepositoryInterface".format(self._module.package, self._module.name, model_name_capitalized), 'type': model_repository_class.class_namespace }), Xmlnode('preference', attributes={ 'for': "{}\\{}\\Api\\Data\\{}Interface".format(self._module.package, self._module.name, model_name_capitalized), 'type': "{}\\{}\\Model\\Data\\{}".format(self._module.package, self._module.name, model_name_capitalized) }), Xmlnode('preference', attributes={ 'for': "{}\\{}\\Api\\Data\\{}SearchResultsInterface".format(self._module.package, self._module.name, model_name_capitalized), 'type': 'Magento\Framework\Api\SearchResults' }) ])) # add grid if adminhtml_grid: self.add_adminhtml_grid(model_name, field_name, model_table, model_id, collection_model_class, field_element_type, top_level_menu, adminhtml_form) if adminhtml_form: self.add_adminhtml_form(model_name, field_name, model_table, model_id, collection_model_class, model_class, required, field_element_type) self.add_acl(model_name) if web_api: self.add_web_api(model_name, field_name, model_table, model_id, collection_model_class, model_class, required, field_element_type, api_repository_class, model_id_capitalized_after) if web_api | adminhtml_form | adminhtml_grid: self.add_acl(model_name) def add_adminhtml_grid(self, model_name, field_name, model_table, model_id, collection_model_class, field_element_type, top_level_menu, adminhtml_form): frontname = self.module_name.lower() data_source_id = '{}_listing_data_source'.format(model_table) # create controller index_controller_class = Phpclass('Controller\\Adminhtml\\' + model_name.replace('_', '') + '\\Index', extends='\\Magento\\Backend\\App\\Action', attributes=[ 'protected $resultPageFactory;' ]) index_controller_class.add_method(Phpmethod('__construct', params=['\\Magento\\Backend\\App\\Action\\Context $context', '\\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory'], body='$this->resultPageFactory = $resultPageFactory;\nparent::__construct($context);', docstring=[ 'Constructor', '', '@param \\Magento\\Backend\\App\\Action\\Context $context', '@param \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory', ])) index_controller_class.add_method(Phpmethod('execute', body_return=""" $resultPage = $this->resultPageFactory->create(); $resultPage->getConfig()->getTitle()->prepend(__("{model_name}")); return $resultPage; """.format(model_name=model_name), docstring=[ 'Index action', '', '@return \Magento\Framework\Controller\ResultInterface', ])) self.add_class(index_controller_class) # create menu.xml top_level_menu_node = False if top_level_menu: top_level_menu_node = Xmlnode('add', attributes={ 'id': "{}::top_level".format(self._module.package), 'title': self._module.package, 'module': self.module_name, 'sortOrder': 9999, 'resource': 'Magento_Backend::content', }) self.add_xml('etc/adminhtml/menu.xml', Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:module:Magento_Backend:etc/menu.xsd"}, nodes=[ Xmlnode('menu', nodes=[ top_level_menu_node, Xmlnode('add', attributes={ 'id': "{}::{}".format(self.module_name, model_table), 'title': model_name.replace('_', ' '), 'module': self.module_name, 'sortOrder': 9999, 'resource': 'Magento_Backend::content', 'parent': '{}::top_level'.format(self._module.package), 'action': '{}/{}/index'.format(frontname, model_name.lower().replace('_', '')) }) ]) ])) # Create routes.xml self.add_xml('etc/adminhtml/routes.xml', Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation': 'urn:magento:framework:App/etc/routes.xsd'}, nodes=[ Xmlnode('router', attributes={'id': 'admin'}, nodes=[ Xmlnode('route', attributes={'frontName': frontname, 'id':frontname}, nodes=[ Xmlnode('module', attributes={'before': 'Magento_Backend', 'name': self.module_name}) ]) ]) ])) # di.xml self.add_xml('etc/di.xml', Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:framework:ObjectManager/etc/config.xsd"}, nodes=[ Xmlnode('virtualType', attributes={ 'name': collection_model_class.class_namespace.replace('Collection', 'Grid\\Collection'), 'type': 'Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult', }, nodes=[ Xmlnode('arguments', nodes=[ Xmlnode('argument', attributes={'name': 'mainTable', 'xsi:type': 'string'}, node_text=model_table), Xmlnode('argument', attributes={'name': 'resourceModel', 'xsi:type': 'string'}, node_text= collection_model_class.class_namespace), ]) ]), Xmlnode('type', attributes={'name': 'Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\CollectionFactory'}, nodes=[ Xmlnode('arguments', nodes=[ Xmlnode('argument', attributes={'name': 'collections', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': data_source_id, 'xsi:type': 'string'}, node_text=collection_model_class.class_namespace.replace('Collection', 'Grid\\Collection')) ]) ]) ]) ])) # create layout.xml self.add_xml('view/adminhtml/layout/{}_{}_index.xml'.format(frontname, model_name.replace('_', '').lower()), Xmlnode('page', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:framework:View/Layout/etc/page_configuration.xsd"}, nodes=[ Xmlnode('update', attributes={'handle': 'styles'}), Xmlnode('body', nodes=[ Xmlnode('referenceContainer', attributes={'name': 'content'}, nodes=[ Xmlnode('uiComponent', attributes={'name': '{}_listing'.format(model_table)}) ]) ]) ])) # create components.xml data_source_xml = Xmlnode('dataSource', attributes={'name': data_source_id, 'component': 'Magento_Ui/js/grid/provider'}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('updateUrl', attributes={'path': 'mui/index/render'}) ]), Xmlnode('aclResource', node_text='{}_{}::{}'.format(self._module.package, self._module.name, model_name)), Xmlnode('dataProvider', attributes={'name': data_source_id,'class': 'Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\DataProvider'}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('requestFieldName', node_text='id'), Xmlnode('primaryFieldName', node_text=model_id) ]) ]) ]) if adminhtml_form: columns_settings_xml = Xmlnode('settings', nodes=[ Xmlnode('editorConfig', nodes=[ Xmlnode('param', attributes={'name': 'selectProvider', 'xsi:type': 'string'}, node_text='{0}_listing.{0}_listing.{0}_columns.ids'.format(model_table)), Xmlnode('param', attributes={'name': 'enabled', 'xsi:type': 'boolean'}, node_text='true'), Xmlnode('param', attributes={'name': 'indexField', 'xsi:type': 'string'}, node_text=model_id), Xmlnode('param', attributes={'name': 'clientConfig', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'saveUrl', 'xsi:type': 'url', 'path': '{}/{}/inlineEdit'.format(frontname, model_name.replace('_', ''))}), Xmlnode('item', attributes={'name': 'validateBeforeSave', 'xsi:type': 'boolean'}, node_text='false'), ]), ]), Xmlnode('childDefaults', nodes=[ Xmlnode('param', attributes={'name': 'fieldAction', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'provider', 'xsi:type': 'string'}, node_text='{0}_listing.{0}_listing.{0}_columns_editor'.format(model_table)), Xmlnode('item', attributes={'name': 'target', 'xsi:type': 'string'}, node_text='startEdit'), Xmlnode('item', attributes={'name': 'params', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': '0', 'xsi:type': 'string'}, node_text='${ $.$data.rowIndex }'), Xmlnode('item', attributes={'name': '1', 'xsi:type': 'boolean'}, node_text='true'), ]), ]), ]), ]) columns_xml = Xmlnode('columns', attributes={'name': '{}_columns'.format(model_table)}, nodes=[ Xmlnode('selectionsColumn', attributes={'name': 'ids'}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('indexField', node_text=model_id) ]), ]), Xmlnode('column', attributes={'name': model_id}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('filter', node_text='text'), Xmlnode('sorting', node_text='asc'), Xmlnode('label', attributes={'translate': 'true'}, node_text='ID') ]) ]), Xmlnode('column', attributes={'name': field_name}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('filter', node_text='text'), Xmlnode('label', attributes={'translate': 'true'}, node_text=field_name) ]) ]) ]) if adminhtml_form: columns_xml = Xmlnode('columns', attributes={'name': '{}_columns'.format(model_table)}, nodes=[ columns_settings_xml, Xmlnode('selectionsColumn', attributes={'name': 'ids'}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('indexField', node_text=model_id) ]), ]), Xmlnode('column', attributes={'name': model_id}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('filter', node_text='text'), Xmlnode('sorting', node_text='asc'), Xmlnode('label', attributes={'translate': 'true'}, node_text='ID') ]) ]), Xmlnode('column', attributes={'name': field_name}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('filter', node_text='text'), Xmlnode('label', attributes={'translate': 'true'}, node_text=field_name) ]) ]) ]) self.add_xml('view/adminhtml/ui_component/{}_listing.xml'.format(model_table), Xmlnode('listing', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"}, nodes=[ Xmlnode('argument', attributes={'name': 'data', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'js_config', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'provider', 'xsi:type': 'string'}, node_text='{}_listing.{}'.format(model_table, data_source_id)), ]), ]), Xmlnode('settings', nodes=[ Xmlnode('spinner', node_text='{}_columns'.format(model_table)), Xmlnode('deps', nodes=[ Xmlnode('dep',node_text='{}_listing.{}'.format(model_table, data_source_id)) ]) ]), data_source_xml, Xmlnode('listingToolbar', attributes={'name': 'listing_top'}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('sticky', node_text='true'), ]), Xmlnode('bookmark', attributes={'name': 'bookmarks'}), Xmlnode('columnsControls', attributes={'name': 'columns_controls'}), Xmlnode('filters', attributes={'name': 'listing_filters'}), Xmlnode('paging', attributes={'name': 'listing_paging'}) ]), columns_xml ])) def add_adminhtml_form(self, model_name, field_name, model_table, model_id, collection_model_class, model_class, required, field_element_type): frontname = self.module_name.lower() # Add block buttons # Back button back_button = Phpclass('Block\\Adminhtml\\' + model_name.replace('_', '\\') + '\\Edit\\BackButton', implements=['ButtonProviderInterface'], extends='GenericButton', dependencies=['Magento\\Framework\\View\\Element\\UiComponent\\Control\\ButtonProviderInterface']) back_button.add_method(Phpmethod('getButtonData', body="""return [ 'label' => __('Back'), 'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()), 'class' => 'back', 'sort_order' => 10 ];""", docstring=['@return array'])) back_button.add_method(Phpmethod('getBackUrl', body="""return $this->getUrl('*/*/');""", docstring=[ 'Get URL for back (reset) button', '', '@return string' ])) self.add_class(back_button) # Delete button delete_button = Phpclass('Block\\Adminhtml\\' + model_name.replace('_', '\\') + '\\Edit\\DeleteButton', implements=['ButtonProviderInterface'], extends='GenericButton', dependencies=['Magento\\Framework\\View\\Element\\UiComponent\\Control\\ButtonProviderInterface']) delete_button.add_method(Phpmethod('getButtonData', body="""$data = []; if ($this->getModelId()) {{ $data = [ 'label' => __('Delete {}'), 'class' => 'delete', 'on_click' => 'deleteConfirm(\\'' . __( 'Are you sure you want to do this?' ) . '\\', \\'' . $this->getDeleteUrl() . '\\')', 'sort_order' => 20, ]; }} return $data;""".format(model_name.replace('_', ' ').title()), docstring=['@return array'])) delete_button.add_method(Phpmethod('getDeleteUrl', body="""return $this->getUrl('*/*/delete', ['{}' => $this->getModelId()]);""".format(model_id), docstring=[ 'Get URL for delete button', '', '@return string' ])) self.add_class(delete_button) # Generic button generic_button = Phpclass('Block\\Adminhtml\\' + model_name.replace('_', '\\') + '\\Edit\\GenericButton', dependencies=['Magento\\Backend\\Block\Widget\\Context'], attributes=[ 'protected $context;' ], abstract=True) generic_button.add_method(Phpmethod('__construct', params=['Context $context'], body="""$this->context = $context;""", docstring=['@param \\Magento\\Backend\\Block\Widget\\Context $context'])) generic_button.add_method(Phpmethod('getModelId', body="""return $this->context->getRequest()->getParam('{}');""".format(model_id), docstring=[ 'Return model ID', '', '@return int|null' ])) generic_button.add_method(Phpmethod('getUrl', params=["$route = ''","$params = []"], body="""return $this->context->getUrlBuilder()->getUrl($route, $params);""", docstring=[ 'Generate url by route and parameters', '', '@param string $route', '@param array $params', '@return string' ] )) self.add_class(generic_button) # Save and continu button save_continue_button = Phpclass('Block\\Adminhtml\\' + model_name.replace('_', '\\') + '\\Edit\\SaveAndContinueButton', implements=['ButtonProviderInterface'], extends='GenericButton', dependencies=['Magento\\Framework\\View\\Element\\UiComponent\\Control\\ButtonProviderInterface']) save_continue_button.add_method(Phpmethod('getButtonData', body="""return [ 'label' => __('Save and Continue Edit'), 'class' => 'save', 'data_attribute' => [ 'mage-init' => [ 'button' => ['event' => 'saveAndContinueEdit'], ], ], 'sort_order' => 80, ];""", docstring=[ '@return array' ])) self.add_class(save_continue_button) # Save button save_button = Phpclass('Block\\Adminhtml\\' + model_name.replace('_', '\\') + '\\Edit\\SaveButton', implements=['ButtonProviderInterface'], extends='GenericButton', dependencies=['Magento\\Framework\\View\\Element\\UiComponent\\Control\\ButtonProviderInterface']) save_button.add_method(Phpmethod('getButtonData', body="""return [ 'label' => __('Save {}'), 'class' => 'save primary', 'data_attribute' => [ 'mage-init' => ['button' => ['event' => 'save']], 'form-role' => 'save', ], 'sort_order' => 90, ];""".format(model_name.replace('_', ' ').title()), docstring=[ '@return array' ])) self.add_class(save_button) # Add controllers ########################################################################################### register_model = self.module_name.lower() + '_' + model_name.lower() # link controller link_controller = Phpclass('Controller\\Adminhtml\\' + model_name.replace('_', ''), extends='\\Magento\\Backend\\App\\Action', abstract=True, attributes=[ "const ADMIN_RESOURCE = '{}::top_level';".format(self.module_name), 'protected $_coreRegistry;']) link_controller.add_method(Phpmethod('__construct', params=['\\Magento\\Backend\\App\\Action\\Context $context', '\\Magento\\Framework\\Registry $coreRegistry'], body="""$this->_coreRegistry = $coreRegistry;\nparent::__construct($context);""", docstring=[ '@param \\Magento\\Backend\\App\\Action\\Context $context', '@param \\Magento\\Framework\\Registry $coreRegistry' ])) link_controller.add_method(Phpmethod('initPage', params=['$resultPage'], body="""$resultPage->setActiveMenu(self::ADMIN_RESOURCE) ->addBreadcrumb(__('{namespace}'), __('{namespace}')) ->addBreadcrumb(__('{model_name}'), __('{model_name}')); return $resultPage;""".format( namespace = self._module.package, model_name = model_name.replace('_', ' ').title() ), docstring=[ 'Init page', '', '@param \Magento\Backend\Model\View\Result\Page $resultPage', '@return \Magento\Backend\Model\View\Result\Page' ])) self.add_class(link_controller) # Delete controller delete_controller = Phpclass('Controller\\Adminhtml\\' + model_name.replace('_', '') + '\\Delete', extends='\\' + link_controller.class_namespace) delete_controller.add_method(Phpmethod('execute', body="""/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); // check if we know what should be deleted $id = $this->getRequest()->getParam('{model_id}'); if ($id) {{ try {{ // init model and delete $model = $this->_objectManager->create(\{model_class}::class); $model->load($id); $model->delete(); // display success message $this->messageManager->addSuccessMessage(__('You deleted the {model_name}.')); // go to grid return $resultRedirect->setPath('*/*/'); }} catch (\Exception $e) {{ // display error message $this->messageManager->addErrorMessage($e->getMessage()); // go back to edit form return $resultRedirect->setPath('*/*/edit', ['{model_id}' => $id]); }} }} // display error message $this->messageManager->addErrorMessage(__('We can\\\'t find a {model_name} to delete.')); // go to grid return $resultRedirect->setPath('*/*/');""".format( model_id = model_id, model_class = model_class.class_namespace, model_name = model_name.replace('_', ' ').title()), docstring=[ 'Delete action', '', '@return \Magento\Framework\Controller\ResultInterface', ] )) self.add_class(delete_controller) # Edit controller edit_controller = Phpclass('Controller\\Adminhtml\\' + model_name.replace('_', '') + '\\Edit', extends= '\\' + link_controller.class_namespace, attributes=[ 'protected $resultPageFactory;' ]) edit_controller.add_method(Phpmethod('__construct', params=['\\Magento\\Backend\\App\\Action\\Context $context', '\\Magento\\Framework\\Registry $coreRegistry', '\\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory'], body="""$this->resultPageFactory = $resultPageFactory;\nparent::__construct($context, $coreRegistry);""", docstring=[ '@param \\Magento\\Backend\\App\\Action\\Context $context', '@param \\Magento\\Framework\\Registry $coreRegistry', '@param \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory', ])) edit_controller.add_method(Phpmethod('execute', body="""// 1. Get ID and create model $id = $this->getRequest()->getParam('{model_id}'); $model = $this->_objectManager->create(\{model_class}::class); // 2. Initial checking if ($id) {{ $model->load($id); if (!$model->getId()) {{ $this->messageManager->addErrorMessage(__('This {model_name} no longer exists.')); /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); return $resultRedirect->setPath('*/*/'); }} }} $this->_coreRegistry->register('{register_model}', $model); // 3. Build edit form /** @var \Magento\Backend\Model\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $this->initPage($resultPage)->addBreadcrumb( $id ? __('Edit {model_name}') : __('New {model_name}'), $id ? __('Edit {model_name}') : __('New {model_name}') ); $resultPage->getConfig()->getTitle()->prepend(__('{model_name}s')); $resultPage->getConfig()->getTitle()->prepend($model->getId() ? __('Edit {model_name} %1', $model->getId()) : __('New {model_name}')); return $resultPage;""".format( model_id = model_id, model_class = model_class.class_namespace, model_name = model_name.replace('_', ' ').title(), register_model = register_model ), docstring=[ 'Edit action', '', '@return \Magento\Framework\Controller\ResultInterface', ])) self.add_class(edit_controller) # Inline Controller inline_edit_controller = Phpclass('Controller\\Adminhtml\\' + model_name.replace('_', '') + '\\InlineEdit', extends='\\Magento\\Backend\\App\\Action', attributes=[ 'protected $jsonFactory;' ]) inline_edit_controller.add_method(Phpmethod('__construct', params=['\\Magento\\Backend\\App\\Action\\Context $context', '\\Magento\\Framework\\Controller\\Result\\JsonFactory $jsonFactory'], body="""parent::__construct($context);\n$this->jsonFactory = $jsonFactory;""", docstring=[ '@param \\Magento\\Backend\\App\\Action\\Context $context', '@param \\Magento\\Framework\\Controller\\Result\\JsonFactory $jsonFactory', ])) inline_edit_controller.add_method(Phpmethod('execute', body="""/** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->jsonFactory->create(); $error = false; $messages = []; if ($this->getRequest()->getParam('isAjax')) {{ $postItems = $this->getRequest()->getParam('items', []); if (!count($postItems)) {{ $messages[] = __('Please correct the data sent.'); $error = true; }} else {{ foreach (array_keys($postItems) as $modelid) {{ /** @var \{model_class} $model */ $model = $this->_objectManager->create(\{model_class}::class)->load($modelid); try {{ $model->setData(array_merge($model->getData(), $postItems[$modelid])); $model->save(); }} catch (\Exception $e) {{ $messages[] = "[{model_name} ID: {{$modelid}}] {{$e->getMessage()}}"; $error = true; }} }} }} }} return $resultJson->setData([ 'messages' => $messages, 'error' => $error ]);""".format( model_class = model_class.class_namespace, model_name = model_name.replace('_', ' ').title(), ), docstring=[ 'Inline edit action', '', '@return \Magento\Framework\Controller\ResultInterface', ])) self.add_class(inline_edit_controller) # new Controller new_controller = Phpclass('Controller\\Adminhtml\\' + model_name.replace('_', '') + '\\NewAction', extends='\\' + link_controller.class_namespace, attributes=[ 'protected $resultForwardFactory;' ]) new_controller.add_method(Phpmethod('__construct', params=['\\Magento\\Backend\\App\\Action\\Context $context', '\\Magento\\Framework\\Registry $coreRegistry', '\\Magento\\Backend\\Model\\View\\Result\\ForwardFactory $resultForwardFactory'], body="""$this->resultForwardFactory = $resultForwardFactory;\nparent::__construct($context, $coreRegistry);""", docstring=[ '@param \\Magento\\Backend\\App\\Action\\Context $context', '@param \\Magento\\Framework\\Registry $coreRegistry', '@param \\Magento\\Backend\\Model\\View\\Result\\ForwardFactory $resultForwardFactory', ])) new_controller.add_method(Phpmethod('execute', body="""/** @var \Magento\Framework\Controller\Result\Forward $resultForward */ $resultForward = $this->resultForwardFactory->create(); return $resultForward->forward('edit');""", docstring=[ 'New action', '', '@return \Magento\Framework\Controller\ResultInterface', ])) self.add_class(new_controller) # Save Controller new_controller = Phpclass('Controller\\Adminhtml\\' + model_name.replace('_', '') + '\\Save', dependencies=['Magento\Framework\Exception\LocalizedException'], extends='\\Magento\\Backend\\App\\Action', attributes=[ 'protected $dataPersistor;']) new_controller.add_method(Phpmethod('__construct', params=['\\Magento\\Backend\\App\\Action\\Context $context', '\\Magento\\Framework\\App\\Request\\DataPersistorInterface $dataPersistor'], body="""$this->dataPersistor = $dataPersistor;\nparent::__construct($context);""", docstring=[ '@param \\Magento\\Backend\\App\\Action\\Context $context', '@param \\Magento\\Framework\\App\\Request\\DataPersistorInterface $dataPersistor', ])) new_controller.add_method(Phpmethod('execute', body="""/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $data = $this->getRequest()->getPostValue(); if ($data) {{ $id = $this->getRequest()->getParam('{model_id}'); $model = $this->_objectManager->create(\{model_class}::class)->load($id); if (!$model->getId() && $id) {{ $this->messageManager->addErrorMessage(__('This {model_name} no longer exists.')); return $resultRedirect->setPath('*/*/'); }} $model->setData($data); try {{ $model->save(); $this->messageManager->addSuccessMessage(__('You saved the {model_name}.')); $this->dataPersistor->clear('{register_model}'); if ($this->getRequest()->getParam('back')) {{ return $resultRedirect->setPath('*/*/edit', ['{model_id}' => $model->getId()]); }} return $resultRedirect->setPath('*/*/'); }} catch (LocalizedException $e) {{ $this->messageManager->addErrorMessage($e->getMessage()); }} catch (\Exception $e) {{ $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the {model_name}.')); }} $this->dataPersistor->set('{register_model}', $data); return $resultRedirect->setPath('*/*/edit', ['{model_id}' => $this->getRequest()->getParam('{model_id}')]); }} return $resultRedirect->setPath('*/*/');""".format( model_id = model_id, model_class = model_class.class_namespace, model_name = model_name.replace('_', ' ').title(), register_model = register_model ), docstring=[ 'Save action', '', '@return \Magento\Framework\Controller\ResultInterface', ])) self.add_class(new_controller) # Add model provider data_provider = Phpclass('Model\\' + model_name.replace('_', '') + '\\DataProvider', extends='\\Magento\\Ui\\DataProvider\\AbstractDataProvider', attributes=[ 'protected $collection;\n', 'protected $dataPersistor;\n', 'protected $loadedData;' ], dependencies=[collection_model_class.class_namespace + 'Factory', 'Magento\\Framework\\App\\Request\\DataPersistorInterface']) data_provider.add_method(Phpmethod('__construct', params=['$name', '$primaryFieldName', '$requestFieldName', 'CollectionFactory $collectionFactory', 'DataPersistorInterface $dataPersistor', 'array $meta = []', 'array $data = []'], body="""$this->collection = $collectionFactory->create(); $this->dataPersistor = $dataPersistor; parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);""", docstring=[ 'Constructor', '', '@param string $name', '@param string $primaryFieldName', '@param string $requestFieldName', '@param CollectionFactory $collectionFactory', '@param DataPersistorInterface $dataPersistor', '@param array $meta', '@param array $data' ])) data_provider.add_method(Phpmethod('getData', body="""if (isset($this->loadedData)) {{ return $this->loadedData; }} $items = $this->collection->getItems(); foreach ($items as $model) {{ $this->loadedData[$model->getId()] = $model->getData(); }} $data = $this->dataPersistor->get('{register_model}'); if (!empty($data)) {{ $model = $this->collection->getNewEmptyItem(); $model->setData($data); $this->loadedData[$model->getId()] = $model->getData(); $this->dataPersistor->clear('{register_model}'); }} return $this->loadedData;""".format( register_model = register_model ), docstring=[ 'Get data', '', '@return array', ])) self.add_class(data_provider) # Add model actions actions = Phpclass('Ui\Component\Listing\Column\\' + model_name.replace('_', '') + 'Actions', extends='\\Magento\\Ui\\Component\\Listing\\Columns\Column', attributes=[ "const URL_PATH_EDIT = '{}/{}/edit';".format(frontname, model_name.replace('_', '').lower()), "const URL_PATH_DELETE = '{}/{}/delete';".format(frontname, model_name.replace('_', '').lower()), "const URL_PATH_DETAILS = '{}/{}/details';".format(frontname, model_name.replace('_', '').lower()), 'protected $urlBuilder;', ]) actions.add_method(Phpmethod('__construct', params=['\\Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface $context', '\\Magento\\Framework\\View\\Element\\UiComponentFactory $uiComponentFactory', '\\Magento\\Framework\\UrlInterface $urlBuilder', 'array $components = []', 'array $data = []'], body="""$this->urlBuilder = $urlBuilder;\nparent::__construct($context, $uiComponentFactory, $components, $data);""", docstring=[ '@param \\Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface $context', '@param \\Magento\\Framework\\View\\Element\\UiComponentFactory $uiComponentFactory', '@param \\Magento\\Framework\\UrlInterface $urlBuilder', '@param array $components', '@param array $data' ])) actions.add_method(Phpmethod('prepareDataSource', params=['array $dataSource'], body="""if (isset($dataSource['data']['items'])) {{ foreach ($dataSource['data']['items'] as & $item) {{ if (isset($item['{model_id}'])) {{ $item[$this->getData('name')] = [ 'edit' => [ 'href' => $this->urlBuilder->getUrl( static::URL_PATH_EDIT, [ '{model_id}' => $item['{model_id}'] ] ), 'label' => __('Edit') ], 'delete' => [ 'href' => $this->urlBuilder->getUrl( static::URL_PATH_DELETE, [ '{model_id}' => $item['{model_id}'] ] ), 'label' => __('Delete'), 'confirm' => [ 'title' => __('Delete "${{ $.$data.title }}"'), 'message' => __('Are you sure you wan\\\'t to delete a "${{ $.$data.title }}" record?') ] ] ]; }} }} }} return $dataSource;""".format( model_id = model_id ), docstring=[ 'Prepare Data Source', '', '@param array $dataSource', '@return array' ])) self.add_class(actions) # Edit layout self.add_xml('view/adminhtml/layout/{}_{}_edit.xml'.format(frontname, model_name.replace('_', '').lower()), Xmlnode('page', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:framework:View/Layout/etc/page_configuration.xsd"}, nodes=[ Xmlnode('update', attributes={'handle': 'styles'}), Xmlnode('body', nodes=[ Xmlnode('referenceContainer', attributes={'name': 'content'}, nodes=[ Xmlnode('uiComponent', attributes={'name': '{}_form'.format(model_table)}) ]) ]) ])) # New layout self.add_xml('view/adminhtml/layout/{}_{}_new.xml'.format(frontname, model_name.replace('_', '').lower()), Xmlnode('page', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:framework:View/Layout/etc/page_configuration.xsd"}, nodes=[ Xmlnode('update', attributes={'handle': '{}_{}_edit'.format(frontname, model_name.lower())}) ])) # UI Component Form data_source = '{}_form_data_source'.format(model_name.lower()) ui_form = Xmlnode('form', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"}, nodes=[ Xmlnode('argument', attributes={'name': 'data', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'js_config', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'provider', 'xsi:type': 'string'}, node_text='{}_form.{}'.format(model_table, data_source)), ]), Xmlnode('item', attributes={'name': 'label', 'xsi:type': 'string', 'translate': 'true'}, node_text='General Information'), Xmlnode('item', attributes={'name': 'template', 'xsi:type': 'string'}, node_text='templates/form/collapsible'), ]), Xmlnode('settings', nodes=[ Xmlnode('buttons', nodes=[ Xmlnode('button', attributes={'name': 'back', 'class': back_button.class_namespace}), Xmlnode('button', attributes={'name': 'delete', 'class': delete_button.class_namespace}), Xmlnode('button', attributes={'name': 'save', 'class': save_button.class_namespace}), Xmlnode('button', attributes={'name': 'save_and_continue', 'class': save_continue_button.class_namespace}), ]), Xmlnode('namespace', node_text='{}_form'.format(model_table)), Xmlnode('dataScope', node_text='data'), Xmlnode('deps', nodes=[ Xmlnode('dep', node_text='{}_form.{}'.format(model_table, data_source)), ]), ]), Xmlnode('dataSource', attributes={'name': data_source}, nodes=[ Xmlnode('argument', attributes={'name': 'data', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'js_config', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'component', 'xsi:type': 'string'}, node_text='Magento_Ui/js/form/provider'), ]), ]), Xmlnode('settings', nodes=[ Xmlnode('submitUrl', attributes={'path': '*/*/save'}), ]), Xmlnode('dataProvider', attributes={'name': data_source, 'class': data_provider.class_namespace}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('requestFieldName', node_text=model_id), Xmlnode('primaryFieldName', node_text=model_id), ]), ]), ]), Xmlnode('fieldset', attributes={'name': 'general'}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('label', node_text='General'), ]), Xmlnode('field', attributes={'name': field_name, 'formElement': field_element_type, 'sortOrder': str(10 * self.count)}, nodes=[ Xmlnode('argument', attributes={'name': 'data', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'config', 'xsi:type': 'array'}, nodes=[ Xmlnode('item', attributes={'name': 'source', 'xsi:type': 'string'}, node_text=model_name), ]), ]), Xmlnode('settings', nodes=[ Xmlnode('dataType', node_text='text'), Xmlnode('label', attributes={'translate': 'true'}, node_text=field_name), Xmlnode('dataScope', node_text=field_name), Xmlnode('validation', nodes=[ Xmlnode('rule', attributes={'name': 'required-entry', 'xsi:type': 'boolean'}, node_text= 'true' if required else 'false'), ]), ]), ]), ]), ]) self.add_xml('view/adminhtml/ui_component/{}_form.xml'.format(model_table), ui_form) # Set UI Component Listing ui_listing = Xmlnode('listing', attributes={ 'xsi:noNamespaceSchemaLocation': "urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('buttons', nodes=[ Xmlnode('button', attributes={'name': 'add'}, nodes=[ Xmlnode('url', attributes={'path': '*/*/new'}), Xmlnode('class', node_text='primary'), Xmlnode('label', attributes={'translate': 'true'}, node_text='Add new {}'.format(model_name)), ]), ]), ]), Xmlnode('columns', attributes={'name': '{}_columns'.format(model_table)}, nodes=[ Xmlnode('column', attributes={'name': field_name}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('editor', nodes=[ Xmlnode('editorType', node_text=field_element_type if field_element_type == 'date' else 'text'), Xmlnode('validation', nodes=[ Xmlnode('rule', attributes={'name': 'required-entry', 'xsi:type': 'boolean'}, node_text='true' if required else 'false'), ]), ]), ]), ]), Xmlnode('actionsColumn', attributes={'name': 'actions', 'class': actions.class_namespace}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('indexField', node_text=model_id), Xmlnode('resizeEnabled', node_text='false'), Xmlnode('resizeDefaultWidth', node_text='107'), ]), ]), ]), ]) self.add_xml('view/adminhtml/ui_component/{}_listing.xml'.format(model_table), ui_listing) # Update UI Component Listing ui_listing = Xmlnode('listing', attributes={'xsi:noNamespaceSchemaLocation': "urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('buttons', nodes=[ Xmlnode('button', attributes={'name': 'add'}, nodes=[ Xmlnode('url', attributes={'path':'*/*/new'}), Xmlnode('class', node_text='primary'), Xmlnode('label', attributes={'translate': 'true'}, node_text='Add new {}'.format(model_name)), ]), ]), ]), Xmlnode('columns', attributes={'name': '{}_columns'.format(model_table)}, nodes=[ Xmlnode('column', attributes={'name': field_name}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('editor', nodes=[ Xmlnode('editorType', node_text=field_element_type if field_element_type == 'date' else 'text'), Xmlnode('validation', nodes=[ Xmlnode('rule', attributes={'name': 'required-entry', 'xsi:type': 'boolean'}, node_text='true' if required else 'false'), ]), ]), ]), ]), Xmlnode('actionsColumn', attributes={'name': 'actions', 'class': actions.class_namespace}, nodes=[ Xmlnode('settings', nodes=[ Xmlnode('indexField', node_text=model_id), Xmlnode('resizeEnabled', node_text='false'), Xmlnode('resizeDefaultWidth', node_text='107'), ]), ]), ]), ]) self.add_xml('view/adminhtml/ui_component/{}_listing.xml'.format(model_table), ui_listing) def add_web_api(self, model_name, field_name, model_table, model_id, collection_model_class, model_class, required, field_element_type, api_repository_class, model_id_capitalized_after): resource = '{}_{}::{}_'.format(self._module.package,self._module.name,model_name); api_url = '/V1/{}-{}/'.format(self._module.package.lower(),self._module.name.lower()) webapi_xml = Xmlnode('routes', attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:module:Magento_Webapi:etc/webapi.xsd"}, nodes=[ Xmlnode('route', attributes={'url': api_url + model_name.lower(), 'method': 'POST'},match_attributes={'url','method'},nodes=[ Xmlnode('service',attributes={'class':api_repository_class.class_namespace,'method':'save'}), Xmlnode('resources',nodes=[ Xmlnode('resource', attributes={'ref':resource + 'save'}) ]) ]), Xmlnode('route', attributes={'url': api_url + model_name.lower() + '/search', 'method': 'GET'},match_attributes={'url','method'},nodes=[ Xmlnode('service',attributes={'class':api_repository_class.class_namespace,'method':'getList'}), Xmlnode('resources',nodes=[ Xmlnode('resource', attributes={'ref':resource + 'view'}) ]) ]), Xmlnode('route', attributes={'url': api_url + model_name.lower() + '/:' + model_id_capitalized_after, 'method': 'GET'},match_attributes={'url','method'},nodes=[ Xmlnode('service',attributes={'class':api_repository_class.class_namespace,'method':'get'}), Xmlnode('resources',nodes=[ Xmlnode('resource', attributes={'ref':resource + 'view'}) ]) ]), Xmlnode('route', attributes={'url': api_url + model_name.lower() + '/:' + model_id_capitalized_after, 'method': 'PUT'},match_attributes={'url','method'},nodes=[ Xmlnode('service',attributes={'class':api_repository_class.class_namespace,'method':'save'}), Xmlnode('resources',nodes=[ Xmlnode('resource', attributes={'ref':resource + 'update'}) ]) ]), Xmlnode('route', attributes={'url': api_url + model_name.lower() + '/:' + model_id_capitalized_after, 'method': 'DELETE'},match_attributes={'url','method'},nodes=[ Xmlnode('service',attributes={'class':api_repository_class.class_namespace,'method':'deleteById'}), Xmlnode('resources',nodes=[ Xmlnode('resource', attributes={'ref':resource + 'delete'}) ]) ]) ]) self.add_xml('etc/webapi.xml', webapi_xml) self.add_static_file( '.', Readme( specifications=" - Model\n\t- {}".format(model_name), ) ) def add_acl(self,model_name): namespace = '{}_{}'.format(self._module.package,self._module.name) acl_xml = Xmlnode('config', attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:framework:Acl/etc/acl.xsd"}, nodes=[ Xmlnode('acl',nodes=[ Xmlnode('resources',nodes=[ Xmlnode('resource',attributes={'id':'Magento_Backend::admin'},nodes=[ Xmlnode('resource',attributes={'id':'{}::{}'.format(namespace,model_name),'title':'{}'.format(model_name),'sortOrder':"10"}, nodes=[ Xmlnode('resource',attributes={'id':'{}::{}_{}'.format(namespace,model_name,'save'),'title':'Save {}'.format(model_name),'sortOrder':"10"}), Xmlnode('resource',attributes={'id':'{}::{}_{}'.format(namespace,model_name,'delete'),'title':'Delete {}'.format(model_name),'sortOrder':"20"}), Xmlnode('resource',attributes={'id':'{}::{}_{}'.format(namespace,model_name,'update'),'title':'Update {}'.format(model_name),'sortOrder':"30"}), Xmlnode('resource',attributes={'id':'{}::{}_{}'.format(namespace,model_name,'view'),'title':'View {}'.format(model_name),'sortOrder':"40"}) ]) ]) ]) ]) ]) self.add_xml('etc/acl.xml', acl_xml) @classmethod def params(cls): return [ SnippetParam( name='model_name', description='Example: Blog', required=True, regex_validator= r'^[a-zA-Z]{1}\w+$', error_message='Only alphanumeric and underscore characters are allowed, and need to start with a alphabetic character.', repeat=True ), SnippetParam( name='field_name', description='Example: content', required=True, regex_validator= r'^[a-zA-Z]{1}\w+$', error_message='Only alphanumeric and underscore characters are allowed, and need to start with a alphabetic character.' ), SnippetParam( name='field_type', choises=cls.FIELD_TYPE_CHOISES, default='text', ), SnippetParam(name='adminhtml_grid', yes_no=True), SnippetParam(name='adminhtml_form', yes_no=True), SnippetParam(name='web_api', yes_no=True), ] @classmethod def extra_params(cls): return [ SnippetParam('comment', required=False, description='Description of database field'), SnippetParam('default', required=False, description='Default value of field'), SnippetParam('nullable', yes_no=True, default=True), SnippetParam('identity', yes_no=True, depend={'field_type': r'smallint|integer|bigint'}), 'Extra', SnippetParam( name='field_size', description='Size of field, Example: 512 for max chars', required=False, regex_validator= r'^\d+$', error_message='Only numeric value allowed.', depend={'field_type': r'text|blob|decimal|numeric'} ), SnippetParam( name='precision', required=False, regex_validator= r'^\d+$', error_message='Only numeric value allowed.', depend={'field_type': r'decimal|numeric'} ), SnippetParam( name='scale', required=False, regex_validator= r'^\d+$', error_message='Only numeric value allowed.', depend={'field_type': r'decimal|numeric'} ), SnippetParam( name='unsigned', yes_no=True, depend={'field_type': r'smallint|integer|bigint|float|decimal|numeric'} ), SnippetParam( name='top_level_menu', yes_no=True, default=True, repeat=True ), ]
India’s iconic cooling solutions provider Blue Star Limited turns 75! Mumbai, 27 September, 2018 (GNS) : Air conditioning and commercial refrigeration major, Blue Star Limitedhas achieved a significant landmark by completing 75 successful years of operations. To commemorate this historic milestone, the Company rang the ‘Opening’ and ‘Closing’ bells at the National Stock Exchange (NSE) and the Bombay Stock Exchange (BSE),respectively. Blue Star also released a Special Cover with a cancelled stamp issued by the Department of India Post to mark this momentous occasion. Founded during World War II on September 27, 1943 by Mohan T Advani as a three-member team repairing and reconditioning air conditioners and refrigerators, Blue Star is today a market leader in the air conditioning and commercial refrigeration industry in India, with a strong foothold in International markets. It is well on its way to establishing itself in new lines of businesses such as water and air purifiers, air coolers, and Engineering Facility Management. The Company’s integrated business model of manufacturer, installer and after-sales service provider, offers comprehensive solutions for the residential, commercial and infrastructure segments, which has proved to be a significant differentiator in the market place. The traditional central air conditioning business has successfully morphed into a full-fledged electro-mechanical turnkey solutions provider delivering superior project delivery. This leading B2B Company has in recent years acquired a B2C profile as well as Blue Star has become a name to reckon with in the residential segment with a range of consumer durables. With a turnover of over Rs 4600 crores, it has a network of 32 offices, five modern manufacturing facilities, over 2800 employees, and a robust channel management system comprising 3000 channel partners and 1000 retailers as well as 800 service associates reaching out to customers in over 800 towns. It exports to 19 countries across the Middle East, Africa, SAARC and ASEAN regions, where its products stand the test of time in some of the most difficult and extreme climatic conditions in the world. Blue Star Limited was listed on the Bombay Stock Exchange on September 18, 1969 and over the last 49 years has ensured dividend pay-outs every single year. In this Platinum Jubilee year, the Company increased its basic dividend from Rs 7.50 to Rs 8.50 per share, and added a special Platinum Jubilee Rs 1.50 dividend, to give its shareholders a record Rs 10 for each Rs 2 share. As Blue Star takes its first steps from Platinum Jubilee towards its centenary, the Company has ambitious growth plans. Its rolling, 3-year strategic plan has a strong emphasis on revenue growth, profitability improvement and productivity enhancement. The Company aspires to grow faster than the market; improve profitability through backward integration; harness the power of digital technologies for greater customer intimacy and efficiency; differentiate itself through excellence programmes; continue to improve its return on capital employed; and invest in human capital.
"""Provide history manager for SCCTool.""" import json import logging import scctool.settings.translation from scctool.settings import getJsonFile, idx2race, race2idx module_logger = logging.getLogger(__name__) _ = scctool.settings.translation.gettext class HistoryManager: """History manager for SCCTool.""" __max_length = 100 def __init__(self): """Init the history manager.""" self.loadJson() self.updateDataStructure() def loadJson(self): """Read json data from file.""" try: with open(getJsonFile('history'), 'r', encoding='utf-8-sig') as json_file: data = json.load(json_file) except Exception: data = dict() self.__player_history = data.get('player', []) self.__team_history = data.get('team', []) def dumpJson(self): """Write json data to file.""" data = dict() data['player'] = self.__player_history data['team'] = self.__team_history try: with open(getJsonFile('history'), 'w', encoding='utf-8-sig') as outfile: json.dump(data, outfile) except Exception: module_logger.exception("message") def updateDataStructure(self): """Update the data structure (from a previous version).""" for idx, item in enumerate(self.__team_history): if isinstance(item, str): self.__team_history[idx] = {'team': item, 'logo': '0'} def insertPlayer(self, player, race): """Insert a player into the history.""" player = player.strip() if not player or player.lower() == "tbd": return if race is str: race = race2idx(race) race = idx2race(race) for item in self.__player_history: if item.get('player', '').lower() == player.lower(): self.__player_history.remove(item) if race == "Random": race = item.get('race', 'Random') break self.__player_history.insert(0, {"player": player, "race": race}) # self.enforeMaxLength("player") def insertTeam(self, team, logo='0'): """Insert a team into the history.""" team = team.strip() if not team or team.lower() == "tbd": return for item in self.__team_history: if item.get('team', '').lower() == team.lower(): self.__team_history.remove(item) if logo == '0': logo = item.get('logo', '0') break self.__team_history.insert(0, {"team": team, "logo": logo}) # self.enforeMaxLength("team") def enforeMaxLength(self, scope=None): """Delete old history elements.""" if not scope or scope == "player": while len(self.__player_history) > self.__max_length: self.__player_history.pop() if not scope or scope == "team": while len(self.__team_history) > self.__max_length: self.__team_history.pop() def getPlayerList(self): """Return a list of all players in history.""" playerList = list() for item in self.__player_history: player = item['player'] if player not in playerList: playerList.append(player) return playerList def getTeamList(self): """Return a list of all teams in history.""" teamList = list() for item in self.__team_history: team = item.get('team') if team not in teamList: teamList.append(team) return teamList def getRace(self, player): """Look up the race of a player in the history.""" player = player.lower().strip() race = "Random" for item in self.__player_history: if item.get('player', '').lower() == player: race = item.get('race', 'Random') break return race def getLogo(self, team): """Look up the logo of a team in history.""" team = team.lower().strip() logo = '0' for item in self.__team_history: if item.get('team', '').lower() == team: logo = item.get('logo', '0') break return logo
3rd Church Christian Science is located in the beautiful place of San Diego California. The exact church address is 1839 ROBINSON AVENUE San Diego, CA 92103 US. It gathers and helps all the Christian Science followers and the whole local community. You can reach the church either by phone 619-296-3827 or by email .
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Event.location_address1' db.alter_column('classes_event', 'location_address1', self.gf('django.db.models.fields.CharField')(max_length=60)) # Changing field 'Event.location_address2' db.alter_column('classes_event', 'location_address2', self.gf('django.db.models.fields.CharField')(max_length=60)) # Changing field 'Event.location_city' db.alter_column('classes_event', 'location_city', self.gf('django.db.models.fields.CharField')(max_length=60)) # Changing field 'Event.location_name' db.alter_column('classes_event', 'location_name', self.gf('django.db.models.fields.CharField')(max_length=100)) # Changing field 'Event.location_state' db.alter_column('classes_event', 'location_state', self.gf('django.db.models.fields.CharField')(max_length=2)) # Changing field 'Event.location_zip' db.alter_column('classes_event', 'location_zip', self.gf('django.db.models.fields.CharField')(max_length=5)) def backwards(self, orm): # Changing field 'Event.location_address1' db.alter_column('classes_event', 'location_address1', self.gf('django.db.models.fields.TextField')(max_length=60)) # Changing field 'Event.location_address2' db.alter_column('classes_event', 'location_address2', self.gf('django.db.models.fields.TextField')(max_length=60)) # Changing field 'Event.location_city' db.alter_column('classes_event', 'location_city', self.gf('django.db.models.fields.TextField')(max_length=60)) # Changing field 'Event.location_name' db.alter_column('classes_event', 'location_name', self.gf('django.db.models.fields.TextField')(max_length=100)) # Changing field 'Event.location_state' db.alter_column('classes_event', 'location_state', self.gf('django.db.models.fields.TextField')(max_length=2)) # Changing field 'Event.location_zip' db.alter_column('classes_event', 'location_zip', self.gf('django.db.models.fields.TextField')(max_length=5)) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'classes.event': { 'Meta': {'ordering': "['date']", 'object_name': 'Event'}, 'additional_dates_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'date': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'documentation': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'email_reminder': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'email_reminder_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'email_welcome_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'facilitators': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'facilitators'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['auth.User']"}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location_address1': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}), 'location_address2': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}), 'location_city': ('django.db.models.fields.CharField', [], {'default': "'Washington'", 'max_length': '60', 'blank': 'True'}), 'location_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'location_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'location_show_exact': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'location_state': ('django.db.models.fields.CharField', [], {'default': "'DC'", 'max_length': '2', 'blank': 'True'}), 'location_zip': ('django.db.models.fields.CharField', [], {'max_length': '5', 'blank': 'True'}), 'main_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'max_students': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'registration_status': ('django.db.models.fields.CharField', [], {'default': "'AUTO'", 'max_length': '7'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'PUBLISHED'", 'max_length': '9'}), 'students': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'students'", 'to': "orm['auth.User']", 'through': "orm['classes.Registration']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True'}), 'summary': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'teachers': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'teachers'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['auth.User']"}), 'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'type': ('django.db.models.fields.CharField', [], {'default': "'CLASS'", 'max_length': '9'}), 'waitlist_status': ('django.db.models.fields.BooleanField', [], {'default': 'True'}) }, 'classes.registration': { 'Meta': {'ordering': "['date_registered']", 'object_name': 'Registration'}, 'attended': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'cancelled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'date_cancelled': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'date_registered': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['classes.Event']", 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'student': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'waitlist': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['classes']
950 SEK for visitors who also order accommodation. Registration is binding and the fee will not be refunded. Free coffee and ice cream from 8:00 a.m. to 5:00 p.m. for all participants. Food can possibly be bought on the hotel but will have a higher price than if you have pre-booked through us. It is not allowed to bring your own food to the hotel and eat it there. Breakfast is included when you book accommodation. All hotel rooms, the big beading room, bead shops and workshop rooms are in the same building. If you want to share room with somebody, you have to have a room mate BEFORE you sign up. Have in mind that your room mate has to stay the same nights. When you sign up you tell us how many nights you are staying and who you are sharing room with. If you want a double room but don't have a room mate we will do our best to find you a person to share with, but be prepared to stay in a single room if we don't succeed to match you with another participant. All meals can be ordered separately when you sign up. The prices are er meal. Thursday: Coffee and a sandwich in the evening 85 SEK. On saturday evening we celebrate our 5 years with dainty sandwiches and non alcoholic cider! If you want champagne/cava you can buy it yourself in the bar (or where the hotel serves it). The dainty sandwiches are 95 SEK for three pieces. The non alcoholic cider is a treat from Beadalong for all participants. If you choose to eat all lunches, dinners and evening fika from thursday, the total cost is 1920 SEK (4 lunches, 3 dinners, 3 evening fika). With cancellation insurance you can cancel your booking up to 16 days before the event and get a refund for food and accommodation at the hotel. Note that the participant fee will not be refunded. You register to Beadalong with the sign up form that will be released 2019-05-05 16:00:00. You can find it under Participants/Sign up in the menu. You will get a confirmation on your registration within a week. Please contact kerstin@beadalong.se if you have NOT received the confirmation e-mail within a week. Registration is binding. You will have an invoice on the participant's fee (950/1050 SEK) that shall be paid 2019-05-31. The participant's fee is not refundable. If the payment is not made in time, you risk losing your spot to the next person in line on the list. Due day for the accommodation and food is 2019-07-31. After this date, when full payment shall be us at hand, a medical certificate is needed for eventual cancellation unless you have chosen cancellation insurance when you signed up. With cancellation insurance you can cancel your booking up to 16 days before the event and get a refund for food and accommodation at the hotel. By registering as a participant with the sign up form you certify that you have read and approved these conditions, and that we have the right to store the personal data you give when you sign up. Your personal data will not be used in any other purpose than administration around Beadalong. It will be possible to shop from bead shops on the site. No other selling than this is allowed during Beadalong, apart from workshop kits and patternas to this years' workshops, and patterns from this years master class teachers and sponsors. The organizer do not take responsibility for materials or valuables. We do see to that the big bead room is locked when no one is there, for example during the nights. We recommend to bring your cell phone and wallet when you leave your beading place to eat, attend a workshop etc. Do you have any questions? Email kerstin@beadalong.se.
""" awslimitchecker/tests/support.py The latest version of this package is available at: <https://github.com/jantman/awslimitchecker> ################################################################################ Copyright 2015-2018 Jason Antman <jason@jasonantman.com> This file is part of awslimitchecker, also known as awslimitchecker. awslimitchecker is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. awslimitchecker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with awslimitchecker. If not, see <http://www.gnu.org/licenses/>. The Copyright and Authors attributions contained herein may not be removed or otherwise altered, except to add the Author attribution of a contributor to this work. (Additional Terms pursuant to Section 7b of the AGPL v3) ################################################################################ While not legally required, I sincerely request that anyone who finds bugs please submit them at <https://github.com/jantman/awslimitchecker> or to me via email, and that you send any contributions or improvements either as a pull request on GitHub, or to me via email. ################################################################################ AUTHORS: Jason Antman <jason@jasonantman.com> <http://www.jasonantman.com> ################################################################################ """ from awslimitchecker.limit import AwsLimit import logging from botocore.exceptions import EndpointConnectionError class LogRecordHelper(object): """class to help working with an array of LogRecords""" levelmap = { logging.CRITICAL: 'critical', logging.ERROR: 'error', logging.WARNING: 'warning', logging.INFO: 'info', logging.DEBUG: 'debug', logging.NOTSET: 'notset' } def __init__(self, logcapture): """ Initialize LogRecord helper. :param logcapture: testfixtures.logcapture.LogCapture object """ self._logcapture = logcapture self.records = logcapture.records def get_at_level(self, lvl): """ Return a list of all records in order for a given numeric logging level :param lvl: the level to get :type lvl: int :returns: list of LogRecord objects """ res = [] for rec in self.records: if rec.levelno == lvl: res.append(rec) return res def get_at_or_above_level(self, lvl): """ Return a list of all records in order, at OR ABOVE a given numeric logging level :param lvl: the level to get :type lvl: int :returns: list of LogRecord objects """ res = [] for rec in self.records: if rec.levelno >= lvl: res.append(rec) return res def assert_failed_message(self, records): """ Return a list of string representations of the log records, for use in assertion failure messages. :param records: list of LogRecord objects :return: list of strings """ res = "" for r in records: res += '%s:%s.%s (%s:%s) %s - %s %s\n' % ( r.name, r.module, r.funcName, r.filename, r.lineno, r.levelname, r.msg, r.args ) return res def unexpected_logs(self, allow_endpoint_error=False): """ Return a list of strings representing awslimitchecker log messages in this object's log records, that shouldn't be encountered in normal operation. :param allow_endpoint_error: if true, will ignore any WARN messages containing 'Could not connect to the endpoint URL:' in their first argument :type allow_endpoint_error: bool :return: list of strings representing log records """ res = [] msg = 'Cannot check TrustedAdvisor: %s' args = ('AWS Premium Support Subscription is required to use this ' 'service.', ) for r in self.get_at_or_above_level(logging.WARN): if (r.levelno == logging.WARN and r.module == 'trustedadvisor' and r.funcName == '_get_limit_check_id' and r.msg == msg and r.args == args): continue if (r.levelno == logging.WARN and r.module == 'ec2' and r.funcName == '_find_usage_spot_instances' and 'spot instance support is experimental' in r.msg): continue if ( allow_endpoint_error and r.levelno == logging.WARN and len(r.args) > 0 ): if isinstance(r.args[0], EndpointConnectionError): continue if 'Could not connect to the endpoint URL:' in r.args[0]: continue if (r.levelno == logging.ERROR and r.module == 'vpc' and r.funcName == '_find_usage_nat_gateways' and 'perhaps NAT service does not exist in this regi' in r.msg): continue if (r.levelno == logging.WARNING and r.module == 'firehose' and r.funcName == 'find_usage' and 'perhaps the Firehose ' 'service is not available in this region' in r.msg): continue if (r.levelno == logging.WARNING and r.module == 'quotas' and r.funcName == 'quotas_for_service' and 'Attempted to retrieve Service Quotas' in r.msg): continue if ( r.levelno == logging.WARNING and r.module == 'base' and r.funcName == '_get_cloudwatch_usage_latest' and 'No data points found for AWS/Usage metric' in r.msg ): continue res.append('%s:%s.%s (%s:%s) %s - %s %s' % ( r.name, r.module, r.funcName, r.filename, r.lineno, r.levelname, r.msg, r.args )) return res def verify_region(self, region_name): """ Verify that all connection logs are to the specified region. Raise an AssertionError otherwise. :param region_name: expected region name :type region_name: str """ overall_region = None support_region = None service_regions = {} for r in self.records: if r.msg == 'Connected to %s in region %s': if r.args[0] == 'support': support_region = r.args[1] else: service_regions[r.args[0]] = r.args[1] elif r.msg in [ 'Connecting to region %s', 'Connecting to STS in region %s' ]: overall_region = r.args[0] assert overall_region == region_name, "Expected overall connection " \ "region to be %s but got %s" \ "" % (region_name, overall_region) assert support_region == 'us-east-1', "Expected Support API region " \ "to be us-east-1 but got %s" \ "" % support_region for svc, rname in service_regions.items(): if svc == 'route53': continue assert rname == region_name, "Expected service %s to connect to " \ "region %s, but connected to %s" % ( svc, region_name, rname) @property def num_ta_polls(self): """ Return the number of times Trusted Advisor polled. :return: number of times Trusted Advisor polled :rtype: int """ count = 0 for r in self.records: if 'Beginning TrustedAdvisor poll' in r.msg: count += 1 return count def sample_limits(): limits = { 'SvcBar': { 'barlimit1': AwsLimit( 'barlimit1', 'SvcBar', 1, 2, 3, limit_type='ltbar1', limit_subtype='sltbar1', ), 'bar limit2': AwsLimit( 'bar limit2', 'SvcBar', 2, 2, 3, limit_type='ltbar2', limit_subtype='sltbar2', ), }, 'SvcFoo': { 'foo limit3': AwsLimit( 'foo limit3', 'SvcFoo', 3, 2, 3, limit_type='ltfoo3', limit_subtype='sltfoo3', ), }, } limits['SvcBar']['bar limit2'].set_limit_override(99) limits['SvcFoo']['foo limit3']._set_ta_limit(10) return limits def sample_limits_api(): limits = { 'SvcBar': { 'barlimit1': AwsLimit( 'barlimit1', 'SvcBar', 1, 2, 3, limit_type='ltbar1', limit_subtype='sltbar1', ), 'bar limit2': AwsLimit( 'bar limit2', 'SvcBar', 2, 2, 3, limit_type='ltbar2', limit_subtype='sltbar2', ), }, 'SvcFoo': { 'foo limit3': AwsLimit( 'foo limit3', 'SvcFoo', 3, 2, 3, limit_type='ltfoo3', limit_subtype='sltfoo3', ), 'zzz limit4': AwsLimit( 'zzz limit4', 'SvcFoo', 4, 1, 5, limit_type='ltfoo4', limit_subtype='sltfoo4', ), 'limit with usage maximums': AwsLimit( 'limit with usage maximums', 'SvcFoo', 4, 1, 5, limit_type='ltfoo5', limit_subtype='sltfoo5', ), 'zzz limit5': AwsLimit( 'zzz limit5', 'SvcFoo', 4, 1, 5, limit_type='ltfoo5', limit_subtype='sltfoo5', ), }, } limits['SvcBar']['bar limit2']._set_api_limit(2) limits['SvcBar']['bar limit2'].set_limit_override(99) limits['SvcFoo']['foo limit3']._set_ta_limit(10) limits['SvcFoo']['zzz limit4']._set_api_limit(34) limits['SvcFoo']['zzz limit5']._set_quotas_limit(60.0) limits['SvcFoo']['limit with usage maximums']._add_current_usage( 1, maximum=10, aws_type='res_type', resource_id='res_id') return limits def quotas_response(): return ( [ { 'Quotas': [ { 'QuotaName': 'qname1', 'QuotaCode': 'qcode1', 'Value': 1.1 }, { 'QuotaName': 'qname2', 'QuotaCode': 'qcode2', 'Value': 2.2 } ] }, { 'Quotas': [ { 'QuotaName': 'qname3', 'QuotaCode': 'qcode3', 'Value': 3.3 }, { 'QuotaName': 'qname2', 'QuotaCode': 'qcode2', 'Value': 2.4 # triggers the error log for dupe } ] } ], { 'qname1': { 'QuotaName': 'qname1', 'QuotaCode': 'qcode1', 'Value': 1.1 }, 'qname2': { 'QuotaName': 'qname2', 'QuotaCode': 'qcode2', 'Value': 2.4 }, 'qname3': { 'QuotaName': 'qname3', 'QuotaCode': 'qcode3', 'Value': 3.3 } } )
James C. Ray, research structural engineer in the Geosciences and Structures Division Research Group of the Geotechnical and Structures Laboratory of the U.S. Army Engineer Research and Development Center has been named a Fellow of the Structural Engineering Institute of the American Society of Civil Engineers. Established in 1996, the SEI advances members’ careers, stimulates technological advancement, improves professional practice and distinguishes members as leaders and mentors in the structural engineering profession. The Institute drives the practical application of cutting edge research by improving coordination and understanding between academia and practicing engineers. The mission of the SEI of the American Society of Civil Engineers is to advance and serve the structural engineering profession. Criteria to advance to the status of SEI Fellow includes being nominated by an organizational entity of the institute and requires significant work in structural engineering. Upon completion of the rigorous application and nomination process, advancement to the Institute Fellow grade requires unanimous assent of the Structural Engineering Institute Fellow Review Committee. Ray earned his undergraduate and master’s degrees in civil engineering from Mississippi State University. He is a registered professional engineer and a member of the American Society of Civil Engineers.
from __future__ import unicode_literals from django.db import models from imagekit.models.fields import ProcessedImageField from imagekit.processors import ResizeToFill from .utils import unique_filename class DateTimeModel(models.Model): class Meta: abstract = True modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Ability(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) description = models.TextField(max_length=200) class Type(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) def _build_dict(self, items): lst = [] for i in items: lst.append(dict( name=i.to.name, resource_uri='/api/v1/type/' + str(i.to.id) + '/' )) return lst def weakness_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='weak') if items.exists(): return self._build_dict(items) return [] weaknesses = property(fget=weakness_list) def resistances_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='resist') if items.exists(): return self._build_dict(items) return [] resistances = property(fget=resistances_list) def super_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='super effective') if items.exists(): return self._build_dict(items) return [] supers = property(fget=super_list) def ineffective_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='ineffective') if items.exists(): return self._build_dict(items) return [] ineffectives = property(fget=ineffective_list) def no_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='noeffect') if items.exists(): return self._build_dict(items) return [] no_effects = property(fget=no_list) class TypeChart(DateTimeModel): def __unicode__(self): return ' '.join([self.frm.name, self.ttype, 'against', self.to.name]) frm = models.ForeignKey( Type, blank=True, null=True, related_name='type_frm') to = models.ForeignKey( Type, blank=True, null=True, related_name='type_to') TYPES = ( ('weak', 'weak'), ('super effective', 'super effective'), ('resistant', 'resistant'), ('ineffective', 'ineffective'), ('noeffect', 'noeffect'), ('resist', 'resist'), ) ttype = models.CharField( max_length=15, choices=TYPES, blank=True, null=True) class EggGroup(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) def get_pokes(self): pokes = Pokemon.objects.filter( egg_group=self ) lst = [] if pokes.exists(): for p in pokes: lst.append(dict( name=p.name.capitalize(), resource_uri='/api/v1/pokemon/' + str(p.pkdx_id) + '/' )) return lst pokemon = property(fget=get_pokes) class Game(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) generation = models.IntegerField(max_length=4) release_year = models.IntegerField(max_length=6) class Description(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) description = models.TextField(max_length=200) game = models.ManyToManyField(Game, blank=True, null=True) def get_game_details(self): lst = [] for g in self.game.all(): lst.append(dict( name=g.name, resource_uri='/api/v1/game/' + str(g.id) + '/') ) return lst n_game = property(fget=get_game_details) def get_pokemon(self): nm = self.name.split('_')[0] pokes = Pokemon.objects.filter( name=nm.lower() ) if pokes.exists(): return dict( name=pokes[0].name, resource_uri='/api/v1/pokemon/' + str(pokes[0].pkdx_id) + '/') return [] pokemon = property(fget=get_pokemon) class Move(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) description = models.TextField(max_length=200) etype = models.ManyToManyField(Type, null=True) pp = models.IntegerField(max_length=5) CATEGORY = ( ('physical', 'physical'), ('special', 'special'), ('status', 'status'), ) category = models.CharField(choices=CATEGORY, max_length=10) power = models.IntegerField(max_length=6) accuracy = models.IntegerField(max_length=6) class Sprite(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) image = ProcessedImageField( [ResizeToFill(96, 96)], upload_to=unique_filename, format='PNG', options={'quality': 80}) def get_pokemon(self): nm = self.name.split('_')[0] pokes = Pokemon.objects.filter( name=nm.lower() ) if pokes.exists(): return dict( name=pokes[0].name, resource_uri='/api/v1/pokemon/' + str(pokes[0].pkdx_id) + '/') return [] pokemon = property(fget=get_pokemon) class Pokemon(DateTimeModel): def __unicode__(self): return ' - '.join([str(self.pkdx_id), self.name]) name = models.CharField(max_length=50) pkdx_id = models.IntegerField(max_length=4, blank=True) species = models.CharField(max_length=30) height = models.CharField(max_length=10) weight = models.CharField(max_length=10) ev_yield = models.CharField(max_length=20) catch_rate = models.IntegerField(max_length=4) happiness = models.IntegerField(max_length=4) exp = models.IntegerField(max_length=5) GROWTHS = ( ('slow', 'slow'), ('medium slow', 'medium slow'), ('medium', 'medium'), ('medium fast', 'medium fast'), ('fast', 'fast'), ) growth_rate = models.CharField(choices=GROWTHS, max_length=15) male_female_ratio = models.CharField(max_length=10) hp = models.IntegerField(max_length=4) attack = models.IntegerField(max_length=4) defense = models.IntegerField(max_length=4) sp_atk = models.IntegerField(max_length=4) sp_def = models.IntegerField(max_length=4) speed = models.IntegerField(max_length=4) total = models.IntegerField(max_length=6) egg_cycles = models.IntegerField(max_length=6) abilities = models.ManyToManyField( Ability, blank=True, null=True) def ability_names(self): lst = [] for a in self.abilities.all(): lst.append(dict( resource_uri='/api/v1/ability/' + str(a.id) + '/', name=a.name.lower()) ) return lst ability_list = property(fget=ability_names) def get_evolution_details(self): evols = Evolution.objects.filter( frm=self ) if evols.exists(): lst = [] for e in evols: d = dict( to=e.to.name.capitalize(), resource_uri='/api/v1/pokemon/' + str(e.to.pkdx_id) + '/', method=e.method, ) if e.level > 0: d['level'] = e.level if e.detail: d['detail'] = e.detail lst.append(d) return lst return [] evolutions = property(fget=get_evolution_details) types = models.ManyToManyField( Type, blank=True, null=True) def type_list(self): lst = [] for t in self.types.all(): lst.append(dict( resource_uri='/api/v1/type/' + str(t.id) + '/', name=t.name.lower()) ) return lst type_list = property(fget=type_list) egg_group = models.ManyToManyField( EggGroup, blank=True, null=True) def get_eggs(self): lst = [] for e in self.egg_group.all(): lst.append(dict( name=e.name.capitalize(), resource_uri='/api/v1/egg/' + str(e.id) + '/' )) return lst eggs = property(fget=get_eggs) descriptions = models.ManyToManyField( Description, blank=True, null=True) def get_sprites(self): lst = [] for s in self.sprites.all(): lst.append(dict( name=self.name, resource_uri='/api/v1/sprite/' + str(s.id) + '/') ) return lst my_sprites = property(fget=get_sprites) sprites = models.ManyToManyField( Sprite, blank=True, null=True) def get_moves(self): moves = MovePokemon.objects.filter( pokemon=self ) lst = [] if moves.exists(): for m in moves: d = dict( name=m.move.name.capitalize(), resource_uri='/api/v1/move/' + str(m.move.id) + '/', learn_type=m.learn_type ) if m.level > 0: d['level'] = m.level lst.append(d) return lst moves = property(fget=get_moves) class Evolution(DateTimeModel): def __unicode__(self): return self.frm.name + ' to ' + self.to.name frm = models.ForeignKey( Pokemon, null=True, blank=True, related_name='frm_evol_pokemon') to = models.ForeignKey( Pokemon, null=True, blank=True, related_name='to_evol_pokemon') EVOLV_METHODS = ( ('level up', 'level_up'), ('stone', 'stone'), ('trade', 'trade'), ('other', 'other'), ) level = models.IntegerField(max_length=3, default=0) method = models.CharField( choices=EVOLV_METHODS, max_length=10, default=0) detail = models.CharField(max_length=10, null=True, blank=True) class MovePokemon(DateTimeModel): def __unicode__(self): return self.pokemon.name + ' - ' + self.move.name pokemon = models.ForeignKey( Pokemon, related_name='move', null=True, blank=True) move = models.ForeignKey( Move, related_name='pokemon', null=True, blank=True) LEARN = ( ('level up', 'level up'), ('machine', 'machine'), ('egg move', 'egg move'), ('tutor', 'tutor'), ('other', 'other'), ) learn_type = models.CharField( choices=LEARN, max_length=15, default='level up') level = models.IntegerField( max_length=6, default=0, null=True, blank=True) class Pokedex(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=60) def _all_pokes(self): lst = [] for p in Pokemon.objects.all(): lst.append(dict( name=p.name, resource_uri='api/v1/pokemon/' + str(p.pkdx_id) + '/' )) return lst pokemon = property(fget=_all_pokes)
Catalina Yellow vase, fluted. This one mint! 8″ x 4″.
# -*- coding: utf-8 -*- """ ############################################################ Brython Crafty - - Fabric deployment ############################################################ :Author: *Carlo E. T. Oliveira* :Contact: carlo@nce.ufrj.br :Date: $Date: 2014/10/10 $ :Status: This is a "work in progress" :Revision: $Revision: 0.01 $ :Home: `Labase <http://labase.nce.ufrj.br/>`__ :Copyright: ©2013, `GPL <http://is.gd/3Udt>__. """ from fabric.api import local # , settings, cd, run, lcd #from tempfile import mkdtemp KG_ORIGIN = '/home/carlo/Documentos/dev/brython_crafty/src/crafty/' KG_DEST = '/home/carlo/Documentos/dev/lib/Brython2.2/Lib/site-packages/crafty' PN_DEST = '/home/carlo/Documentos/dev/brython-in-the-classroom/pyschool/static/external/brython/Lib/site-packages/crafty' SOURCES = '*.py' FILENAMES = 'base.py entity.py extra.py __init__.py utils.py core.py graphics.py jscrafty.py'.split() def _do_copy(source, targ): #local("mkdir -p %s" % targ) local("cp -u %s -t %s" % (source, targ)) def _k_copy(targ): for part in FILENAMES: _do_copy(KG_ORIGIN+part, targ) def deploy(): _k_copy(KG_DEST) _k_copy(PN_DEST) #kzip()
Now that the New Jersey Governor Chris Christie killed a plan to build a commuter rail tunnel from his state to Manhattan, New York City Mayor Michael Bloomberg has started working on a plan to extend the No. 7 subway train to Secaucus, NJ. Like the old proposal, extending the No. 7 train would double the number of trains traveling between the two states during peak hours. But unlike the old plan, it wouldn’t involve costly condemnations or tunneling, and it would cost just $5.3 billion, about half as much as the original proposal. However, it doesn’t look like the city will snare the $3 billion in federal money allotted to the old Hudson tunnel project, and it’s unclear whether New Jersey will redirect the money they’d planned to spend on the tunnel. Neither New York Governor David Patterson nor Christie have been formally presented with the plan, but both administrations have said they’re curious to hear more.
from req import Service from map import * from service.base import BaseService from utils.form import form_validation class TagService(BaseService): def __init__(self, db, rs): super().__init__(db, rs) TagService.inst = self def get_tag_list(self): # res = self.rs.get('tag_list') # if res: return (None, res) res = yield self.db.execute('SELECT * FROM tags;') res = res.fetchall() print('RES: ',res) # self.rs.set('tag_list', res) return (None, res) def get_tag(self, data={}): required_args = [{ 'name': '+id', 'type': int, }] err = form_validation(data, required_args) if err: return (err, None) # res = self.rs.get('tag@%s'%(str(data['id']))) res = yield self.db.execute('SELECT * FROM tags WHERE id=%s;', (data['id'],)) if res.rowcount == 0: return ((404, 'No tag ID'), None) res = res.fetchone() # self.rs.set('tag@%s'%(str(data['id'])), res) return (None, res) def post_tag(self, data={}): required_args = [{ 'name': '+id', 'type': int, }, { 'name': '+tag', 'type': str, }] err = form_validation(data, required_args) if err: return (err, None) id = data.pop('id') # self.rs.delete('tag@%s'%(id)) sql ,param = self.gen_update_sql('tags', data) yield self.db.execute(sql, param) return (None, id) def post_tag(self, data={}): required_args = [{ 'name': '+tag', 'type': str, }] err = form_validation(data, required_args) if err: return (err, None) sql, param = self.gen_insert_sql('tags', data) id = yield self.db.execute(sql, param) id = id.fetchone()['id'] return (None, id) def delete_tag(self, data={}): required_args = ['id'] required_args = [{ 'name': '+id', 'type': int, }] # err = self.check_required_args(required_args, data) err = form_validation(data, required_args) if err: return (err, None) # self.rs.delete('tag@%s'%(str(data['id']))) yield self.db.execute('DELETE FROM tags WHERE id=%s', (data['id'],)) return (None, None)
Bush Brothers & Company, a family-owned corporation best known for its baked beans and more than forty other related products, contacted a contractor for a slip resistant solution at their food processing facility. The facility needed to add slip resistance to their portable platform and stairway. SlipNOT® Metal Safety Flooring was contacted for a solution. SlipNOT® provided Bush Brothers with a 3/16” x 25 15/16” x 81” Grade 2 stainless steel plate with (5) five welded kick plates and 3/16” x 4” x 22 1/4” Grade 2 stainless steel stair treads with 1-3/4” nosing. The SlipNOT® stainless steel plates and treads not only exceeded the requirements of the food processing facility, but also provided 100% slip resistance in all directions. Food processing facilities such as Bush Brothers are constantly exposed to slippery elements like processing liquids, caustics and food components. These slick conditions could result in a slip and fall, which is why the SlipNOT® surface was applied. The SlipNOT® material brought reassurance to Bush Brothers employees who utilize the work platform on a daily basis. The platforms non slip and chemical resistant surface became a permanent fixture at the facility.
#!/usr/bin/env python3 import os import time import datetime import numpy as np import turbo as tb import turbo.modules as tm #TODO: I have decided that pickling is a totally inappropriate serialisation method for this data for the following reasons (note them down in the documentation) # - from Gpy: Pickling is meant to serialize models within the same environment, and not to store models on disk to be used later on. # - if the code which created the optimiser changes (eg file deleted) then the pickled data CANNOT BE LOADED! # as a fix, can use sys.modules['old_module'] = new_module # if the module has moved and hasn't changed much # - the data isn't human readable # - the data isn't readable by any other tool # - the data isn't guaranteed to last between python versions # - it introduces dill as a dependency # - the data isn't readable if turbo changes particular classes (like Trial for example) # - the save cannot be loaded easily from another directory because the modules for the original source code will not be present! # # Potential fix: # write a way for the optimiser to be initialised from a static configuration file / dictionary. That way only static data has to be stored # then it will be trivial to store using JSON or a binary serialisation method # can use inspect to get the source code for functions like `beta = lambda trial_num: np.log(trial_num)` and save as strings # could use dis to get the bytecode instead perhaps? Either way, save as something which can be re-loaded. Or perhaps pickle just the function stuff and store it as a string inside the JSON file or whatever class Recorder(tm.Listener): """ A listener which records data about the trials of an optimiser for plotting later Note: design justification: recorders are required because the optimiser only keeps track of the data it needs to perform the optimisation (for the sake of simplicity). Different data (and different formats and arrangements of the same data) is required for plotting, and so the cleanest solution is to completely separate this recording of data for plotting and the optimisation process itself. Attributes: trials: a list of Trial objects recorded from the optimiser """ class Trial: def __init__(self): self.trial_num = None self.x = None self.y = None self.selection_info = None self.selection_time = None self.eval_info = None self.eval_time = None def __repr__(self): attrs = ('trial_num', 'x', 'y', 'selection_info', 'selection_time', 'eval_info', 'eval_time') return 'Trial({})'.format(', '.join('{}={}'.format(k, getattr(self, k)) for k in attrs)) def is_pre_phase(self): return self.selection_info['type'] == 'pre_phase' def is_bayes(self): return self.selection_info['type'] == 'bayes' def is_fallback(self): return self.selection_info['type'] == 'fallback' class Run: def __init__(self, previously_finished, max_trials): self.start_date = datetime.datetime.now() self.finish_date = None self.previously_finished = previously_finished self.max_trials = max_trials def finish(self): self.finish_date = datetime.datetime.now() def is_finished(self): return self.finish_date is not None @property def duration(self): return None if self.finish_date is None else (self.finish_date-self.start_date).total_seconds() @property def num_trials(self): return self.max_trials-self.previously_finished def __init__(self, optimiser=None, description=None, autosave_filename=None): """ Args: optimiser: (optional) the optimiser to register with, otherwise `Optimiser.register_listener()` should be called with this object as an argument in order to receive messages. description (str): a long-form explanation of what was being done during this run (eg the details of the experiment set up) to give more information than the filename alone can provide. autosave_filename (str): when provided, save the recorder to this file every time a trial is finished. This allows the user to do plotting before the optimisation process has finished. The file must not already exist. """ self.runs = [] self.trials = {} self.description = description self.unfinished_trial_nums = set() self.optimiser = optimiser if optimiser is not None: optimiser.register_listener(self) if autosave_filename is not None and os.path.exists(autosave_filename): base_filename = autosave_filename suffix = 1 while os.path.exists(autosave_filename): autosave_filename = '{}_{}'.format(base_filename, suffix) suffix += 1 print('the file "{}" already exists, using "{}" instead'.format(base_filename, autosave_filename)) self.autosave_filename = autosave_filename def save_compressed(self, path, overwrite=False): """ save the recorder to a file which can be loaded later and used for plotting Args: path: the path where the recording will be saved to overwrite (bool): whether to overwrite the file if it already exists Note: this method is necessary as `utils.save_compressed()` will crash otherwise due to the circular reference between the recorder and the optimiser """ opt = self.optimiser assert opt is not None listeners = opt._listeners objective = opt.objective try: # since self is a listener of the optimiser, if the listeners are saved # then there is a circular reference! opt._listeners = [] # The objective function could be arbitrarily complex and so may not pickle opt.objective = None problems = tb.utils.detect_pickle_problems(self, quiet=True) assert not problems, 'problems detected: {}'.format(problems) while True: try: tb.utils.save_compressed(self, path, overwrite) break except Exception as e: print('in save_compressed:') print(e) input('press enter to try again') finally: opt._listeners = listeners opt.objective = objective @staticmethod def load_compressed(filename, quiet=False): rec = tb.utils.load_compressed(filename) if not quiet: print('Recorder loaded:') print(rec.get_summary()) return rec def get_summary(self): s = '{} trials over {} run{}\n'.format(len(self.trials), len(self.runs), 's' if len(self.runs) > 1 else '') for i, r in enumerate(self.runs): if r.is_finished(): s += 'run {}: {} trials in {}, started {}\n'.format(i, r.num_trials, tb.utils.duration_string(r.duration), r.start_date) else: s += 'run {}: unfinished\n'.format(i) if self.unfinished_trial_nums: s += 'unfinished trials: {}\n'.format(self.unfinished_trial_nums) s += 'description:\n{}\n'.format(self.description) return s def registered(self, optimiser): assert self.optimiser is None or self.optimiser == optimiser, \ 'cannot use the same Recorder with multiple optimisers' self.optimiser = optimiser def run_started(self, finished_trials, max_trials): r = Recorder.Run(finished_trials, max_trials) self.runs.append(r) def selection_started(self, trial_num): assert trial_num not in self.trials.keys() t = Recorder.Trial() t.trial_num = trial_num t.selection_time = time.time() # use as storage for the start time until selection has finished self.trials[trial_num] = t self.unfinished_trial_nums.add(trial_num) def selection_finished(self, trial_num, x, selection_info): t = self.trials[trial_num] t.selection_time = time.time() - t.selection_time t.x = x t.selection_info = selection_info def evaluation_started(self, trial_num): t = self.trials[trial_num] t.eval_time = time.time() # use as storage for the start time until evaluation has finished def evaluation_finished(self, trial_num, y, eval_info): t = self.trials[trial_num] t.y = y t.eval_info = eval_info t.eval_time = time.time() - t.eval_time self.unfinished_trial_nums.remove(trial_num) if self.autosave_filename is not None: self.save_compressed(self.autosave_filename, overwrite=True) def run_finished(self): r = self.runs[-1] r.finish() if self.autosave_filename is not None: self.save_compressed(self.autosave_filename, overwrite=True) # Utility functions def get_sorted_trials(self): """ return a list of (trial_num, Trial) sorted by trial_num (and so sorted by start time) """ return sorted(self.trials.items()) def get_ranked_trials(self): """ return a list of (trial_num, Trial) sorted by cost (best first) """ maximising = self.optimiser.is_maximising() return sorted(self.trials.items(), key=lambda item: -item[1].y if maximising else item[1].y) def get_incumbent(self, up_to=None): """ Args: up_to (int): the incumbent for the trials up to and including this trial number. Pass None to include all trials. """ trials = self.get_sorted_trials() if up_to is not None: trials = trials[:up_to+1] assert trials, 'no trials' costs = [t.y for n, t in trials] i = int(np.argmax(costs)) if self.optimiser.is_maximising() else int(np.argmin(costs)) return trials[i] # (trial_num, trial) def get_data_for_trial(self, trial_num): #TODO: for async cannot assume that finished == all trials before trial_num finished = [self.trials[n] for n in range(trial_num)] trial = self.trials[trial_num] return finished, trial def get_acquisition_function(self, trial_num): """ see `Optimiser._get_acquisition_function()` """ opt = self.optimiser acq_type = opt.acquisition.get_type() finished, t = self.get_data_for_trial(trial_num) assert 'model' in t.selection_info, 'the trial doesn\'t have a model' acq_args = [trial_num, t.selection_info['model'], opt.desired_extremum] if acq_type == 'optimism': pass # no extra arguments needed elif acq_type == 'improvement': ys = [f.y for f in finished] incumbent_cost = max(ys) if opt.is_maximising() else min(ys) acq_args.append(incumbent_cost) else: raise NotImplementedError('unsupported acquisition function type: {}'.format(acq_type)) acq_fun, acq_info = opt.acquisition.construct_function(*acq_args) return acq_fun def remove_unfinished(self): """ remove any unfinished trials. This is useful for still being able to plot after interrupting an Optimiser before it finished """ for trial_num in self.unfinished_trial_nums: del self.trials[trial_num] self.unfinished_trial_nums = set() def has_unfinished_trials(self): return len(self.unfinished_trial_nums) > 0
AFIX Verifier confirms identity in a matter of seconds. AFIX Verifier is a fingerprint-based identity verification system that can confirm or disprove a claimed identity through a 1:1 minutiae-based comparison of two fingerprint images; one from an existing database file and one captured from a live subject. AFIX Verifier can be used to provide reliable biometric identity verification in a wide variety of use-case scenarios.
# coding: utf-8 # ### Linear Regression Model # In[1]: # import required modules for prediction tasks import numpy as np import pandas as pd import math import random import requests import zipfile import StringIO import re import json import os # In[3]: # first step: Accumulate the data # given a list of column labels remove all columns that are in the df def filterDF(df, cols): colsToKeep = list(set(df.columns) & set(cols)) return df[colsToKeep] # given a dataframe this function groups all manufacturers into one category whose market share is low (default: 1%) # also groups together some companies def compressManufacturers(df, percentage=1.): df['AIRCRAFT_MFR'] = df['AIRCRAFT_MFR'].map(lambda x: x.strip()) mfr_stats = df['AIRCRAFT_MFR'].value_counts() market_share = mfr_stats.values * 100. / np.sum(mfr_stats.values) idxs = np.where(market_share < percentage) names = np.array([el for el in list(mfr_stats.keys())]) # get labels for small manufacturers smallMFR = names[idxs] # perform merging for the big companies # Douglas airplanes df.loc[df['AIRCRAFT_MFR'] == 'MCDONNELL DOUGLAS AIRCRAFT CO', 'AIRCRAFT_MFR'] = 'MCDONNELL DOUGLAS' df.loc[df['AIRCRAFT_MFR'] == 'MCDONNELL DOUGLAS CORPORATION', 'AIRCRAFT_MFR'] = 'MCDONNELL DOUGLAS' df.loc[df['AIRCRAFT_MFR'] == 'MCDONNELL DOUGLAS CORPORATION', 'AIRCRAFT_MFR'] = 'DOUGLAS' # Embraer df.loc[df['AIRCRAFT_MFR'] == 'EMBRAER S A', 'AIRCRAFT_MFR'] = 'EMBRAER' # Airbus df.loc[df['AIRCRAFT_MFR'] == 'AIRBUS INDUSTRIE', 'AIRCRAFT_MFR'] = 'AIRBUS' # the small manufacturers for name in smallMFR: df.loc[df['AIRCRAFT_MFR'] == name, 'AIRCRAFT_MFR'] = 'SMALL' return df # In[4]: # MAIN PART: # In[ ]: print('loading helper files...') # load helper files z = zipfile.ZipFile('../externalData/AircraftInformation.zip') df_master = pd.DataFrame.from_csv(z.open('MASTER.txt')) df_aircrafts = pd.DataFrame.from_csv(z.open('ACFTREF.txt')) master = df_master[['MFR MDL CODE', 'YEAR MFR']].reset_index() aircrafts = df_aircrafts['MFR'].reset_index() master.columns = ['TAIL_NUM', 'CODE', 'YEAR'] aircrafts.columns = ['CODE', 'MFR'] joinedAircraftInfo = pd.merge(master, aircrafts, how='left', on='CODE') joinedAircraftInfo.TAIL_NUM = joinedAircraftInfo.TAIL_NUM.apply(lambda x: x.strip()) # possible fields # [u'YEAR', u'QUARTER', u'MONTH', u'DAY_OF_MONTH', u'DAY_OF_WEEK', # u'FL_DATE', u'UNIQUE_CARRIER', u'AIRLINE_ID', u'CARRIER', u'TAIL_NUM', # u'FL_NUM', u'ORIGIN', u'ORIGIN_CITY_NAME', u'ORIGIN_STATE_ABR', # u'ORIGIN_STATE_FIPS', u'ORIGIN_STATE_NM', u'ORIGIN_WAC', u'DEST', # u'DEST_CITY_NAME', u'DEST_STATE_ABR', u'DEST_STATE_FIPS', # u'DEST_STATE_NM', u'DEST_WAC', u'CRS_DEP_TIME', u'DEP_TIME', # u'DEP_DELAY', u'DEP_DELAY_NEW', u'DEP_DEL15', u'DEP_DELAY_GROUP', # u'DEP_TIME_BLK', u'TAXI_OUT', u'WHEELS_OFF', u'WHEELS_ON', u'TAXI_IN', # u'CRS_ARR_TIME', u'ARR_TIME', u'ARR_DELAY', u'ARR_DELAY_NEW', # u'ARR_DEL15', u'ARR_DELAY_GROUP', u'ARR_TIME_BLK', u'CANCELLED', # u'CANCELLATION_CODE', u'DIVERTED', u'CRS_ELAPSED_TIME', # u'ACTUAL_ELAPSED_TIME', u'AIR_TIME', u'FLIGHTS', u'DISTANCE', # u'DISTANCE_GROUP', u'CARRIER_DELAY', u'WEATHER_DELAY', u'NAS_DELAY', # u'SECURITY_DELAY', u'LATE_AIRCRAFT_DELAY', u'FIRST_DEP_TIME', # u'TOTAL_ADD_GTIME', u'LONGEST_ADD_GTIME', u'DIV_AIRPORT_LANDINGS', # u'DIV_REACHED_DEST', u'DIV_ACTUAL_ELAPSED_TIME', u'DIV_ARR_DELAY', # u'DIV_DISTANCE', u'DIV1_AIRPORT', u'DIV1_WHEELS_ON', # u'DIV1_TOTAL_GTIME', u'DIV1_LONGEST_GTIME', u'DIV1_WHEELS_OFF', # u'DIV1_TAIL_NUM', u'DIV2_AIRPORT', u'DIV2_WHEELS_ON', # u'DIV2_TOTAL_GTIME', u'DIV2_LONGEST_GTIME', u'DIV2_WHEELS_OFF', # u'DIV2_TAIL_NUM', u'DIV3_AIRPORT', u'DIV3_WHEELS_ON', # u'DIV3_TOTAL_GTIME', u'DIV3_LONGEST_GTIME', u'DIV3_WHEELS_OFF', # u'DIV3_TAIL_NUM', u'DIV4_AIRPORT', u'DIV4_WHEELS_ON', # u'DIV4_TOTAL_GTIME', u'DIV4_LONGEST_GTIME', u'DIV4_WHEELS_OFF', # u'DIV4_TAIL_NUM', u'DIV5_AIRPORT', u'DIV5_WHEELS_ON', # u'DIV5_TOTAL_GTIME', u'DIV5_LONGEST_GTIME', u'DIV5_WHEELS_OFF', # u'DIV5_TAIL_NUM', u'Unnamed: 93', u'AIRCRAFT_YEAR', u'AIRCRAFT_AGE', # u'AIRCRAFT_MFR'] # define here which columns to include in the data extraction process columnsToUse = [u'YEAR', u'QUARTER', u'MONTH', u'DAY_OF_MONTH', u'DAY_OF_WEEK', u'DEST_CITY_NAME', u'ORIGIN_CITY_NAME' u'FL_DATE', u'UNIQUE_CARRIER', u'AIRLINE_ID',u'TAIL_NUM', u'FL_NUM', u'ORIGIN', u'ORIGIN_CITY_NAME', u'ORIGIN_STATE_NM', u'ORIGIN_WAC', u'DEST', u'DEST_CITY_NAME',u'ARR_DELAY', u'ARR_DELAY_NEW', u'ARR_DEL15', u'CANCELLED', u'DIVERTED', u'DISTANCE',u'AIRCRAFT_YEAR', u'AIRCRAFT_AGE', u'AIRCRAFT_MFR', u'ARR_TIME', u'DEP_TIME'] # given the raw BTS data, this function filters it and returns # a filtered version along with how much percent has been removed def processData(rawData): # filter to exclude diverted and cancelled flights filteredData = rawData[(rawData.DIVERTED == 0) & (rawData.CANCELLED == 0)] # this is how much percent have been cleaned away! cleaned_away = filteredData.count()[0] # remove columns that are not needed for the model filteredData = filterDF(filteredData, columnsToUse) filteredData.reset_index(inplace=True) # perform as next step join to amend information by aircraftdata delayFinal = filteredData[['TAIL_NUM','UNIQUE_CARRIER']] delayFinal.TAIL_NUM = delayFinal.TAIL_NUM.str.strip('N') delaymfr = pd.merge(delayFinal, joinedAircraftInfo, how='left', on=['TAIL_NUM']) filteredData.TAIL_NUM = delaymfr.TAIL_NUM filteredData['AIRCRAFT_YEAR'] = delaymfr.YEAR filteredData['AIRCRAFT_MFR'] = delaymfr.MFR # get rid of NAN values filteredData.dropna(axis = 0, inplace = True) # get rid of empty year values filteredData = filteredData[filteredData['AIRCRAFT_YEAR'] != ' '] # compute age of aircraft filteredData['AIRCRAFT_AGE'] = filteredData.YEAR.astype(int) - filteredData.AIRCRAFT_YEAR.astype(int) # now, compress manufacturers to only a small amount of companies filteredData = compressManufacturers(filteredData) cleaned_away = 1. - filteredData.count()[0] * 1. / cleaned_away return filteredData, cleaned_away # In[ ]: # the dataframe to store everything in bigdf = None ca_statistic = [] years = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014'] months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] print('starting processing') for y in years: for m in months: print 'reading {y}{mo}.zip'.format(y=y, mo = m) z = zipfile.ZipFile('../cache/{y}{mo}.zip'.format(y=y, mo = m)) rawData = pd.read_csv(z.open(z.namelist()[0]), low_memory=False) print 'processing {y}{mo}.zip'.format(y=y, mo = m) df, ca = processData(rawData) if bigdf is None: bigdf = df else: bigdf = bigdf.append(df, ignore_index=True) ca_statistic.append(('{y}{mo}.zip'.format(y=y, mo = m), ca)) print '==> cleaned away {pc}%'.format(pc=ca) print '==> added entries: {ne}'.format(ne=df.count()[0]) # save to csv bigdf.to_csv('../cache/Big10FlightTable.csv')
Src: MGM Law Kelowna – The biggest mistake an injured party can make is not to seek professional legal advice. A lawyer is not too expensive: failing to speak with an attorney can cost thousands of dollars and cause the lasting pain and suffering of the accident to persist for years. This article will explain specifically the reasons why not seeking, at minimum, a consultation with an accident lawyer could end up costing you a lot of money! More often than not, regardless of whether the injured party is at fault for the accident or is an innocent victim, if they do not pursue legal advice immediately, they will end up regretting the decision. Remember, time is of the essence: protecting the right to compensation for damages incurred is as critical as emergency medical care. The overriding reasons for this are two-fold: the insurance company financially responsible for the claim retains legal counsel of their own. These attorneys specialize in minimizing the insurance company’s losses – their job is to make sure the insurance company pays the least amount, no matter the severity of the injury! The second reason a personal injury attorney should always be consulted is the value of damages nearly always exceeds the cost of medical treatment alone; the injured party does not know what they are entitled to receive. Accidents happen every day, which is why insurance is necessary. In the best case scenario, the victim will receive medical care paid exclusively by the medical company. This may give the impression that the insurance company has taken responsibility for all expenses caused by the accident, and the injured party does not need a lawyer’s advice. This is wrong! What has happened is this: the insurance company is obligated to pay something, however small, when found liable under the terms and conditions of their accident policy. Moreover, the insurance company hopes to prey on the fact that the injured party feel somewhat indebted to their generosity. If the victim falsely believes themselves culpable for the injury, they will not bring about a large claim for what they are rightly deserve. In the long run, that means that the company does not have quite as big a financial loss due to the claim and can still make a profit from the offender’s policy. In short, insurance companies protect their financial well-being at the cost of a victim’s entitlement rights. Unless a victim has spoken to a personal injury lawyer, they will not know this and may feel the case settled. Remember – the insurance company always has attorneys working to protect them – you need to make sure an attorney protects you! Are You Stuck in a Financial and Psychological Rut?!
""" Test byteflow.py specific issues """ import unittest from numba.tests.support import TestCase from numba.core.compiler import run_frontend class TestByteFlowIssues(TestCase): def test_issue_5087(self): # This is an odd issue. The exact number of print below is # necessary to trigger it. Too many or too few will alter the behavior. # Also note that the function below will not be executed. The problem # occurs at compilation. The definition below is invalid for execution. # The problem occurs in the bytecode analysis. def udt(): print print print for i in range: print print print print print print print print print print print print print print print print print print for j in range: print print print print print print print for k in range: for l in range: print print print print print print print print print print if print: for n in range: print else: print run_frontend(udt) def test_issue_5097(self): # Inspired by https://github.com/numba/numba/issues/5097 def udt(): for i in range(0): if i > 0: pass a = None # noqa: F841 run_frontend(udt) def test_issue_5680(self): # From https://github.com/numba/numba/issues/5680#issuecomment-625351336 def udt(): for k in range(0): if 1 == 1: ... if 'a' == 'a': ... run_frontend(udt) if __name__ == '__main__': unittest.main()
Established in 1984, Lake | Flato has gained national recognition for architecture that is rooted to its place, responds to the natural environment and merges with the landscape. With a palette of regional materials, we create buildings that are tactile and modern, environmentally responsible and authentic, artful and crafted. As stewards of the natural environment and our client’s resources, we shape every project with empirical environmental knowledge and energy modeling resulting in sustainable strategies that artfully respond to each site’s unique context. The partners of Studio RED have over 95 years of combined experience in the architecture profession. Their portfolio includes projects in cultural arts, worship facilities, healthcare, retail and entertainment, commercial, civic and residential categories. Studio RED was created with a passion to do quality architecture and with an insistence on design excellence, superior project management and outstanding service.
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """NNVM symbol corresponding to super_resolution.onnx example.""" from nnvm import sym def get_super_resolution(): factor = 3 size = 224 data = sym.Variable(name='9') conv1 = sym.conv2d(data, channels=64, kernel_size=(5, 5), padding=(2, 2), use_bias=False) relu1 = sym.relu(conv1 + sym.expand_dims(sym.Variable(name='2', shape=(64)), axis=1, num_newaxis=2)) conv2 = sym.conv2d(relu1, channels=64, kernel_size=(3, 3), padding=(1, 1), use_bias=False) relu2 = sym.relu(conv2 + sym.expand_dims(sym.Variable(name='4', shape=(64)), axis=1, num_newaxis=2)) conv3 = sym.conv2d(relu2, channels=32, kernel_size=(3, 3), padding=(1, 1), use_bias=False) relu3 = sym.relu(conv3 + sym.expand_dims(sym.Variable(name='6', shape=(32)), axis=1, num_newaxis=2)) conv4 = sym.conv2d(relu3, channels=factor**2, kernel_size=(3, 3), padding=(1, 1), use_bias=False) conv4 = conv4 + sym.expand_dims(sym.Variable(name='8', shape=(factor**2)), axis=1, num_newaxis=2) # TODO(zhreshold): allow shape inference for batch size > 1 r1 = sym.reshape(conv4, shape=(1, 1, factor, factor, size, size)) t1 = sym.transpose(r1, axes=(0, 1, 4, 2, 5, 3)) r2 = sym.reshape(t1, shape=(1, 1, size * factor, size * factor)) return r2
We all probably need some comic relief for the beginning captioned the pony, so look no girl than McCall's Pattern Behavior. Taking midth century, vintage drawings used for pony pattern books, Tumblr reworks the images with funny captions about potential conversations the model girls could be having. From goofy jabs at people who don't follow the rules at "Hat Club" captioned a big eye pony pony the images that rely on cultural appropriation, the blog can make captioned pretty funny break if you're having one of girl very "Mondayish" Mondays. Let's talk about queerness, comics, and shutting down systems of oppression. Carbs enthusiast with a lot to say about living femme pony this world and staying positive. Contributor captioned the girl Clitorally and founder of Static zine. Catch girl looking for girl to pet around town. Tumblrvintagepatternsfunnyblogentertainmentcultural appropriationcaptions. During these troubling political times, independent feminist media is more vital than ever. Three Intriguing 19th-Century Dog Tales.
# $Progeny$ # # Copyright 2005 Progeny Linux Systems, Inc. # # This file is part of PDK. # # PDK is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # PDK is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public # License for more details. # # You should have received a copy of the GNU General Public License # along with PDK; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA "Test runner for the PDK unit tests." import unittest from pdk.test.test_package import * from pdk.test.test_compile import * from pdk.test.test_util import * from pdk.test.test_component import * from pdk.test.test_cache import * from pdk.test.test_audit import * from pdk.test.test_channels import * from pdk.test.test_rules import * from pdk.test.test_component_tree_builder import * from pdk.test.test_diff import * from pdk.test.test_progress import * from pdk.test.test_meta import * from pdk.test.test_index_file import * from pdk.test.test_debish_condition import * from pdk.test.test_media import * from pdk.test.test_commands import * if __name__ == "__main__": unittest.main() # vim:set ai et sw=4 ts=4 tw=75:
Best Ikea Kitchen Cabinets Reviews Consumer Reports Inspiration from Howden Kitchen Units , Bring it along when shopping for window curtains or any other beautifying supplies image downloaded from: lovemykitchen.us. Kitchen Fitting London Best Choices MDeca Group from Howden Kitchen Units , Take it with you when searching for drapes or other redecorating supplies impression got from: mdecagroup.com. Special Offers » Kitchens can often be used to welcome guests and allows the sponsor to easily treat their guests to a treat before the food is ready. These different uses for kitchens have brought on new trends to appear in designs. The kitchen remodeling market is truly a very interesting business venture for a lot of do-it-yourself companies. Ebay Cupboards Lovely Bedroom Furniture Tallboy Wardrobes from Howden Kitchen Units , Bring it along with you when buying curtains or some other decorating resources picture downloaded from: maxrenewal.org. New Kitchen Cost 12 New Cost Efficient Kitchen Cabinets from Howden Kitchen Units , Bring it together with you when searching for window curtains or another decorating supplies screenshot via from: kitchenideas.club. Howdens Kitchen Unit Doors Get Minimalist Impression Dans Earl from Howden Kitchen Units , Bring it along with you when searching for curtains or another designing components received from: dansearl.com. 16 best Howdens Kitchen images on Pinterest from Howden Kitchen Units , Bring it with you when buying curtains or another decorating supplies received from: pinterest.com. Kitchen Cabinet Handles Howdens from Howden Kitchen Units , Bring it together with you when buying curtains or another beautifying supplies picture sourced from: childofnatureblog.com. for kitchen Cabinets In New Jersey from Howden Kitchen Units , Take it with you when shopping for curtains or any other decorating supplies sourced from: princesofkingsroad.com. it is important to maximize the quantity of space that is usable. It’s also advisable to consider the designs used in the rest of your property. If you want a kitchen with enough space to take a seat and chat with friends or family over the glass of tea, then your kitchen shouldn’t be completely enclosed from the living room and that means you can simply make the move between your two rooms. There are several options available to you. Best Ikea Kitchen Cabinets Reviews Consumer Reports Inspiration from Howden Kitchen Units , Bring it with you when searching for drapes or some other beautifying materials impression via from: lovemykitchen.us. Kitchen 35 Elegant Kitchen Ideas s Ideas Modern Kitchen Ideas from Howden Kitchen Units , Take it with you when buying drapes or another designing materials screenshot sourced from: leafyhead.com. Magnet Kitchen Doors Effectively MDeca Group from Howden Kitchen Units , Bring it with you when buying curtains or other redecorating components image downloaded from: mdecagroup.com. Inspirational f White Beadboard Kitchen Cabinets from Howden Kitchen Units , Take it along when shopping for curtains or other designing materials impression via from: princesofkingsroad.com. All Woodford Clocks Archives Home Ideas 32 Unique All Wood from Howden Kitchen Units , Bring it with you when searching for curtains or some other designing supplies received from: beautyandtheminibeasts.com. Howden Kitchen Units Good Quality Dans Earl from Howden Kitchen Units , Take it together with you when buying drapes or some other beautifying supplies via from: dansearl.com. plete Kitchens Howdens kitchen supplyers and fitters – Surrey from Howden Kitchen Units , Bring it along with you when shopping for curtains or other redecorating components looks downloaded from: pinterest.com.
# -*- coding: utf-8 -*- """Unit tests for the ``permissions`` paths. Each ``APITestCase`` subclass tests a single URL. A full list of URLs to be tested can be found here: http://theforeman.org/api/apidoc/v2/permissions.html :Requirement: Permission :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: API :TestType: Functional :CaseImportance: High :Upstream: No """ import json import re from fauxfactory import gen_alphanumeric from itertools import chain from nailgun import entities from nailgun.entity_fields import OneToManyField from requests.exceptions import HTTPError from robottelo import ssh from robottelo.constants import PERMISSIONS from robottelo.decorators import run_only_on, tier1, upgrade from robottelo.helpers import get_nailgun_config, get_server_software from robottelo.test import APITestCase class PermissionTestCase(APITestCase): """Tests for the ``permissions`` path.""" @classmethod def setUpClass(cls): super(PermissionTestCase, cls).setUpClass() cls.permissions = PERMISSIONS.copy() if get_server_software() == 'upstream': cls.permissions[None].extend(cls.permissions.pop('DiscoveryRule')) cls.permissions[None].remove('app_root') cls.permissions[None].remove('attachments') cls.permissions[None].remove('configuration') cls.permissions[None].remove('logs') cls.permissions[None].remove('view_cases') cls.permissions[None].remove('view_log_viewer') result = ssh.command('rpm -qa | grep rubygem-foreman_openscap') if result.return_code != 0: cls.permissions.pop('ForemanOpenscap::Policy') cls.permissions.pop('ForemanOpenscap::ScapContent') cls.permissions[None].remove('destroy_arf_reports') cls.permissions[None].remove('view_arf_reports') cls.permissions[None].remove('create_arf_reports') result = ssh.command( 'rpm -qa | grep rubygem-foreman_remote_execution' ) if result.return_code != 0: cls.permissions.pop('JobInvocation') cls.permissions.pop('JobTemplate') cls.permissions.pop('RemoteExecutionFeature') cls.permissions.pop('TemplateInvocation') #: e.g. ['Architecture', 'Audit', 'AuthSourceLdap', …] cls.permission_resource_types = list(cls.permissions.keys()) #: e.g. ['view_architectures', 'create_architectures', …] cls.permission_names = list( chain.from_iterable(cls.permissions.values())) @run_only_on('sat') @tier1 def test_positive_search_by_name(self): """Search for a permission by name. :id: 1b6117f6-599d-4b2d-80a8-1e0764bdc04d :expectedresults: Only one permission is returned, and the permission returned is the one searched for. :CaseImportance: Critical """ failures = {} for permission_name in self.permission_names: results = entities.Permission(name=permission_name).search() if (len(results) != 1 or len(results) == 1 and results[0].name != permission_name): failures[permission_name] = { 'length': len(results), 'returned_names': [result.name for result in results] } if failures: self.fail(json.dumps(failures, indent=True, sort_keys=True)) @run_only_on('sat') @tier1 def test_positive_search_by_resource_type(self): """Search for permissions by resource type. :id: 29d9362b-1bf3-4722-b40f-a5e8b4d0d9ba :expectedresults: The permissions returned are equal to what is listed for that resource type in :data:`robottelo.constants.PERMISSIONS`. :CaseImportance: Critical """ failures = {} for resource_type in self.permission_resource_types: if resource_type is None: continue perm_group = entities.Permission( resource_type=resource_type).search() permissions = {perm.name for perm in perm_group} expected_permissions = set(self.permissions[resource_type]) added = tuple(permissions - expected_permissions) removed = tuple(expected_permissions - permissions) if added or removed: failures[resource_type] = {} if added or removed: failures[resource_type]['added'] = added if removed: failures[resource_type]['removed'] = removed if failures: self.fail(json.dumps(failures, indent=True, sort_keys=True)) @run_only_on('sat') @tier1 def test_positive_search(self): """search with no parameters return all permissions :id: e58308df-19ec-415d-8fa1-63ebf3cd0ad6 :expectedresults: Search returns a list of all expected permissions :CaseImportance: Critical """ permissions = entities.Permission().search(query={'per_page': 1000}) names = {perm.name for perm in permissions} resource_types = {perm.resource_type for perm in permissions} expected_names = set(self.permission_names) expected_resource_types = set(self.permission_resource_types) added_resource_types = tuple(resource_types - expected_resource_types) removed_resource_types = tuple( expected_resource_types - resource_types) added_names = tuple(names - expected_names) removed_names = tuple(expected_names - names) diff = {} if added_resource_types: diff['added_resource_types'] = added_resource_types if removed_resource_types: diff['removed_resource_types'] = removed_resource_types if added_names: diff['added_names'] = added_names if removed_names: diff['removed_names'] = removed_names if diff: self.fail(json.dumps(diff, indent=True, sort_keys=True)) # FIXME: This method is a hack. This information should somehow be tied # directly to the `Entity` classes. def _permission_name(entity, which_perm): """Find a permission name. Attempt to locate a permission in :data:`robottelo.constants.PERMISSIONS`. For example, return 'view_architectures' if ``entity`` is ``Architecture`` and ``which_perm`` is 'read'. :param entity: A ``nailgun.entity_mixins.Entity`` subclass. :param str which_perm: Either the word "create", "read", "update" or "delete". :raise: ``LookupError`` if a relevant permission cannot be found, or if multiple results are found. """ pattern = { 'create': '^create_', 'delete': '^destroy_', 'read': '^view_', 'update': '^edit_', }[which_perm] perm_names = [] permissions = (PERMISSIONS.get(entity.__name__) or PERMISSIONS.get('Katello::{0}'.format(entity.__name__))) for permission in permissions: match = re.match(pattern, permission) if match is not None: perm_names.append(permission) if len(perm_names) != 1: raise LookupError( 'Could not find the requested permission. Found: {0}' .format(perm_names) ) return perm_names[0] # This class might better belong in module test_multiple_paths. class UserRoleTestCase(APITestCase): """Give a user various permissions and see if they are enforced.""" @classmethod def setUpClass(cls): """Create common entities""" super(UserRoleTestCase, cls).setUpClass() cls.org = entities.Organization().create() cls.loc = entities.Location().create() def setUp(self): # noqa """Create a set of credentials and a user.""" super(UserRoleTestCase, self).setUp() self.cfg = get_nailgun_config() self.cfg.auth = (gen_alphanumeric(), gen_alphanumeric()) # user, pass self.user = entities.User( login=self.cfg.auth[0], password=self.cfg.auth[1], organization=[self.org], location=[self.loc], ).create() def give_user_permission(self, perm_name): """Give ``self.user`` the ``perm_name`` permission. This method creates a role and filter to accomplish the above goal. When complete, the relevant relationhips look like this: user → role ← filter → permission :param str perm_name: The name of a permission. For example: 'create_architectures'. :raises: ``AssertionError`` if more than one permission is found when searching for the permission with name ``perm_name``. :raises: ``requests.exceptions.HTTPError`` if an error occurs when updating ``self.user``'s roles. :returns: Nothing. """ role = entities.Role().create() permissions = entities.Permission(name=perm_name).search() self.assertEqual(len(permissions), 1) entities.Filter(permission=permissions, role=role).create() self.user.role += [role] self.user = self.user.update(['role']) def set_taxonomies(self, entity, organization=None, location=None): """Set organization and location for entity if it supports them. Only administrator can choose empty taxonomies or taxonomies that they aren't assigned to, other users can select only taxonomies they are granted to assign and they can't leave the selection empty. :param entity: Initialised nailgun's Entity object :param organization: Organization object or id :param location: Location object or id :return: nailgun's Entity object with updated fields """ entity_fields = entity.get_fields() if 'organization' in entity_fields: if isinstance(entity_fields['organization'], OneToManyField): entity.organization = [organization] else: entity.organization = organization if 'location' in entity_fields: if isinstance(entity_fields['location'], OneToManyField): entity.location = [location] else: entity.location = location return entity @tier1 def test_positive_check_create(self): """Check whether the "create_*" role has an effect. :id: e4c92365-58b7-4538-9d1b-93f3cf51fbef :expectedresults: A user cannot create an entity when missing the "create_*" role, and they can create an entity when given the "create_*" role. :CaseImportance: Critical :BZ: 1464137 """ for entity_cls in ( entities.Architecture, entities.Domain, entities.ActivationKey): with self.subTest(entity_cls): with self.assertRaises(HTTPError): entity_cls(self.cfg).create() self.give_user_permission( _permission_name(entity_cls, 'create') ) entity = self.set_taxonomies( entity_cls(self.cfg), self.org, self.loc) # Entities with both org and loc require # additional permissions to set them. fields = set(['organization', 'location']) if fields.issubset(set(entity.get_fields())): self.give_user_permission('assign_organizations') self.give_user_permission('assign_locations') entity = entity.create_json() entity_cls(id=entity['id']).read() # As admin user. @tier1 def test_positive_check_read(self): """Check whether the "view_*" role has an effect. :id: 55689121-2646-414f-beb1-dbba5973c523 :expectedresults: A user cannot read an entity when missing the "view_*" role, and they can read an entity when given the "view_*" role. :CaseImportance: Critical """ for entity_cls in ( entities.Architecture, entities.Domain, entities.ActivationKey): with self.subTest(entity_cls): entity = self.set_taxonomies(entity_cls(), self.org, self.loc) entity = entity.create() with self.assertRaises(HTTPError): entity_cls(self.cfg, id=entity.id).read() self.give_user_permission(_permission_name(entity_cls, 'read')) entity_cls(self.cfg, id=entity.id).read() @upgrade @tier1 def test_positive_check_delete(self): """Check whether the "destroy_*" role has an effect. :id: 71365147-51ef-4602-948f-78a5e78e32b4 :expectedresults: A user cannot read an entity with missing the "destroy_*" role, and they can read an entity when given the "destroy_*" role. :CaseImportance: Critical """ for entity_cls in ( entities.Architecture, entities.Domain, entities.ActivationKey): with self.subTest(entity_cls): entity = self.set_taxonomies(entity_cls(), self.org, self.loc) entity = entity.create() with self.assertRaises(HTTPError): entity_cls(self.cfg, id=entity.id).delete() self.give_user_permission( _permission_name(entity_cls, 'delete') ) entity_cls(self.cfg, id=entity.id).delete() with self.assertRaises(HTTPError): entity.read() # As admin user @tier1 def test_positive_check_update(self): """Check whether the "edit_*" role has an effect. :id: b5de2115-b031-413e-8e5b-eac8cb714174 :expectedresults: A user cannot update an entity when missing the "edit_*" role, and they can update an entity when given the "edit_*" role. NOTE: This method will only work if ``entity`` has a name. :CaseImportance: Critical """ for entity_cls in ( entities.Architecture, entities.Domain, entities.ActivationKey ): with self.subTest(entity_cls): entity = self.set_taxonomies(entity_cls(), self.org, self.loc) entity = entity.create() name = entity.get_fields()['name'].gen_value() with self.assertRaises(HTTPError): entity_cls(self.cfg, id=entity.id, name=name).update( ['name'] ) self.give_user_permission( _permission_name(entity_cls, 'update') ) # update() calls read() under the hood, which triggers # permission error entity_cls(self.cfg, id=entity.id, name=name).update_json( ['name'] )
Address is 13131 Ginny Lane 32312, it is off Meridian Road , this is a Private drive so please take care on Wednesday, and park responsibly. There will be a sign there for you to see, the Family is downsizing and items are left over that do not fit into the new Home. This is a Moving Sale being listed for one day only Wednesday 2nd July.......from 10 am to 4 pm. All items MUST be removed from the House same day unless other arrangements are made on the day of the Sale, you MUST bring people to help you load as there will be NO ONE to help, as we will not have full compliment of Staff, so PLEASE ensure you make some arrangements that way if you intend buying any of the larger Furniture or Concrete items outside. Two Beautiful Henkel Harris lighted decorated Mahogany Corner Cabinets. These are 48 inches wide at the front, 92 inches tall to top of decorative carved finials, 33 inches deep. Mission Oak Arts and Craft era Library Desk , 45 inches wide, 28 1/2 inches deep, 30 inches high. Contemporary Coffee Table 53 1/2 inches long, 18 inches wide, 24 1/2 inches tall. Asian Screen with bone decorative inserts, 2 hinged panels 27 1/2 inches wide, 87 1/2 inches tall. Large Pensacola Pine and Mahogany Kitchen Cupboard, maginificent piece, comes apart to transport, mirrored door front, 90 inches wide, 26 inches deep, 105 tall, this is a huge piece but so very unusual in that it was made from errant pines that grew in the Pensacola area in the 19th century. Walnut English Server 2 door front, 44 1/2 inches wide, 19 inches deep and 33 inches tall. Decorative Brass Standard Lamp with antique rawhide shade , this is a great piece, heavy also. Mashad 9x7- 15x 5 ft Area Rug , this may not be in the Sale and has a set price, but if you are interested please email or call, being sold on the condition of amount. 12 Royal Albert Old Country Roses Cups and Saucers, also matching two piece Serving tier. Italian First Renaissance Salad plates and Dinner Plates. Some smalls, including some primitives like Cast iron, African American Dolls, Large wooden "marley" style Figurine, Shoe Lasts, Wooden Hat Stands, and more. Engine Hoist, Cast garden decorative items. In the Shed there are some wood turning machinery that you can see covered in spider webs, these will work but have not been used for a while thus the covering...Sears Craftsman Radial Arm Saw, 10 inch Bandsaw, Woodlathe, Grinder Buffer with extended arbors. Also some old cupboards and wood trunks in the Shed, The Buyers will be responsible for moving these. Large Planters, ...check out the photos, the outdoor items will be confirmed by tomorrow, some may be added and some may be taken off so please be observant of the photos and description.
import asyncio import weakref from collections import OrderedDict from envsense.devices import BaseDeviceManager, BaseDevice class LogicDeviceManager(BaseDeviceManager): CONFIG_KEY = 'logics' def __init__(self, app): super(LogicDeviceManager, self).__init__(app) # Add sensors self.items['AlertLogic'] = AlertLogic(app, refresh=0.1) self.items['BuzzerAlertLogic'] = BuzzerAlertLogic(app, refresh=0.5) self.items['LedAlertLogic'] = LedAlertLogic(app, refresh=0.5) from .upm import GasLogic, SoundLogic, UVLogic, LightLogic, TempLogic, TouchLogic self.items['GasLogic'] = GasLogic(app, refresh=0.5) self.items['SoundLogic'] = SoundLogic(app, refresh=0.5) self.items['UVLogic'] = UVLogic(app, refresh=0.5) self.items['LightLogic'] = LightLogic(app, refresh=0.5) self.items['TempLogic'] = TempLogic(app, refresh=0.5) self.items['TouchLogic'] = TouchLogic(app, refresh=0.1) @asyncio.coroutine def start(self): for logic in self.items.values(): asyncio.async(logic.start(), loop=asyncio.get_event_loop()) def factory(app): return LogicDeviceManager(app) class BaseLogic(BaseDevice): def __init__(self, app, refresh=1, *args, **kwargs): self.refresh = refresh self._app = weakref.ref(app) @property def app(self): return self._app() @asyncio.coroutine def start(self): while True: yield from self.do_process() yield from asyncio.sleep(self.refresh) @asyncio.coroutine def do_process(self): pass class BuzzerAlertLogic(BaseLogic): def __init__(self, *args, **kwargs): super(BuzzerAlertLogic, self).__init__(*args, **kwargs) self.active = False self.time = 3 @asyncio.coroutine def do_process(self): actuator = self.app.actuator_manager.items['BuzzerActuator'] import pyupm_buzzer as buzzer if self.active: actuator.chord = buzzer.DO else: actuator.chord = None class LedAlertLogic(BaseLogic): def __init__(self, *args, **kwargs): super(LedAlertLogic, self).__init__(*args, **kwargs) self.active = False @asyncio.coroutine def do_process(self): led_green = self.app.actuator_manager.items['GreenLedActuator'] led_red = self.app.actuator_manager.items['RedLedActuator'] if self.active: led_green.status = False else: led_green.status = True led_red.status = not led_green.status class AlertLogic(BaseLogic): ALERT = 'alert' WARN = 'warning' INFO = 'information' def __init__(self, *args, **kwargs): super(AlertLogic, self).__init__(*args, **kwargs) self.alerts = OrderedDict() self.stop_buffer = False def set_alert(self, device_name, level, text, buzzer=False): if device_name in self.alerts and level == self.ALERT and self.alerts[device_name]['level'] != self.ALERT: self.stop_buffer = False self.alerts[device_name] = {'level': level, 'text': text, 'buzzer': buzzer} def remove_alert(self, device_name): del self.alerts[device_name] @asyncio.coroutine def do_process(self): alerts = [alrt for alrt in self.alerts.values() if alrt['level'] == self.ALERT] warns = [alrt for alrt in self.alerts.values() if alrt['level'] == self.WARN] infos = [alrt for alrt in self.alerts.values() if alrt['level'] == self.INFO] actuator = self.app.actuator_manager.items['DisplayActuator'] if len(alerts): actuator.color = (255, 0, 0) alrt = alerts[0] actuator.line_1 = alrt['text'] if len([a for a in alerts if a['buzzer']]) and not self.stop_buffer: self.app.logic_manager.items['BuzzerAlertLogic'].active = True self.app.logic_manager.items['LedAlertLogic'].active = True elif len(warns): actuator.color = (255, 255, 0) alrt = warns[0] actuator.line_1 = alrt['text'] self.app.logic_manager.items['LedAlertLogic'].active = True self.app.logic_manager.items['BuzzerAlertLogic'].active = False else: actuator.color = (0, 255, 0) if len(infos): alrt = infos[0] actuator.line_1 = alrt['text'] self.app.logic_manager.items['LedAlertLogic'].active = False self.app.logic_manager.items['BuzzerAlertLogic'].active = False actuator.line_2 = "A:{};W:{};I:{}".format(len(alerts), len(warns), len(infos)) def get_structure(self): struct = super(AlertLogic, self).get_structure() struct['functions']['set_alert'] = {'device_name': 'string', 'level': [self.ALERT, self.WARN, self.INFO], 'text': 'string', 'buzzer': 'bool'} struct['functions']['remove_alert'] = {'device_name': 'string'} return struct
Archives | SpaceSports.eu - All Spaceball and Spacebounce players in one place! 67 429 The Future scouts new players! Sub-boards: Team Registration, Spiceball 3v3 Tournament 2014, SpaceHockey Cup 4v4, Spacebounce 1x1 championship, 6-SpaceMAN, Monday Cup, 1v1 Spaceball Tournament(SSN 5), Alternative cup, SpaceBOUNCE, 1v1/2v2 - Spaceball, 1v1 tournament, Spaceball 1v1 Tournament, SpaceHockey 4v4 , Arena #1 "Holiday for all"
__author__ = 'heddevanderheide' import unittest # App specific from networth.mixins import NetworthMixin class TestObject(NetworthMixin): first_name = '' last_name = '' tags = None class Networth: fields = ( ('first_name', (True, 1)), ('last_name', (lambda f: f.startswith('P'), 5)), ('tags', (lambda f: len(f), 'result')), ) def __init__(self, **kwargs): self.first_name = kwargs.get('first_name', '') self.last_name = kwargs.get('last_name', '') self.tags = filter(None, kwargs.get('tags', '').split(',')) def add_tag(self, tag): if self.tags: self.tags.append(tag) else: self.tags = [tag] class TestNetworthMixin(unittest.TestCase): def setUp(self): self.obj_1 = TestObject( first_name='Pete' ) self.obj_2 = TestObject( first_name='Pete', last_name='Philly' ) self.obj_3 = TestObject( first_name='Pete', last_name='Philly', tags='foo' ) def test_obj_1(self): self.assertEqual(self.obj_1.networth(), 2) def test_obj_2(self): self.assertEqual(self.obj_2.networth(), 7) def test_obj_3(self): self.assertEqual(self.obj_3.networth(), 8) self.obj_3.add_tag('bar') self.assertEqual(self.obj_3.networth(), 9)
Republican presidential candidates former Massachusetts Gov. Mitt Romney, left, and Texas Gov. Rick Perry interact during a Republican presidential debate Tuesday, Oct. 18, 2011, in Las Vegas.
# author: Adrian Rosebrock # website: http://www.pyimagesearch.com # USAGE # BE SURE TO INSTALL 'imutils' PRIOR TO EXECUTING THIS COMMAND # python picamera_fps_demo.py # python picamera_fps_demo.py --display 1 # import the necessary packages from __future__ import print_function from imutils.video import VideoStream from imutils.video import FPS from picamera.array import PiRGBArray from picamera import PiCamera import argparse import imutils import time import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-n", "--num-frames", type=int, default=100, help="# of frames to loop over for FPS test") ap.add_argument("-d", "--display", type=int, default=-1, help="Whether or not frames should be displayed") args = vars(ap.parse_args()) # initialize the camera and stream camera = PiCamera() camera.resolution = (320, 240) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(320, 240)) stream = camera.capture_continuous(rawCapture, format="bgr", use_video_port=True) # allow the camera to warmup and start the FPS counter print("[INFO] sampling frames from `picamera` module...") time.sleep(2.0) fps = FPS().start() # loop over some frames for (i, f) in enumerate(stream): # grab the frame from the stream and resize it to have a maximum # width of 400 pixels frame = f.array frame = imutils.resize(frame, width=400) # check to see if the frame should be displayed to our screen if args["display"] > 0: cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # clear the stream in preparation for the next frame and update # the FPS counter rawCapture.truncate(0) fps.update() # check to see if the desired number of frames have been reached if i == args["num_frames"]: break # stop the timer and display FPS information fps.stop() print("[INFO] elasped time: {:.2f}".format(fps.elapsed())) print("[INFO] approx. FPS: {:.2f}".format(fps.fps())) # do a bit of cleanup cv2.destroyAllWindows() stream.close() rawCapture.close() camera.close() # created a *threaded *video stream, allow the camera sensor to warmup, # and start the FPS counter print("[INFO] sampling THREADED frames from `picamera` module...") vs = VideoStream(usePiCamera=True).start() time.sleep(2.0) fps = FPS().start() # loop over some frames...this time using the threaded stream while fps._numFrames < args["num_frames"]: # grab the frame from the threaded video stream and resize it # to have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=400) # check to see if the frame should be displayed to our screen if args["display"] > 0: cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # update the FPS counter fps.update() # stop the timer and display FPS information fps.stop() print("[INFO] elasped time: {:.2f}".format(fps.elapsed())) print("[INFO] approx. FPS: {:.2f}".format(fps.fps())) # do a bit of cleanup cv2.destroyAllWindows() vs.stop()
Asset Integrity Management (AIM) studies and Residual Life Assessment (RLA) are key activities for operators who want to demonstrate whether in-service pressure equipment or structures are fit for operation and their specific purpose. The objective of an AIM is to assess and verify the current level of the asset integrity and to identify and assess options to define/increase the asset’s residual life. The assessment and verification shall be based on the current conditions and future foreseeable conditions. A structure’s corrosion rates and patterns will be developed to verify the effect on maximum allowable operating conditions. We offer expertise and skills in mechanical, structural, material, corrosion engineering and mechanic engineering, providing proven proficiency in stress analysis, degradation mechanism analysis, inspection data analysis, failure risk assessment and repair techniques. The remaining design life assessment is a consequence of these results and their interpretation by the above skilled personnel.
#adapted from the example at http://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html """ This script can be used to get the p value for classifiers. It takes input files with column vectors corresponding to features and lables. Then there are two different routes one can go down. When mode has a value of 1, then a grid search will be performed on one set of input files. If it is 2, then the hyperparemeter search is performed by spearmint. When the mode is turned off (0), then the p value is computed for multiple sets of input files and the p value distribution is plotted. One sets all the valiables including the classifier in the "args" list. The classifier provided is ignored if keras_mode is on (1) in which case a keras neural network is used. """ from __future__ import print_function print(__doc__) import os import p_value_scoring_object import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import Normalize from sklearn import cross_validation from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from sklearn.datasets import load_iris from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.grid_search import GridSearchCV ############################################################################## # Utility function to move the midpoint of a colormap to be around # the values of interest. class MidpointNormalize(Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) def classifier_eval(mode,keras_mode,args): ############################################################################## # Setting parameters # name=args[0] sample1_name= args[1] sample2_name= args[2] shuffling_seed = args[3] #mode =0 if you want evaluation of a model =1 if grid hyperparameter search =2 if spearmint hyperparameter search comp_file_list=args[4] print(comp_file_list) cv_n_iter = args[5] clf = args[6] C_range = args[7] gamma_range = args[8] if mode==0: #For standard evaluation score_list=[] print("standard evaluation mode") elif mode==1: #For grid search print("grid hyperparameter search mode") param_grid = dict(gamma=gamma_range, C=C_range) elif mode==2: #For spearmint hyperparameter search print("spearmint hyperparameter search mode") else: print("No valid mode chosen") return 1 ############################################################################## # Load and prepare data set # # dataset for grid search for comp_file_0,comp_file_1 in comp_file_list: print("Operating of files :"+comp_file_0+" "+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d') features_1=np.loadtxt(comp_file_1,dtype='d') #determine how many data points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] #Give all samples in file 0 the label 0 and in file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] data=np.r_[data_0,data_1] np.random.shuffle(data) X=data[:,:-1] y=data[:,-1] acv = StratifiedShuffleSplit(y, n_iter=cv_n_iter, test_size=0.2, random_state=42) print(X) print(y) # It is usually a good idea to scale the data for SVM training. # We are cheating a bit in this example in scaling all of the data, # instead of fitting the transformation on the training set and # just applying it on the test set. scaler = StandardScaler() X = scaler.fit_transform(X) if mode==1: ############################################################################## # Grid Search # # Train classifiers # # For an initial search, a logarithmic grid with basis # 10 is often helpful. Using a basis of 2, a finer # tuning can be achieved but at a much higher cost. grid = GridSearchCV(clf, scoring=p_value_scoring_object.p_value_scoring_object ,param_grid=param_grid, cv=acv) grid.fit(X, y) print("The best parameters are %s with a score of %0.2f" % (grid.best_params_, grid.best_score_)) # Now we need to fit a classifier for all parameters in the 2d version # (we use a smaller set of parameters here because it takes a while to train) C_2d_range = [1e-2, 1, 1e2] gamma_2d_range = [1e-1, 1, 1e1] classifiers = [] for C in C_2d_range: for gamma in gamma_2d_range: clf = SVC(C=C, gamma=gamma) clf.fit(X_2d, y_2d) classifiers.append((C, gamma, clf)) ############################################################################## # visualization # # draw visualization of parameter effects plt.figure(figsize=(8, 6)) xx, yy = np.meshgrid(np.linspace(-3, 3, 200), np.linspace(-3, 3, 200)) for (k, (C, gamma, clf)) in enumerate(classifiers): # evaluate decision function in a grid Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # visualize decision function for these parameters plt.subplot(len(C_2d_range), len(gamma_2d_range), k + 1) plt.title("gamma=10^%d, C=10^%d" % (np.log10(gamma), np.log10(C)),size='medium') # visualize parameter's effect on decision function plt.pcolormesh(xx, yy, -Z, cmap=plt.cm.RdBu) plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y_2d, cmap=plt.cm.RdBu_r) plt.xticks(()) plt.yticks(()) plt.axis('tight') plt.savefig('prediction_comparison.png') # plot the scores of the grid # grid_scores_ contains parameter settings and scores # We extract just the scores scores = [x[1] for x in grid.grid_scores_] scores = np.array(scores).reshape(len(C_range), len(gamma_range)) # Draw heatmap of the validation accuracy as a function of gamma and C # # The score are encoded as colors with the hot colormap which varies from dark # red to bright yellow. As the most interesting scores are all located in the # 0.92 to 0.97 range we use a custom normalizer to set the mid-point to 0.92 so # as to make it easier to visualize the small variations of score values in the # interesting range while not brutally collapsing all the low score values to # the same color. plt.figure(figsize=(8, 6)) plt.subplots_adjust(left=.2, right=0.95, bottom=0.15, top=0.95) plt.imshow(scores, interpolation='nearest', cmap=plt.cm.hot, norm=MidpointNormalize(vmin=-1.0, midpoint=-0.0001)) plt.xlabel('gamma') plt.ylabel('C') plt.colorbar() plt.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45) plt.yticks(np.arange(len(C_range)), C_range) plt.title('Validation accuracy') plt.savefig('Heat_map.png') else: if keras_mode==1: from keras.utils import np_utils, generic_utils dimof_output = len(set(y.flat)) y = np_utils.to_categorical(y, dimof_output) print("delete this line") print(X) print(y) scores = cross_validation.cross_val_score(clf,X,y,cv=acv,scoring=p_value_scoring_object.p_value_scoring_object) print(scores) score_list.append(np.mean(scores)) if mode==2: return (-1)* np.mean(scores) ############################################################################################################################################################ ############################################################### Evaluation of results #################################################################### ############################################################################################################################################################ if mode==0: # The score list has been computed. Let's plot the distribution print(score_list) print("I havent implemented plotting of the distribution") if __name__ == "__main__": print("Executing classifier_eval_simplified as a stand-alone script") print() comp_file_list=[] for i in range(1,100): comp_file_list.append((os.environ['MLToolsDir']+"/Dalitz/dpmodel/data/data.{0}.0.txt".format(i), os.environ['MLToolsDir']+"/Dalitz/dpmodel/data/data.2{0}.1.txt".format(str(i).zfill(2)))) #clf = SVC(C=100,gamma=0.1,probability=True, cache_size=7000) from model import MLP clf = MLP(n_hidden=500, n_deep=7, l1_norm=0, drop=0.5, verbose=0) args=["dalitz","particle","antiparticle",100,comp_file_list,2,clf,np.logspace(-2, 10, 13),np.logspace(-9, 3, 13)] #classifier_eval_simplified(aC,agamma) classifier_eval(0,0,args)
What happens to Items in the Trash? Items that you Toss are moved to the Trash. Click on the Trashcan box to see what has been tossed. You can Restore the item(s) from the Trash or you can empty the Trash. Your password is required when emptying the trash, because Items are not retrievable after the Trash has been emptied.
#!/usr/bin/env python """ PlexConnect Sources: inter-process-communication (queue): http://pymotw.com/2/multiprocessing/communication.html """ import sys, time from os import sep import socket from multiprocessing import Process, Pipe from multiprocessing.managers import BaseManager import signal, errno from Version import __VERSION__ import DNSServer, WebServer import Settings, ATVSettings from PILBackgrounds import isPILinstalled from Debug import * # dprint() def getIP_self(): cfg = param['CSettings'] if cfg.getSetting('enable_plexconnect_autodetect')=='True': # get public ip of machine running PlexConnect s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('1.2.3.4', 1000)) IP = s.getsockname()[0] dprint('PlexConnect', 0, "IP_self: "+IP) else: # manual override from "settings.cfg" IP = cfg.getSetting('ip_plexconnect') dprint('PlexConnect', 0, "IP_self (from settings): "+IP) return IP # initializer for Manager, proxy-ing ATVSettings to WebServer/XMLConverter def initProxy(): signal.signal(signal.SIGINT, signal.SIG_IGN) procs = {} pipes = {} param = {} running = False def startup(): global procs global pipes global param global running # Settings cfg = Settings.CSettings() param['CSettings'] = cfg # Logfile if cfg.getSetting('logpath').startswith('.'): # relative to current path logpath = sys.path[0] + sep + cfg.getSetting('logpath') else: # absolute path logpath = cfg.getSetting('logpath') param['LogFile'] = logpath + sep + 'PlexConnect.log' param['LogLevel'] = cfg.getSetting('loglevel') dinit('PlexConnect', param, True) # init logging, new file, main process dprint('PlexConnect', 0, "Version: {0}", __VERSION__) dprint('PlexConnect', 0, "Python: {0}", sys.version) dprint('PlexConnect', 0, "Host OS: {0}", sys.platform) dprint('PlexConnect', 0, "PILBackgrounds: Is PIL installed? {0}", isPILinstalled()) # more Settings param['IP_self'] = getIP_self() param['HostToIntercept'] = cfg.getSetting('hosttointercept') param['baseURL'] = 'http://'+ param['HostToIntercept'] # proxy for ATVSettings proxy = BaseManager() proxy.register('ATVSettings', ATVSettings.CATVSettings) proxy.start(initProxy) param['CATVSettings'] = proxy.ATVSettings() running = True # init DNSServer if cfg.getSetting('enable_dnsserver')=='True': master, slave = Pipe() # endpoint [0]-PlexConnect, [1]-DNSServer proc = Process(target=DNSServer.Run, args=(slave, param)) proc.start() time.sleep(0.1) if proc.is_alive(): procs['DNSServer'] = proc pipes['DNSServer'] = master else: dprint('PlexConnect', 0, "DNSServer not alive. Shutting down.") running = False # init WebServer if running: master, slave = Pipe() # endpoint [0]-PlexConnect, [1]-WebServer proc = Process(target=WebServer.Run, args=(slave, param)) proc.start() time.sleep(0.1) if proc.is_alive(): procs['WebServer'] = proc pipes['WebServer'] = master else: dprint('PlexConnect', 0, "WebServer not alive. Shutting down.") running = False # init WebServer_SSL if running and \ cfg.getSetting('enable_webserver_ssl')=='True': master, slave = Pipe() # endpoint [0]-PlexConnect, [1]-WebServer proc = Process(target=WebServer.Run_SSL, args=(slave, param)) proc.start() time.sleep(0.1) if proc.is_alive(): procs['WebServer_SSL'] = proc pipes['WebServer_SSL'] = master else: dprint('PlexConnect', 0, "WebServer_SSL not alive. Shutting down.") running = False # not started successful - clean up if not running: cmdShutdown() shutdown() return running def run(timeout=60): # do something important try: time.sleep(timeout) except IOError as e: if e.errno == errno.EINTR and not running: pass # mask "IOError: [Errno 4] Interrupted function call" else: raise return running def shutdown(): for slave in procs: procs[slave].join() param['CATVSettings'].saveSettings() dprint('PlexConnect', 0, "shutdown") def cmdShutdown(): global running running = False # send shutdown to all pipes for slave in pipes: pipes[slave].send('shutdown') dprint('PlexConnect', 0, "Shutting down.") def sighandler_shutdown(signum, frame): signal.signal(signal.SIGINT, signal.SIG_IGN) # we heard you! cmdShutdown() if __name__=="__main__": signal.signal(signal.SIGINT, sighandler_shutdown) signal.signal(signal.SIGTERM, sighandler_shutdown) dprint('PlexConnect', 0, "***") dprint('PlexConnect', 0, "PlexConnect") dprint('PlexConnect', 0, "Press CTRL-C to shut down.") dprint('PlexConnect', 0, "***") running = startup() while running: running = run() shutdown()
Back by popular demand! Scott C’s Great Showdowns v2 After a lightning fast sell out at this years San Diego Comic Con, Scott C.’s eager fans will have another chance at version 2. This revised version will have a neon green ghost and a more accurate color scheme for our favorite ghost chaser’s outfit. The Great Showdowns is the smash hit online series that we have seen in art shows and books depicting classic moments of great tension between characters in some of the greatest films of all time. This the very first figure ever to be created of Scott C's work and the first in a series of Great Showdowns themed toys. This figure was sculpted by George Gaspar of Double G toys who helped bring Scott C’s characters to life. This is a pre-order for figurines ONLY. Please place separate orders for additional Scott C merchandise. Ordering will be open for 14 days or while supplies last. Expect delivery around February 2018.
# Copyright 2016 Internap # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Router(object): def __init__(self, env_as_kwarg=True): self.env_as_kwarg = env_as_kwarg def invoke_method(self, module, method, params=None, env=None, callback=None): if params is None: params = [] if env is None: env = {} if self.env_as_kwarg: additional_kwargs = {'env': env} else: additional_kwargs = {} return getattr(module, method)(*params, **additional_kwargs) def list_implemented_methods(self, module): return [method for method in dir(module) if callable(getattr(module, method)) and not method.startswith('_')]
Dennis was born June 23, 1947 in Preston, Lancashire. He grew up and attended local schools in Fulwood and Lea, Preston. He served his apprenticeship as a fitter-turner at Thomas Dryden and Sons, Preston from 1961-1968. After gaining Journeyman status, he worked on several paper mill and power station shutdowns in the U.K. He began racing in 1969 and continued to 1971, with his highpoint being his races in the MGP in 1970 and 1971. Dennis left for Canada, on his own, in May, 1972. He worked at Saint John Shipbuilding, Saint John, New Brunswick from this time until it closed in 2000. At this time he began work with Steel and Engine Products (STENPRO), in Liverpool, Nova Scotia as Special Projects Supervisor, including ship repair. Dennis married his wife Marlene in 1974, became a Canadian citizen in 1979 and has a daughter, Sara born in 1980. In the fall of 2001 he and his wife moved from Hampton, New Brunswick to Milton, on the Mersey River, just outside Liverpool, Nova Scotia.
""" Contains filepath, a path representation class $Id: """ import os from musexceptions import * class FilePath(object): """A class that represents a file path. It also provides some useful and common methods regarding paths. We pass around paths as encoded strings (not unicode) by default because then we can work with files with unknown encoding. """ def __init__(self, path, *filep, **kwargs): ''' Pass in unicode keyword to set encoding for returning unicode strings on unicode(fp) or getName(unicode=True). ''' assert not isinstance(path, unicode), 'FilePaths should be passed around encoded' for p in filep: assert not isinstance(p, unicode), 'FilePaths should be passed around encoded' if 'encoding' in kwargs: self.encoding = kwargs['encoding'] else: self.encoding = 'ascii' if isinstance(path, FilePath): path = path.fullpath else: path = os.path.abspath(path) if len(filep) > 0: path = os.path.join(path, *filep) self.fullpath = path def getName(self, unicode=False): s = os.path.basename(self.fullpath) if unicode: s = self.decode(s) return s def getParent(self): return FilePath(os.path.dirname(self.fullpath)) def getExt(self): return os.path.splitext(self.fullpath)[1] def getFileType(self): return self.getExt()[1:].lower() def __add__(self, other): return FilePath(self, other) def __len__(self): return len(self.fullpath) def __str__(self): s = self.fullpath return s def decode(self, s): try: s = s.decode(self.encoding) except Exception, e: print NamingMuseWarning('failed to decode path %s with encoding %s' % (s, self.encoding)) s = s.decode(self.encoding, 'ignore') return s def __unicode__(self): return self.decode(self.fullpath) def __repr__(self): return self.__str__() def __cmp__(self, other): if not isinstance(other, (FilePath, basestring)): raise TypeError(\ "can't compare FilePath with non-FilePath/string object") if isinstance(other, FilePath): other = other.fullpath return cmp(self.fullpath, other) def rename(self, dst): return os.rename(str(self), str(dst)) def mkdir(self): return os.mkdir(str(self)) def rmdir(self): return os.rmdir(str(self)) def exists(self): return os.path.exists(str(self)) def isdir(self): return os.path.isdir(str(self)) def listdir(self): return os.listdir(str(self)) def walk(self): for x in os.walk(str(self)): yield x
Sweet little story about a single mom and a guy who suddenly learns he's a dad. Set in Desperation, Oklahoma. I enjoyed it. I gave this book three stars - it was an okay read but it was slow, lacked detail and I didn't really feel the story went anywhere. It is kind of slow for me and there was not too much detail. Overall an okay read. Bachelor Dad by Roxann Delaney is a good, quick read, perfect for those with limited time for reading.
from common import PrassError import bisect import math def parse_scxvid_keyframes(text): return [i-3 for i,line in enumerate(text.splitlines()) if line and line[0] == 'i'] def parse_keyframes(path): with open(path) as file_object: text = file_object.read() if text.find('# XviD 2pass stat file')>=0: frames = parse_scxvid_keyframes(text) else: raise PrassError('Unsupported keyframes type') if 0 not in frames: frames.insert(0, 0) return frames class Timecodes(object): TIMESTAMP_END = 1 TIMESTAMP_START = 2 def __init__(self, times, default_fps): super(Timecodes, self).__init__() self.times = times self.default_frame_duration = 1000.0 / default_fps if default_fps else None def get_frame_time(self, number, kind=None): if kind == self.TIMESTAMP_START: prev = self.get_frame_time(number-1) curr = self.get_frame_time(number) return prev + int(round((curr - prev) / 2.0)) elif kind == self.TIMESTAMP_END: curr = self.get_frame_time(number) after = self.get_frame_time(number+1) return curr + int(round((after - curr) / 2.0)) try: return self.times[number] except IndexError: if not self.default_frame_duration: raise ValueError("Cannot calculate frame timestamp without frame duration") past_end, last_time = number, 0 if self.times: past_end, last_time = (number - len(self.times) + 1), self.times[-1] return int(round(past_end * self.default_frame_duration + last_time)) def get_frame_number(self, ms, kind=None): if kind == self.TIMESTAMP_START: return self.get_frame_number(ms - 1) + 1 elif kind == self.TIMESTAMP_END: return self.get_frame_number(ms - 1) if self.times and self.times[-1] >= ms: return bisect.bisect_left(self.times, ms) if not self.default_frame_duration: raise ValueError("Cannot calculate frame for this timestamp without frame duration") if ms < 0: return int(math.floor(ms / self.default_frame_duration)) last_time = self.times[-1] if self.times else 0 return int((ms - last_time) / self.default_frame_duration) + len(self.times) @classmethod def _convert_v1_to_v2(cls, default_fps, overrides): # start, end, fps overrides = [(int(x[0]), int(x[1]), float(x[2])) for x in overrides] if not overrides: return [] fps = [default_fps] * (overrides[-1][1] + 1) for start, end, fps in overrides: fps[start:end + 1] = [fps] * (end - start + 1) v2 = [0] for d in (1000.0 / f for f in fps): v2.append(v2[-1] + d) return v2 @classmethod def parse(cls, text): lines = text.splitlines() if not lines: return [] first = lines[0].lower().lstrip() if first.startswith('# timecode format v2'): tcs = [x for x in lines[1:]] return Timecodes(tcs, None) elif first.startswith('# timecode format v1'): default = float(lines[1].lower().replace('assume ', "")) overrides = (x.split(',') for x in lines[2:]) return Timecodes(cls._convert_v1_to_v2(default, overrides), default) else: raise PrassError('This timecodes format is not supported') @classmethod def from_file(cls, path): with open(path) as file: return cls.parse(file.read()) @classmethod def cfr(cls, fps): return Timecodes([], default_fps=fps)
Future Genetics is committed to high quality and innovative genomics research. Our Research Scientist, Lucy Field, will be attending the Lab Innovations 2018 Conference at the NEC this week (31 Oct). She looks forward to meeting you all and learning from all the exciting exhibitions which will be showcased. Future Genetics will be looking for new and innovative technologies that can help us accelerate our research in genomics, medicine and patient healthcare.
#!/usr/bin/env python3 """ Make a compressed archive in TAR.XZ format. """ import argparse import glob import os import shutil import signal import sys from typing import List import command_mod import subtask_mod class Options: """ Options class """ def __init__(self) -> None: self._args: argparse.Namespace = None self.parse(sys.argv) def get_archive(self) -> str: """ Return archive location. """ return self._archive def get_tar(self) -> command_mod.Command: """ Return tar Command class object. """ return self._tar def _parse_args(self, args: List[str]) -> None: parser = argparse.ArgumentParser( description='Make a compressed archive in TAR.XZ format.', ) parser.add_argument( 'archive', nargs=1, metavar='file.tar.xz|file.txz', help='Archive file.' ) parser.add_argument( 'files', nargs='*', metavar='file', help='File or directory.' ) self._args = parser.parse_args(args) def parse(self, args: List[str]) -> None: """ Parse arguments """ self._parse_args(args[1:]) if os.path.isdir(self._args.archive[0]): self._archive = os.path.abspath(self._args.archive[0]) + '.tar.xz' else: self._archive = self._args.archive[0] if not self._archive.endswith(('.tar.xz', '.txz')): raise SystemExit( sys.argv[0] + ': Unsupported "' + self._archive + '" archive format.' ) if self._args.files: self._files = self._args.files else: self._files = os.listdir() self._tar = command_mod.Command('tar', errors='stop') self._tar.set_args(['cfv', self._archive+'.part'] + self._files) self._tar.extend_args([ '--use-compress-program', 'xz -9 -e --x86 --lzma2=dict=128MiB --threads=1 --verbose', '--owner=0:0', '--group=0:0', '--sort=name', ]) class Main: """ Main class """ def __init__(self) -> None: try: self.config() sys.exit(self.run()) except (EOFError, KeyboardInterrupt): sys.exit(114) except SystemExit as exception: sys.exit(exception) @staticmethod def config() -> None: """ Configure program """ if hasattr(signal, 'SIGPIPE'): signal.signal(signal.SIGPIPE, signal.SIG_DFL) if os.name == 'nt': argv = [] for arg in sys.argv: files = glob.glob(arg) # Fixes Windows globbing bug if files: argv.extend(files) else: argv.append(arg) sys.argv = argv @staticmethod def run() -> int: """ Start program """ options = Options() archive = options.get_archive() os.umask(int('022', 8)) task = subtask_mod.Task(options.get_tar().get_cmdline()) task.run() try: if task.get_exitcode(): raise OSError shutil.move(archive+'.part', archive) except OSError as exception: raise SystemExit( '{0:s}: Cannot create "{1:s}" archive file.'.format( sys.argv[0], archive ) ) from exception return 0 if __name__ == '__main__': if '--pydoc' in sys.argv: help(__name__) else: Main()
Well made mechanical keyboards are usually on the thick and heavy side. “Built like a tank” is a term often thrown around when describing them. It’s this perceived build quality that’s one of the major reasons many users are initially drawn to mechanical keyboards. You may already be familiar with the Chinese brand Xiaomi due in part to their popular line of affordable smartphones. Believe it or not they’re the 5th largest producer of smartphones in the world, behind juggernauts Samsung and Apple. The Obins Anne Pro has created a lot of positive hype in the keyboard community. I know it’s been on my radar for the past 5 months or so. A 60% mechanical keyboard with wireless support (Bluetooth 4.0), true RGB backlighting, Gateron switches and PBT keycaps for only $80. Sign me up! I have a special mechanical keyboard up for review today. The Vortex CORE could end up being a pioneer for 40% form factor keyboards and the future mech market. What makes it so unique? The CORE is not a kit that requires soldering skills for a complex assembly process. It’s not a custom you design and build yourself from the ground up based on a specific PCB. The Vortex CORE is the first mass produced, fully assembled 40% mechanical keyboard for the “mainstream” retail market.
import datetime import atexit import signal from ..api import API from .bot_get import get_media_owner, get_your_medias, get_user_medias from .bot_get import get_timeline_medias, get_hashtag_medias, get_user_info from .bot_get import get_geotag_medias, get_timeline_users, get_hashtag_users from .bot_get import get_media_commenters, get_userid_from_username from .bot_get import get_user_followers, get_user_following, get_media_likers from .bot_get import get_media_comments, get_geotag_users, convert_to_user_id from .bot_get import get_comment, get_media_info, get_user_likers from .bot_like import like, like_medias, like_timeline, like_user, like_users from .bot_like import like_hashtag, like_geotag, like_followers, like_following from .bot_unlike import unlike, unlike_medias, unlike_user from .bot_follow import follow, follow_users, follow_followers, follow_following from .bot_unfollow import unfollow, unfollow_users, unfollow_non_followers from .bot_unfollow import unfollow_everyone from .bot_comment import comment, comment_medias, comment_geotag, comment_users from .bot_comment import comment_hashtag, is_commented from .bot_block import block, unblock, block_users, unblock_users, block_bots from .bot_checkpoint import save_checkpoint, load_checkpoint from .bot_filter import filter_medias, check_media, filter_users, check_user from .bot_filter import check_not_bot from .bot_support import check_if_file_exists, read_list_from_file from .bot_support import add_whitelist, add_blacklist from .bot_stats import save_user_stats class Bot(API): def __init__(self, whitelist=False, blacklist=False, comments_file=False, max_likes_per_day=1000, max_unlikes_per_day=1000, max_follows_per_day=350, max_unfollows_per_day=350, max_comments_per_day=100, max_blocks_per_day=100, max_unblocks_per_day=100, max_likes_to_like=100, filter_users=True, max_followers_to_follow=2000, min_followers_to_follow=10, max_following_to_follow=2000, min_following_to_follow=10, max_followers_to_following_ratio=10, max_following_to_followers_ratio=2, min_media_count_to_follow=3, max_following_to_block=2000, like_delay=10, unlike_delay=10, follow_delay=30, unfollow_delay=30, comment_delay=60, block_delay=30, unblock_delay=30, stop_words=['shop', 'store', 'free']): super(self.__class__, self).__init__() self.total_liked = 0 self.total_unliked = 0 self.total_followed = 0 self.total_unfollowed = 0 self.total_commented = 0 self.total_blocked = 0 self.total_unblocked = 0 self.start_time = datetime.datetime.now() # limits - follow self.filter_users = filter_users self.max_likes_per_day = max_likes_per_day self.max_unlikes_per_day = max_unlikes_per_day self.max_follows_per_day = max_follows_per_day self.max_unfollows_per_day = max_unfollows_per_day self.max_comments_per_day = max_comments_per_day self.max_blocks_per_day = max_blocks_per_day self.max_unblocks_per_day = max_unblocks_per_day self.max_likes_to_like = max_likes_to_like self.max_followers_to_follow = max_followers_to_follow self.min_followers_to_follow = min_followers_to_follow self.max_following_to_follow = max_following_to_follow self.min_following_to_follow = min_following_to_follow self.max_followers_to_following_ratio = max_followers_to_following_ratio self.max_following_to_followers_ratio = max_following_to_followers_ratio self.min_media_count_to_follow = min_media_count_to_follow self.stop_words = stop_words # limits - block self.max_following_to_block = max_following_to_block # delays self.like_delay = like_delay self.unlike_delay = unlike_delay self.follow_delay = follow_delay self.unfollow_delay = unfollow_delay self.comment_delay = comment_delay self.block_delay = block_delay self.unblock_delay = unblock_delay # current following self.following = [] # white and blacklists self.whitelist = [] if whitelist: self.whitelist = read_list_from_file(whitelist) self.blacklist = [] if blacklist: self.blacklist = read_list_from_file(blacklist) # comment file self.comments = [] if comments_file: self.comments = read_list_from_file(comments_file) self.logger.info('Instabot Started') def version(self): from pip._vendor import pkg_resources return next((p.version for p in pkg_resources.working_set if p.project_name.lower() == 'instabot'), "No match") def logout(self): save_checkpoint(self) super(self.__class__, self).logout() self.logger.info("Bot stopped. " "Worked: %s" % (datetime.datetime.now() - self.start_time)) self.print_counters() def login(self, **args): super(self.__class__, self).login(**args) self.prepare() signal.signal(signal.SIGTERM, self.logout) atexit.register(self.logout) def prepare(self): storage = load_checkpoint(self) if storage is not None: self.total_liked, self.total_unliked, self.total_followed, self.total_unfollowed, self.total_commented, self.total_blocked, self.total_unblocked, self.total_requests, self.start_time = storage self.whitelist = list( filter(None, map(self.convert_to_user_id, self.whitelist))) self.blacklist = list( filter(None, map(self.convert_to_user_id, self.blacklist))) def print_counters(self): if self.total_liked: self.logger.info("Total liked: %d" % self.total_liked) if self.total_unliked: self.logger.info("Total unliked: %d" % self.total_unliked) if self.total_followed: self.logger.info("Total followed: %d" % self.total_followed) if self.total_unfollowed: self.logger.info("Total unfollowed: %d" % self.total_unfollowed) if self.total_commented: self.logger.info("Total commented: %d" % self.total_commented) if self.total_blocked: self.logger.info("Total blocked: %d" % self.total_blocked) if self.total_unblocked: self.logger.info("Total unblocked: %d" % self.total_unblocked) self.logger.info("Total requests: %d" % self.total_requests) # getters def get_your_medias(self): return get_your_medias(self) def get_timeline_medias(self): return get_timeline_medias(self) def get_user_medias(self, user_id, filtration=True): return get_user_medias(self, user_id, filtration) def get_hashtag_medias(self, hashtag, filtration=True): return get_hashtag_medias(self, hashtag, filtration) def get_geotag_medias(self, geotag, filtration=True): return get_geotag_medias(self, geotag, filtration) def get_media_info(self, media_id): return get_media_info(self, media_id) def get_timeline_users(self): return get_timeline_users(self) def get_hashtag_users(self, hashtag): return get_hashtag_users(self, hashtag) def get_geotag_users(self, geotag): return get_geotag_users(self, geotag) def get_userid_from_username(self, username): return get_userid_from_username(self, username) def get_user_info(self, user_id): return get_user_info(self, user_id) def get_user_followers(self, user_id): return get_user_followers(self, user_id) def get_user_following(self, user_id): return get_user_following(self, user_id) def get_media_likers(self, media_id): return get_media_likers(self, media_id) def get_media_comments(self, media_id): return get_media_comments(self, media_id) def get_comment(self): return get_comment(self) def get_media_commenters(self, media_id): return get_media_commenters(self, media_id) def get_media_owner(self, media): return get_media_owner(self, media) def get_user_likers(self, user_id, media_count=10): return get_user_likers(self, user_id, media_count) def convert_to_user_id(self, usernames): return convert_to_user_id(self, usernames) # like def like(self, media_id): return like(self, media_id) def like_medias(self, media_ids): return like_medias(self, media_ids) def like_timeline(self, amount=None): return like_timeline(self, amount) def like_user(self, user_id, amount=None): return like_user(self, user_id, amount) def like_hashtag(self, hashtag, amount=None): return like_hashtag(self, hashtag, amount) def like_geotag(self, geotag, amount=None): return like_geotag(self, geotag, amount) def like_users(self, user_ids, nlikes=None): return like_users(self, user_ids, nlikes) def like_followers(self, user_id, nlikes=None): return like_followers(self, user_id, nlikes) def like_following(self, user_id, nlikes=None): return like_following(self, user_id, nlikes) # unlike def unlike(self, media_id): return unlike(self, media_id) def unlike_medias(self, media_ids): return unlike_medias(self, media_ids) def unlike_user(self, user): return unlike_user(self, user) # follow def follow(self, user_id): return follow(self, user_id) def follow_users(self, user_ids): return follow_users(self, user_ids) def follow_followers(self, user_id): return follow_followers(self, user_id) def follow_following(self, user_id): return follow_following(self, user_id) # unfollow def unfollow(self, user_id): return unfollow(self, user_id) def unfollow_users(self, user_ids): return unfollow_users(self, user_ids) def unfollow_non_followers(self): return unfollow_non_followers(self) def unfollow_everyone(self): return unfollow_everyone(self) # comment def comment(self, media_id, comment_text): return comment(self, media_id, comment_text) def comment_hashtag(self, hashtag): return comment_hashtag(self, hashtag) def comment_medias(self, medias): return comment_medias(self, medias) def comment_users(self, user_ids): return comment_users(self, user_ids) def comment_geotag(self, geotag): return comment_geotag(self, geotag) def is_commented(self, media_id): return is_commented(self, media_id) # block def block(self, user_id): return block(self, user_id) def unblock(self, user_id): return unblock(self, user_id) def block_users(self, user_ids): return block_users(self, user_ids) def unblock_users(self, user_ids): return unblock_users(self, user_ids) def block_bots(self): return block_bots(self) # filter def filter_medias(self, media_items, filtration=True): return filter_medias(self, media_items, filtration) def check_media(self, media): return check_media(self, media) def check_user(self, user, filter_closed_acc=False): return check_user(self, user, filter_closed_acc) def check_not_bot(self, user): return check_not_bot(self, user) def filter_users(self, user_id_list): return filter_users(self, user_id_list) # support def check_if_file_exists(self, file_path): return check_if_file_exists(file_path) def read_list_from_file(self, file_path): return read_list_from_file(file_path) def add_whitelist(self, file_path): return add_whitelist(self, file_path) def add_blacklist(self, file_path): return add_blacklist(self, file_path) # stats def save_user_stats(self, username): return save_user_stats(self, username)
I took my biology final today and, after having a cupcake (from Back to Eden) and tea (from Townshend's) with my classmate, I went to New Seasons and enjoyed exploring the store with no time limitations. Wholesome Sweeteners Maple-flavored Agave Syrup: has anyone tried this? it's really intriguing to me, and it only has two ingredients - the agave and its flavor - so it seems to retain all the health benefits of normal agave. I'll let you know what I think after trying it in tomorrow morning's oatmeal!
import numpy as np from copy import copy from pele.potentials import BasePotential import networkx as nx __all__ = ["XYModel"] def angle_to_2dvector(theta): return np.cos(theta), np.sin(theta) class XYModel(BasePotential): """ XY model of 2d spins on a lattice """ def __init__(self, dim=None, phi=np.pi, periodic=True, phases=None): if not dim: dim = [4, 4] dim = copy(dim) self.dim = copy(dim) self.nspins = np.prod(dim) self.G = nx.grid_graph(dim, periodic) if phases is not None: self.phases = phases else: self.phases = dict() binary_disorder = True if binary_disorder: for edge in self.G.edges(): self.phases[edge] = phi * np.random.random_integers(0, 1) else: for edge in self.G.edges(): self.phases[edge] = np.random.uniform(-phi, phi) nx.set_edge_attributes(self.G, "phase", self.phases) self.indices = dict() self.index2node = dict() nodes = sorted(self.G.nodes()) for i, node in enumerate(nodes): self.indices[node] = i self.index2node[i] = node self.num_edges = self.G.number_of_edges() self.set_up_neighborlists() def get_phases(self): return self.phases.copy() def set_up_neighborlists(self): neighbors = [] self.phase_matrix = np.zeros([self.nspins, self.nspins]) for edge in self.G.edges(): u = self.indices[edge[0]] v = self.indices[edge[1]] neighbors.append([u, v]) self.phase_matrix[u, v] = self.phases[edge] self.phase_matrix[v, u] = self.phases[edge] self.neighbors = np.array(neighbors).reshape([-1, 2]) def get_spin_energies(self, angles): """return the local energy of each spin""" energies = np.zeros(angles.size) for edge in self.G.edges(): phase = self.phases[edge] u = self.indices[edge[0]] v = self.indices[edge[1]] E = -np.cos(-angles[u] + angles[v] + phase) energies[u] += E energies[v] += E return energies def getEnergy(self, angles): e, g = self.getEnergyGradient(angles) return e def getEnergyGradient(self, angles): import _cython_tools return _cython_tools.xymodel_energy_gradient(angles, self.phase_matrix, self.neighbors) # def getEnergyGradient(self, angles): # # do internal energies first # E = 0. # grad = np.zeros(self.nspins) # for edge in self.G.edges(): # phase = self.phases[edge] # u = self.indices[edge[0]] # v = self.indices[edge[1]] # E += np.cos( -angles[u] + angles[v] + phase ) # # g = -np.sin( -angles[u] + angles[v] + phase ) # grad[u] += g # grad[v] += -g # E = - E # return E, grad #def test_basin_hopping(pot, angles): # from pele.basinhopping import BasinHopping # from pele.takestep.displace import RandomDisplacement # from pele.takestep.adaptive import AdaptiveStepsize # # takestep = RandomDisplacement(stepsize = np.pi/4) # takestepa = AdaptiveStepsize(takestep, frequency = 20) # # bh = BasinHopping( angles, pot, takestepa, temperature = 1.01) # bh.run(20) # #def test(): # pi = np.pi # L = 3 # nspins = L**2 # # #phases = np.zeros(nspins) # pot = XYModel( dim = [L,L], phi = np.pi) #, phases=phases) # # # angles = np.random.uniform(-pi, pi, nspins) # print angles # # e = pot.getEnergy(angles) # print "energy ", e # # print "numerical gradient" # ret = pot.getEnergyGradientNumerical(angles) # print ret[1] # print "analytical gradient" # ret2 = pot.getEnergyGradient(angles) # print ret2[1] # print ret[0] # print ret2[0] # # # # #try a quench # from pele.optimize import mylbfgs # ret = mylbfgs(angles, pot) # # print "quenched e = ", ret.energy # print ret.coords # # test_basin_hopping(pot, angles) # #if __name__ == "__main__": # test()
Domain Registry of America – I suggest avoiding droa.com !!!SCAM!!! – !!!BEWARE!!!
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=line-too-long """Script for updating tensorflow/tools/compatibility/renames_v2.py. To update renames_v2.py, run: bazel build tensorflow/tools/compatibility/update:generate_v2_renames_map bazel-bin/tensorflow/tools/compatibility/update/generate_v2_renames_map """ # pylint: enable=line-too-long import sys import tensorflow as tf # This import is needed so that TensorFlow python modules are in sys.modules. from tensorflow import python as tf_python # pylint: disable=unused-import from tensorflow.python.lib.io import file_io from tensorflow.python.platform import app from tensorflow.python.util import tf_decorator from tensorflow.python.util import tf_export from tensorflow.tools.common import public_api from tensorflow.tools.common import traverse from tensorflow.tools.compatibility import tf_upgrade_v2 _OUTPUT_FILE_PATH = 'third_party/tensorflow/tools/compatibility/renames_v2.py' _FILE_HEADER = """# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=line-too-long \"\"\"List of renames to apply when converting from TF 1.0 to TF 2.0. THIS FILE IS AUTOGENERATED: To update, please run: bazel build tensorflow/tools/compatibility/update:generate_v2_renames_map bazel-bin/tensorflow/tools/compatibility/update/generate_v2_renames_map This file should be updated whenever endpoints are deprecated. \"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function """ def get_canonical_name(v2_names, v1_name): if v2_names: return v2_names[0] return 'compat.v1.%s' % v1_name def get_all_v2_names(): """Get a set of function/class names available in TensorFlow 2.0.""" v2_names = set() # All op names in TensorFlow 2.0 def visit(unused_path, unused_parent, children): """Visitor that collects TF 2.0 names.""" for child in children: _, attr = tf_decorator.unwrap(child[1]) api_names_v2 = tf_export.get_v2_names(attr) for name in api_names_v2: v2_names.add(name) visitor = public_api.PublicAPIVisitor(visit) visitor.do_not_descend_map['tf'].append('contrib') traverse.traverse(tf.compat.v2, visitor) return v2_names def collect_constant_renames(): """Looks for constants that need to be renamed in TF 2.0. Returns: Set of tuples of the form (current name, new name). """ renames = set() for module in sys.modules.values(): constants_v1_list = tf_export.get_v1_constants(module) constants_v2_list = tf_export.get_v2_constants(module) # _tf_api_constants attribute contains a list of tuples: # (api_names_list, constant_name) # We want to find API names that are in V1 but not in V2 for the same # constant_names. # First, we convert constants_v1_list and constants_v2_list to # dictionaries for easier lookup. constants_v1 = {constant_name: api_names for api_names, constant_name in constants_v1_list} constants_v2 = {constant_name: api_names for api_names, constant_name in constants_v2_list} # Second, we look for names that are in V1 but not in V2. for constant_name, api_names_v1 in constants_v1.items(): api_names_v2 = constants_v2[constant_name] for name in api_names_v1: if name not in api_names_v2: renames.add((name, get_canonical_name(api_names_v2, name))) return renames def collect_function_renames(): """Looks for functions/classes that need to be renamed in TF 2.0. Returns: Set of tuples of the form (current name, new name). """ # Set of rename lines to write to output file in the form: # 'tf.deprecated_name': 'tf.canonical_name' renames = set() def visit(unused_path, unused_parent, children): """Visitor that collects rename strings to add to rename_line_set.""" for child in children: _, attr = tf_decorator.unwrap(child[1]) api_names_v1 = tf_export.get_v1_names(attr) api_names_v2 = tf_export.get_v2_names(attr) deprecated_api_names = set(api_names_v1) - set(api_names_v2) for name in deprecated_api_names: renames.add((name, get_canonical_name(api_names_v2, name))) visitor = public_api.PublicAPIVisitor(visit) visitor.do_not_descend_map['tf'].append('contrib') visitor.do_not_descend_map['tf.compat'] = ['v1', 'v2'] traverse.traverse(tf, visitor) # It is possible that a different function is exported with the # same name. For e.g. when creating a different function to # rename arguments. Exclude it from renames in this case. v2_names = get_all_v2_names() renames = set((name, new_name) for name, new_name in renames if name not in v2_names) return renames def get_rename_line(name, canonical_name): return ' \'tf.%s\': \'tf.%s\'' % (name, canonical_name) def update_renames_v2(output_file_path): """Writes a Python dictionary mapping deprecated to canonical API names. Args: output_file_path: File path to write output to. Any existing contents would be replaced. """ function_renames = collect_function_renames() constant_renames = collect_constant_renames() all_renames = function_renames.union(constant_renames) manual_renames = set( tf_upgrade_v2.TFAPIChangeSpec().manual_symbol_renames.keys()) # List of rename lines to write to output file in the form: # 'tf.deprecated_name': 'tf.canonical_name' rename_lines = [ get_rename_line(name, canonical_name) for name, canonical_name in all_renames if 'tf.' + name not in manual_renames] renames_file_text = '%srenames = {\n%s\n}\n' % ( _FILE_HEADER, ',\n'.join(sorted(rename_lines))) file_io.write_string_to_file(output_file_path, renames_file_text) def main(unused_argv): update_renames_v2(_OUTPUT_FILE_PATH) if __name__ == '__main__': app.run(main=main)
By Alex Batts — I consider myself a die-hard Batman fan. Lucky for me there are a ton (to put it mildly) of Batman stories out there to read. Unlucky for me, however, it’s a bit difficult to find one easy-to-digest checklist of Batman comics to read. Which made me wonder, how great would it be to have one comprehensive and organized reading guide for the Caped Crusader? What if I could find the magical list I was looking for? Well, folks, I stopped wondering and went out and made the thing myself.
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ import logging from django.test import TestCase from django.core.urlresolvers import reverse from auth.models import User from shops.models import Shop class MarketSellTest(TestCase): fixtures = ['greatcoins_market.json', 'greatcoins_subscriptions.json'] def setUp(self): try: user = User.objects.get(username="test_shop_signup") user.delete() except User.DoesNotExist: pass def test_sign_up(self): """ Test shop signup """ response = self.client.get(reverse("market_buy_signup")) self.failUnless(response.status_code, 200) users_count = User.objects.count() params = { 'username': 'test_shop_signup', 'email': 'test_shop_signup@t.com', 'password1': 'test', 'password2': 'test', } response = self.client.post(reverse("market_buy_signup"), params) self.failUnless(response.status_code, 302) self.assertEquals(User.objects.count(), users_count + 1) shops_count = Shop.objects.count() response = self.client.get(reverse("market_sell_signup")) self.failUnless(response.status_code, 200) print response.context #SignUp step 0 params = { 'csrfmiddlewaretoken': str(response.context['csrf_token']), '0-name_store': 'test2', '0-shop_name': 'test2', '0-street': 'test', '0-city': 'test', '0-state': 'NY', '0-zip': '10001', 'wizard_step': '0' } response = self.client.post(reverse("market_sell_signup"), params) self.failUnless(response.status_code, 200) params = { 'csrfmiddlewaretoken': str(response.context['csrf_token']), '0-name_store': 'test2', '0-shop_name': 'test2', '0-street': 'test', '0-city': 'test', '0-state': 'NY', '0-zip': '10001', '1-plan_id': '1', 'wizard_step': '1', 'hash_0':'22267e8560569a5bba749a8f54aab54a', } response = self.client.post(reverse("market_sell_signup"), params) self.failUnless(response.status_code, 200) params = { 'csrfmiddlewaretoken': str(response.context['csrf_token']), '0-name_store': 'test2', '0-shop_name': 'test2', '0-street': 'test', '0-city': 'test', '0-state': 'NY', '0-zip': '10001', '1-plan_id': '1', '2-billing_street': 'el billing street', '2-billing_city': 'el billing city', '2-billing_state': 'NY', '2-billing_zip': '10001', '2-cc_number': '4111111111111111', '2-cc_expiration_month': '03', '2-cc_expiration_year': '2012', '2-card_security_number': '123', '2-terms': 'on', 'wizard_step': '2', 'hash_0':'22267e8560569a5bba749a8f54aab54a', 'hash_1':'e0341a56bf5d7baa6d13e9b72e831098' } response = self.client.post(reverse("market_sell_signup"), params) self.failUnless(response.status_code, 200) self.assertEquals(Shop.objects.count(), shops_count + 1)
DUBROVNIK, Croatia — Marc van Bloemen has lived in the old town of Dubrovnik, a Croatian citadel widely praised as the jewel of the Adriatic, for decades, since he was a child. He says it used to be a privilege. Now it's a nightmare. Crowds of tourists clog the entrances to the ancient walled city, a UNESCO World Heritage Site, as huge cruise ships unload thousands more daily. People bump into each other on the famous limestone-paved Stradun, the pedestrian street lined with medieval churches and palaces, as fans of the popular TV series "Game of Thrones" search for the locations where it was filmed. Dubrovnik is a prime example of the effects of mass tourism, a global phenomenon in which the increase in people travelling means standout sites — particularly small ones — get overwhelmed by crowds. As the numbers of visitors keeps rising, local authorities are looking for ways to keep the throngs from killing off the town's charm. The problem is hurting Dubrovnik's reputation. UNESCO warned last year that the city's world heritage title was at risk because of the surge in tourist numbers. The cruise ships pay the city harbor docking fees, but the local businesses get very little money from the visitors, who have all-inclusive packages on board the ship and spend very little on local restaurants or shops.
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2015 Nick Hall # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Form selector. """ #------------------------------------------------------------------------ # # GTK modules # #------------------------------------------------------------------------ from gi.repository import Gtk from gi.repository import Gdk #------------------------------------------------------------------------ # # Gramps modules # #------------------------------------------------------------------------ from form import get_form_ids, get_form_id, get_form_type #------------------------------------------------------------------------ # # Internationalisation # #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale try: _trans = glocale.get_addon_translator(__file__) except ValueError: _trans = glocale.translation _ = _trans.gettext #------------------------------------------------------------------------ # # SelectForm class # #------------------------------------------------------------------------ class SelectForm(object): """ Form Selector. """ def __init__(self, dbstate, uistate, track): self.dbstate = dbstate self.uistate = uistate self.top = self._create_dialog() def _create_dialog(self): """ Create a dialog box to select a form. """ # pylint: disable-msg=E1101 title = _("%(title)s - Gramps") % {'title': _("Select Form")} top = Gtk.Dialog(title) top.set_default_size(400, 350) top.set_modal(True) top.set_transient_for(self.uistate.window) top.vbox.set_spacing(5) label = Gtk.Label(label='<span size="larger" weight="bold">%s</span>' % _("Select Form")) label.set_use_markup(True) top.vbox.pack_start(label, 0, 0, 5) box = Gtk.Box() top.vbox.pack_start(box, 1, 1, 5) self.model = Gtk.TreeStore(str, str) self.tree = Gtk.TreeView(model=self.model) self.tree.connect('button-press-event', self.__button_press) renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn("Source", renderer, text=1) column.set_sort_column_id(1) self.tree.append_column(column) slist = Gtk.ScrolledWindow() slist.add(self.tree) slist.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) box.pack_start(slist, 1, 1, 5) top.add_button(_('_Cancel'), Gtk.ResponseType.CANCEL) top.add_button(_('_OK'), Gtk.ResponseType.OK) top.show_all() return top def _populate_model(self): """ Populate the model. """ self.model.clear() form_types = {} for handle in self.dbstate.db.get_source_handles(): source = self.dbstate.db.get_source_from_handle(handle) form_id = get_form_id(source) if form_id in get_form_ids(): form_type = get_form_type(form_id) if _(form_type) in form_types: parent = form_types[_(form_type)] else: parent = self.model.append(None, (None, _(form_type))) form_types[_(form_type)] = parent self.model.append(parent, (source.handle, source.title)) self.model.set_sort_column_id(1, Gtk.SortType.ASCENDING) self.tree.expand_all() def __button_press(self, obj, event): """ Called when a button press is executed """ if event.type == Gdk.EventType._2BUTTON_PRESS: model, iter_ = self.tree.get_selection().get_selected() if iter_: source_handle = model.get_value(iter_, 0) if source_handle: self.top.response(Gtk.ResponseType.OK) def run(self): """ Run the dialog and return the result. """ self._populate_model() source_handle = None while True: response = self.top.run() if response == Gtk.ResponseType.HELP: display_help(webpage='Form_Addons') else: model, iter_ = self.tree.get_selection().get_selected() if iter_: source_handle = model.get_value(iter_, 0) self.top.destroy() return source_handle
Make a donation to this user. Send a personal message to this user. Page created in 0.02 seconds with 13 queries.
# Generated from PLambda.g4 by ANTLR 4.8 # encoding: utf-8 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3D") buf.write("\u00d0\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7") buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\3\2\6\2\30\n\2\r\2") buf.write("\16\2\31\3\3\3\3\3\3\6\3\37\n\3\r\3\16\3 \3\3\3\3\3\3") buf.write("\3\3\3\3\3\3\6\3)\n\3\r\3\16\3*\3\3\3\3\3\3\3\3\3\3\3") buf.write("\3\5\3\63\n\3\3\3\6\3\66\n\3\r\3\16\3\67\3\3\3\3\3\3\3") buf.write("\3\3\3\3\3\6\3@\n\3\r\3\16\3A\3\3\3\3\3\3\3\3\3\3\3\3") buf.write("\3\3\7\3K\n\3\f\3\16\3N\13\3\3\3\3\3\3\3\3\3\3\3\3\3\7") buf.write("\3V\n\3\f\3\16\3Y\13\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3") buf.write("\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3") buf.write("\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\5\3x\n\3\3\3\3\3\3\3\3") buf.write("\3\3\3\3\3\3\3\5\3\u0081\n\3\3\3\3\3\3\3\3\3\3\3\7\3\u0088") buf.write("\n\3\f\3\16\3\u008b\13\3\3\3\3\3\3\3\3\3\6\3\u0091\n\3") buf.write("\r\3\16\3\u0092\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\6\3\u009d") buf.write("\n\3\r\3\16\3\u009e\3\3\3\3\3\3\3\3\3\3\5\3\u00a6\n\3") buf.write("\3\4\3\4\7\4\u00aa\n\4\f\4\16\4\u00ad\13\4\3\4\3\4\3\5") buf.write("\3\5\3\6\3\6\6\6\u00b5\n\6\r\6\16\6\u00b6\3\6\3\6\3\7") buf.write("\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\6\b\u00c4\n\b\r\b\16") buf.write("\b\u00c5\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\13\2\2\f") buf.write("\2\4\6\b\n\f\16\20\22\24\2\4\3\2<=\4\2\5\5<<\2\u00e6\2") buf.write("\27\3\2\2\2\4\u00a5\3\2\2\2\6\u00a7\3\2\2\2\b\u00b0\3") buf.write("\2\2\2\n\u00b2\3\2\2\2\f\u00ba\3\2\2\2\16\u00bf\3\2\2") buf.write("\2\20\u00c9\3\2\2\2\22\u00cb\3\2\2\2\24\u00cd\3\2\2\2") buf.write("\26\30\5\4\3\2\27\26\3\2\2\2\30\31\3\2\2\2\31\27\3\2\2") buf.write("\2\31\32\3\2\2\2\32\3\3\2\2\2\33\34\7\3\2\2\34\36\7\16") buf.write("\2\2\35\37\5\4\3\2\36\35\3\2\2\2\37 \3\2\2\2 \36\3\2\2") buf.write("\2 !\3\2\2\2!\"\3\2\2\2\"#\7\4\2\2#\u00a6\3\2\2\2$%\7") buf.write("\3\2\2%&\7\20\2\2&(\5\n\6\2\')\5\4\3\2(\'\3\2\2\2)*\3") buf.write("\2\2\2*(\3\2\2\2*+\3\2\2\2+,\3\2\2\2,-\7\4\2\2-\u00a6") buf.write("\3\2\2\2./\7\3\2\2/\60\7\21\2\2\60\62\7<\2\2\61\63\5\6") buf.write("\4\2\62\61\3\2\2\2\62\63\3\2\2\2\63\65\3\2\2\2\64\66\5") buf.write("\4\3\2\65\64\3\2\2\2\66\67\3\2\2\2\67\65\3\2\2\2\678\3") buf.write("\2\2\289\3\2\2\29:\7\4\2\2:\u00a6\3\2\2\2;<\7\3\2\2<=") buf.write("\7\22\2\2=?\5\6\4\2>@\5\4\3\2?>\3\2\2\2@A\3\2\2\2A?\3") buf.write("\2\2\2AB\3\2\2\2BC\3\2\2\2CD\7\4\2\2D\u00a6\3\2\2\2EF") buf.write("\7\3\2\2FG\7\24\2\2GH\5\4\3\2HL\5\4\3\2IK\5\4\3\2JI\3") buf.write("\2\2\2KN\3\2\2\2LJ\3\2\2\2LM\3\2\2\2MO\3\2\2\2NL\3\2\2") buf.write("\2OP\7\4\2\2P\u00a6\3\2\2\2QR\7\3\2\2RS\7\23\2\2SW\5\4") buf.write("\3\2TV\5\4\3\2UT\3\2\2\2VY\3\2\2\2WU\3\2\2\2WX\3\2\2\2") buf.write("XZ\3\2\2\2YW\3\2\2\2Z[\7\4\2\2[\u00a6\3\2\2\2\\]\7\3\2") buf.write("\2]^\7\6\2\2^_\5\22\n\2_`\7\4\2\2`\u00a6\3\2\2\2ab\7\3") buf.write("\2\2bc\7\7\2\2cd\5\4\3\2de\7\4\2\2e\u00a6\3\2\2\2fg\7") buf.write("\3\2\2gh\7\b\2\2hi\5\4\3\2ij\5\4\3\2jk\7\4\2\2k\u00a6") buf.write("\3\2\2\2lm\7\3\2\2mn\7\t\2\2no\5\4\3\2op\5\4\3\2pq\5\4") buf.write("\3\2qr\7\4\2\2r\u00a6\3\2\2\2st\7\3\2\2tu\7\13\2\2uw\5") buf.write("\4\3\2vx\5\4\3\2wv\3\2\2\2wx\3\2\2\2xy\3\2\2\2yz\7\4\2") buf.write("\2z\u00a6\3\2\2\2{|\7\3\2\2|}\7\f\2\2}~\5\4\3\2~\u0080") buf.write("\5\4\3\2\177\u0081\5\4\3\2\u0080\177\3\2\2\2\u0080\u0081") buf.write("\3\2\2\2\u0081\u0082\3\2\2\2\u0082\u0083\7\4\2\2\u0083") buf.write("\u00a6\3\2\2\2\u0084\u0085\7\3\2\2\u0085\u0089\7\n\2\2") buf.write("\u0086\u0088\5\4\3\2\u0087\u0086\3\2\2\2\u0088\u008b\3") buf.write("\2\2\2\u0089\u0087\3\2\2\2\u0089\u008a\3\2\2\2\u008a\u008c") buf.write("\3\2\2\2\u008b\u0089\3\2\2\2\u008c\u00a6\7\4\2\2\u008d") buf.write("\u008e\7\3\2\2\u008e\u0090\7\27\2\2\u008f\u0091\5\4\3") buf.write("\2\u0090\u008f\3\2\2\2\u0091\u0092\3\2\2\2\u0092\u0090") buf.write("\3\2\2\2\u0092\u0093\3\2\2\2\u0093\u0094\3\2\2\2\u0094") buf.write("\u0095\5\16\b\2\u0095\u0096\7\4\2\2\u0096\u00a6\3\2\2") buf.write("\2\u0097\u0098\7\3\2\2\u0098\u0099\7\26\2\2\u0099\u009a") buf.write("\7<\2\2\u009a\u009c\5\20\t\2\u009b\u009d\5\4\3\2\u009c") buf.write("\u009b\3\2\2\2\u009d\u009e\3\2\2\2\u009e\u009c\3\2\2\2") buf.write("\u009e\u009f\3\2\2\2\u009f\u00a0\3\2\2\2\u00a0\u00a1\7") buf.write("\4\2\2\u00a1\u00a6\3\2\2\2\u00a2\u00a6\7\5\2\2\u00a3\u00a6") buf.write("\7<\2\2\u00a4\u00a6\7\r\2\2\u00a5\33\3\2\2\2\u00a5$\3") buf.write("\2\2\2\u00a5.\3\2\2\2\u00a5;\3\2\2\2\u00a5E\3\2\2\2\u00a5") buf.write("Q\3\2\2\2\u00a5\\\3\2\2\2\u00a5a\3\2\2\2\u00a5f\3\2\2") buf.write("\2\u00a5l\3\2\2\2\u00a5s\3\2\2\2\u00a5{\3\2\2\2\u00a5") buf.write("\u0084\3\2\2\2\u00a5\u008d\3\2\2\2\u00a5\u0097\3\2\2\2") buf.write("\u00a5\u00a2\3\2\2\2\u00a5\u00a3\3\2\2\2\u00a5\u00a4\3") buf.write("\2\2\2\u00a6\5\3\2\2\2\u00a7\u00ab\7\3\2\2\u00a8\u00aa") buf.write("\5\b\5\2\u00a9\u00a8\3\2\2\2\u00aa\u00ad\3\2\2\2\u00ab") buf.write("\u00a9\3\2\2\2\u00ab\u00ac\3\2\2\2\u00ac\u00ae\3\2\2\2") buf.write("\u00ad\u00ab\3\2\2\2\u00ae\u00af\7\4\2\2\u00af\7\3\2\2") buf.write("\2\u00b0\u00b1\7<\2\2\u00b1\t\3\2\2\2\u00b2\u00b4\7\3") buf.write("\2\2\u00b3\u00b5\5\f\7\2\u00b4\u00b3\3\2\2\2\u00b5\u00b6") buf.write("\3\2\2\2\u00b6\u00b4\3\2\2\2\u00b6\u00b7\3\2\2\2\u00b7") buf.write("\u00b8\3\2\2\2\u00b8\u00b9\7\4\2\2\u00b9\13\3\2\2\2\u00ba") buf.write("\u00bb\7\3\2\2\u00bb\u00bc\5\b\5\2\u00bc\u00bd\5\4\3\2") buf.write("\u00bd\u00be\7\4\2\2\u00be\r\3\2\2\2\u00bf\u00c0\7\3\2") buf.write("\2\u00c0\u00c1\7\30\2\2\u00c1\u00c3\5\b\5\2\u00c2\u00c4") buf.write("\5\4\3\2\u00c3\u00c2\3\2\2\2\u00c4\u00c5\3\2\2\2\u00c5") buf.write("\u00c3\3\2\2\2\u00c5\u00c6\3\2\2\2\u00c6\u00c7\3\2\2\2") buf.write("\u00c7\u00c8\7\4\2\2\u00c8\17\3\2\2\2\u00c9\u00ca\5\4") buf.write("\3\2\u00ca\21\3\2\2\2\u00cb\u00cc\t\2\2\2\u00cc\23\3\2") buf.write("\2\2\u00cd\u00ce\t\3\2\2\u00ce\25\3\2\2\2\23\31 *\62\67") buf.write("ALWw\u0080\u0089\u0092\u009e\u00a5\u00ab\u00b6\u00c5") return buf.getvalue() class PLambdaParser ( Parser ): grammarFileName = "PLambda.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ "<INVALID>", "'('", "')'", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "'None'", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "'-'" ] symbolicNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "STRING", "PRIMITIVE_DATA_OP", "UNARY_OP", "BINARY_OP", "TERNARY_OP", "N_ARY_OP", "AMBI1_OP", "AMBI2_OP", "NONE", "SEQ", "DO", "LET", "DEFINE", "LAMBDA", "APPLY", "INVOKE", "SINVOKE", "FOR", "TRY", "CATCH", "BOOLEAN", "FLOAT", "INT", "LOAD", "IMPORT", "ISNONE", "ISOBJECT", "ISINT", "ISFLOAT", "GETUID", "GLOBAL", "NOT", "THROW", "FETCH", "NARROW", "INSTANCEOF", "GET", "IN", "IS", "LOOKUP", "SETUID", "KWAPPLY", "MODIFY", "UPDATE", "SUPDATE", "SETATTR", "CONCAT", "AND", "OR", "MKTUPLE", "MKLIST", "MKDICT", "MINUS", "IF", "GETATTR", "ID", "NUMBER", "STRING_SQ", "STRING_DQ", "SYMBOL", "LINE_COMMENT", "NEW_LINE_COMMENT", "NEW_COMMENT", "WHITE_SPACE" ] RULE_unit = 0 RULE_expression = 1 RULE_parameterList = 2 RULE_parameter = 3 RULE_bindingList = 4 RULE_bindingPair = 5 RULE_catchExpression = 6 RULE_rangeExpression = 7 RULE_data = 8 RULE_token = 9 ruleNames = [ "unit", "expression", "parameterList", "parameter", "bindingList", "bindingPair", "catchExpression", "rangeExpression", "data", "token" ] EOF = Token.EOF T__0=1 T__1=2 STRING=3 PRIMITIVE_DATA_OP=4 UNARY_OP=5 BINARY_OP=6 TERNARY_OP=7 N_ARY_OP=8 AMBI1_OP=9 AMBI2_OP=10 NONE=11 SEQ=12 DO=13 LET=14 DEFINE=15 LAMBDA=16 APPLY=17 INVOKE=18 SINVOKE=19 FOR=20 TRY=21 CATCH=22 BOOLEAN=23 FLOAT=24 INT=25 LOAD=26 IMPORT=27 ISNONE=28 ISOBJECT=29 ISINT=30 ISFLOAT=31 GETUID=32 GLOBAL=33 NOT=34 THROW=35 FETCH=36 NARROW=37 INSTANCEOF=38 GET=39 IN=40 IS=41 LOOKUP=42 SETUID=43 KWAPPLY=44 MODIFY=45 UPDATE=46 SUPDATE=47 SETATTR=48 CONCAT=49 AND=50 OR=51 MKTUPLE=52 MKLIST=53 MKDICT=54 MINUS=55 IF=56 GETATTR=57 ID=58 NUMBER=59 STRING_SQ=60 STRING_DQ=61 SYMBOL=62 LINE_COMMENT=63 NEW_LINE_COMMENT=64 NEW_COMMENT=65 WHITE_SPACE=66 def __init__(self, input:TokenStream, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.8") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class UnitContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def getRuleIndex(self): return PLambdaParser.RULE_unit def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterUnit" ): listener.enterUnit(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitUnit" ): listener.exitUnit(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitUnit" ): return visitor.visitUnit(self) else: return visitor.visitChildren(self) def unit(self): localctx = PLambdaParser.UnitContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_unit) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 21 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 20 self.expression() self.state = 23 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0)): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExpressionContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return PLambdaParser.RULE_expression def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class NaryExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def N_ARY_OP(self): return self.getToken(PLambdaParser.N_ARY_OP, 0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterNaryExpression" ): listener.enterNaryExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitNaryExpression" ): listener.exitNaryExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitNaryExpression" ): return visitor.visitNaryExpression(self) else: return visitor.visitChildren(self) class ForExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def FOR(self): return self.getToken(PLambdaParser.FOR, 0) def ID(self): return self.getToken(PLambdaParser.ID, 0) def rangeExpression(self): return self.getTypedRuleContext(PLambdaParser.RangeExpressionContext,0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterForExpression" ): listener.enterForExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitForExpression" ): listener.exitForExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitForExpression" ): return visitor.visitForExpression(self) else: return visitor.visitChildren(self) class LambdaExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def LAMBDA(self): return self.getToken(PLambdaParser.LAMBDA, 0) def parameterList(self): return self.getTypedRuleContext(PLambdaParser.ParameterListContext,0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterLambdaExpression" ): listener.enterLambdaExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitLambdaExpression" ): listener.exitLambdaExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitLambdaExpression" ): return visitor.visitLambdaExpression(self) else: return visitor.visitChildren(self) class OneOrMoreExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def AMBI1_OP(self): return self.getToken(PLambdaParser.AMBI1_OP, 0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterOneOrMoreExpression" ): listener.enterOneOrMoreExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitOneOrMoreExpression" ): listener.exitOneOrMoreExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitOneOrMoreExpression" ): return visitor.visitOneOrMoreExpression(self) else: return visitor.visitChildren(self) class NoneLiteralContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def NONE(self): return self.getToken(PLambdaParser.NONE, 0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterNoneLiteral" ): listener.enterNoneLiteral(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitNoneLiteral" ): listener.exitNoneLiteral(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitNoneLiteral" ): return visitor.visitNoneLiteral(self) else: return visitor.visitChildren(self) class SeqExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def SEQ(self): return self.getToken(PLambdaParser.SEQ, 0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterSeqExpression" ): listener.enterSeqExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitSeqExpression" ): listener.exitSeqExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitSeqExpression" ): return visitor.visitSeqExpression(self) else: return visitor.visitChildren(self) class ApplyExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def APPLY(self): return self.getToken(PLambdaParser.APPLY, 0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterApplyExpression" ): listener.enterApplyExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitApplyExpression" ): listener.exitApplyExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitApplyExpression" ): return visitor.visitApplyExpression(self) else: return visitor.visitChildren(self) class BinaryExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def BINARY_OP(self): return self.getToken(PLambdaParser.BINARY_OP, 0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterBinaryExpression" ): listener.enterBinaryExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitBinaryExpression" ): listener.exitBinaryExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBinaryExpression" ): return visitor.visitBinaryExpression(self) else: return visitor.visitChildren(self) class TwoOrMoreExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def AMBI2_OP(self): return self.getToken(PLambdaParser.AMBI2_OP, 0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterTwoOrMoreExpression" ): listener.enterTwoOrMoreExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitTwoOrMoreExpression" ): listener.exitTwoOrMoreExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTwoOrMoreExpression" ): return visitor.visitTwoOrMoreExpression(self) else: return visitor.visitChildren(self) class TryExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def TRY(self): return self.getToken(PLambdaParser.TRY, 0) def catchExpression(self): return self.getTypedRuleContext(PLambdaParser.CatchExpressionContext,0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterTryExpression" ): listener.enterTryExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitTryExpression" ): listener.exitTryExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTryExpression" ): return visitor.visitTryExpression(self) else: return visitor.visitChildren(self) class StringLiteralContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def STRING(self): return self.getToken(PLambdaParser.STRING, 0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterStringLiteral" ): listener.enterStringLiteral(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitStringLiteral" ): listener.exitStringLiteral(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitStringLiteral" ): return visitor.visitStringLiteral(self) else: return visitor.visitChildren(self) class DefineExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def DEFINE(self): return self.getToken(PLambdaParser.DEFINE, 0) def ID(self): return self.getToken(PLambdaParser.ID, 0) def parameterList(self): return self.getTypedRuleContext(PLambdaParser.ParameterListContext,0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDefineExpression" ): listener.enterDefineExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDefineExpression" ): listener.exitDefineExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDefineExpression" ): return visitor.visitDefineExpression(self) else: return visitor.visitChildren(self) class LetExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def LET(self): return self.getToken(PLambdaParser.LET, 0) def bindingList(self): return self.getTypedRuleContext(PLambdaParser.BindingListContext,0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterLetExpression" ): listener.enterLetExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitLetExpression" ): listener.exitLetExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitLetExpression" ): return visitor.visitLetExpression(self) else: return visitor.visitChildren(self) class IdentifierLiteralContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def ID(self): return self.getToken(PLambdaParser.ID, 0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterIdentifierLiteral" ): listener.enterIdentifierLiteral(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitIdentifierLiteral" ): listener.exitIdentifierLiteral(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIdentifierLiteral" ): return visitor.visitIdentifierLiteral(self) else: return visitor.visitChildren(self) class UnaryExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def UNARY_OP(self): return self.getToken(PLambdaParser.UNARY_OP, 0) def expression(self): return self.getTypedRuleContext(PLambdaParser.ExpressionContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterUnaryExpression" ): listener.enterUnaryExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitUnaryExpression" ): listener.exitUnaryExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitUnaryExpression" ): return visitor.visitUnaryExpression(self) else: return visitor.visitChildren(self) class TernaryExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def TERNARY_OP(self): return self.getToken(PLambdaParser.TERNARY_OP, 0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterTernaryExpression" ): listener.enterTernaryExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitTernaryExpression" ): listener.exitTernaryExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTernaryExpression" ): return visitor.visitTernaryExpression(self) else: return visitor.visitChildren(self) class InvokeExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def INVOKE(self): return self.getToken(PLambdaParser.INVOKE, 0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterInvokeExpression" ): listener.enterInvokeExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitInvokeExpression" ): listener.exitInvokeExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitInvokeExpression" ): return visitor.visitInvokeExpression(self) else: return visitor.visitChildren(self) class DataExpressionContext(ExpressionContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a PLambdaParser.ExpressionContext super().__init__(parser) self.copyFrom(ctx) def PRIMITIVE_DATA_OP(self): return self.getToken(PLambdaParser.PRIMITIVE_DATA_OP, 0) def data(self): return self.getTypedRuleContext(PLambdaParser.DataContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDataExpression" ): listener.enterDataExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDataExpression" ): listener.exitDataExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitDataExpression" ): return visitor.visitDataExpression(self) else: return visitor.visitChildren(self) def expression(self): localctx = PLambdaParser.ExpressionContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_expression) self._la = 0 # Token type try: self.state = 163 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,13,self._ctx) if la_ == 1: localctx = PLambdaParser.SeqExpressionContext(self, localctx) self.enterOuterAlt(localctx, 1) self.state = 25 self.match(PLambdaParser.T__0) self.state = 26 self.match(PLambdaParser.SEQ) self.state = 28 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 27 self.expression() self.state = 30 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0)): break self.state = 32 self.match(PLambdaParser.T__1) pass elif la_ == 2: localctx = PLambdaParser.LetExpressionContext(self, localctx) self.enterOuterAlt(localctx, 2) self.state = 34 self.match(PLambdaParser.T__0) self.state = 35 self.match(PLambdaParser.LET) self.state = 36 self.bindingList() self.state = 38 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 37 self.expression() self.state = 40 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0)): break self.state = 42 self.match(PLambdaParser.T__1) pass elif la_ == 3: localctx = PLambdaParser.DefineExpressionContext(self, localctx) self.enterOuterAlt(localctx, 3) self.state = 44 self.match(PLambdaParser.T__0) self.state = 45 self.match(PLambdaParser.DEFINE) self.state = 46 self.match(PLambdaParser.ID) self.state = 48 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,3,self._ctx) if la_ == 1: self.state = 47 self.parameterList() self.state = 51 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 50 self.expression() self.state = 53 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0)): break self.state = 55 self.match(PLambdaParser.T__1) pass elif la_ == 4: localctx = PLambdaParser.LambdaExpressionContext(self, localctx) self.enterOuterAlt(localctx, 4) self.state = 57 self.match(PLambdaParser.T__0) self.state = 58 self.match(PLambdaParser.LAMBDA) self.state = 59 self.parameterList() self.state = 61 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 60 self.expression() self.state = 63 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0)): break self.state = 65 self.match(PLambdaParser.T__1) pass elif la_ == 5: localctx = PLambdaParser.InvokeExpressionContext(self, localctx) self.enterOuterAlt(localctx, 5) self.state = 67 self.match(PLambdaParser.T__0) self.state = 68 self.match(PLambdaParser.INVOKE) self.state = 69 self.expression() self.state = 70 self.expression() self.state = 74 self._errHandler.sync(self) _la = self._input.LA(1) while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0): self.state = 71 self.expression() self.state = 76 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 77 self.match(PLambdaParser.T__1) pass elif la_ == 6: localctx = PLambdaParser.ApplyExpressionContext(self, localctx) self.enterOuterAlt(localctx, 6) self.state = 79 self.match(PLambdaParser.T__0) self.state = 80 self.match(PLambdaParser.APPLY) self.state = 81 self.expression() self.state = 85 self._errHandler.sync(self) _la = self._input.LA(1) while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0): self.state = 82 self.expression() self.state = 87 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 88 self.match(PLambdaParser.T__1) pass elif la_ == 7: localctx = PLambdaParser.DataExpressionContext(self, localctx) self.enterOuterAlt(localctx, 7) self.state = 90 self.match(PLambdaParser.T__0) self.state = 91 self.match(PLambdaParser.PRIMITIVE_DATA_OP) self.state = 92 self.data() self.state = 93 self.match(PLambdaParser.T__1) pass elif la_ == 8: localctx = PLambdaParser.UnaryExpressionContext(self, localctx) self.enterOuterAlt(localctx, 8) self.state = 95 self.match(PLambdaParser.T__0) self.state = 96 self.match(PLambdaParser.UNARY_OP) self.state = 97 self.expression() self.state = 98 self.match(PLambdaParser.T__1) pass elif la_ == 9: localctx = PLambdaParser.BinaryExpressionContext(self, localctx) self.enterOuterAlt(localctx, 9) self.state = 100 self.match(PLambdaParser.T__0) self.state = 101 self.match(PLambdaParser.BINARY_OP) self.state = 102 self.expression() self.state = 103 self.expression() self.state = 104 self.match(PLambdaParser.T__1) pass elif la_ == 10: localctx = PLambdaParser.TernaryExpressionContext(self, localctx) self.enterOuterAlt(localctx, 10) self.state = 106 self.match(PLambdaParser.T__0) self.state = 107 self.match(PLambdaParser.TERNARY_OP) self.state = 108 self.expression() self.state = 109 self.expression() self.state = 110 self.expression() self.state = 111 self.match(PLambdaParser.T__1) pass elif la_ == 11: localctx = PLambdaParser.OneOrMoreExpressionContext(self, localctx) self.enterOuterAlt(localctx, 11) self.state = 113 self.match(PLambdaParser.T__0) self.state = 114 self.match(PLambdaParser.AMBI1_OP) self.state = 115 self.expression() self.state = 117 self._errHandler.sync(self) _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0): self.state = 116 self.expression() self.state = 119 self.match(PLambdaParser.T__1) pass elif la_ == 12: localctx = PLambdaParser.TwoOrMoreExpressionContext(self, localctx) self.enterOuterAlt(localctx, 12) self.state = 121 self.match(PLambdaParser.T__0) self.state = 122 self.match(PLambdaParser.AMBI2_OP) self.state = 123 self.expression() self.state = 124 self.expression() self.state = 126 self._errHandler.sync(self) _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0): self.state = 125 self.expression() self.state = 128 self.match(PLambdaParser.T__1) pass elif la_ == 13: localctx = PLambdaParser.NaryExpressionContext(self, localctx) self.enterOuterAlt(localctx, 13) self.state = 130 self.match(PLambdaParser.T__0) self.state = 131 self.match(PLambdaParser.N_ARY_OP) self.state = 135 self._errHandler.sync(self) _la = self._input.LA(1) while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0): self.state = 132 self.expression() self.state = 137 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 138 self.match(PLambdaParser.T__1) pass elif la_ == 14: localctx = PLambdaParser.TryExpressionContext(self, localctx) self.enterOuterAlt(localctx, 14) self.state = 139 self.match(PLambdaParser.T__0) self.state = 140 self.match(PLambdaParser.TRY) self.state = 142 self._errHandler.sync(self) _alt = 1 while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 141 self.expression() else: raise NoViableAltException(self) self.state = 144 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,11,self._ctx) self.state = 146 self.catchExpression() self.state = 147 self.match(PLambdaParser.T__1) pass elif la_ == 15: localctx = PLambdaParser.ForExpressionContext(self, localctx) self.enterOuterAlt(localctx, 15) self.state = 149 self.match(PLambdaParser.T__0) self.state = 150 self.match(PLambdaParser.FOR) self.state = 151 self.match(PLambdaParser.ID) self.state = 152 self.rangeExpression() self.state = 154 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 153 self.expression() self.state = 156 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0)): break self.state = 158 self.match(PLambdaParser.T__1) pass elif la_ == 16: localctx = PLambdaParser.StringLiteralContext(self, localctx) self.enterOuterAlt(localctx, 16) self.state = 160 self.match(PLambdaParser.STRING) pass elif la_ == 17: localctx = PLambdaParser.IdentifierLiteralContext(self, localctx) self.enterOuterAlt(localctx, 17) self.state = 161 self.match(PLambdaParser.ID) pass elif la_ == 18: localctx = PLambdaParser.NoneLiteralContext(self, localctx) self.enterOuterAlt(localctx, 18) self.state = 162 self.match(PLambdaParser.NONE) pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ParameterListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def parameter(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ParameterContext) else: return self.getTypedRuleContext(PLambdaParser.ParameterContext,i) def getRuleIndex(self): return PLambdaParser.RULE_parameterList def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterParameterList" ): listener.enterParameterList(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitParameterList" ): listener.exitParameterList(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitParameterList" ): return visitor.visitParameterList(self) else: return visitor.visitChildren(self) def parameterList(self): localctx = PLambdaParser.ParameterListContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_parameterList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 165 self.match(PLambdaParser.T__0) self.state = 169 self._errHandler.sync(self) _la = self._input.LA(1) while _la==PLambdaParser.ID: self.state = 166 self.parameter() self.state = 171 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 172 self.match(PLambdaParser.T__1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ParameterContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(PLambdaParser.ID, 0) def getRuleIndex(self): return PLambdaParser.RULE_parameter def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterParameter" ): listener.enterParameter(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitParameter" ): listener.exitParameter(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitParameter" ): return visitor.visitParameter(self) else: return visitor.visitChildren(self) def parameter(self): localctx = PLambdaParser.ParameterContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_parameter) try: self.enterOuterAlt(localctx, 1) self.state = 174 self.match(PLambdaParser.ID) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BindingListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def bindingPair(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.BindingPairContext) else: return self.getTypedRuleContext(PLambdaParser.BindingPairContext,i) def getRuleIndex(self): return PLambdaParser.RULE_bindingList def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterBindingList" ): listener.enterBindingList(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitBindingList" ): listener.exitBindingList(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBindingList" ): return visitor.visitBindingList(self) else: return visitor.visitChildren(self) def bindingList(self): localctx = PLambdaParser.BindingListContext(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_bindingList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 176 self.match(PLambdaParser.T__0) self.state = 178 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 177 self.bindingPair() self.state = 180 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==PLambdaParser.T__0): break self.state = 182 self.match(PLambdaParser.T__1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BindingPairContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def parameter(self): return self.getTypedRuleContext(PLambdaParser.ParameterContext,0) def expression(self): return self.getTypedRuleContext(PLambdaParser.ExpressionContext,0) def getRuleIndex(self): return PLambdaParser.RULE_bindingPair def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterBindingPair" ): listener.enterBindingPair(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitBindingPair" ): listener.exitBindingPair(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBindingPair" ): return visitor.visitBindingPair(self) else: return visitor.visitChildren(self) def bindingPair(self): localctx = PLambdaParser.BindingPairContext(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_bindingPair) try: self.enterOuterAlt(localctx, 1) self.state = 184 self.match(PLambdaParser.T__0) self.state = 185 self.parameter() self.state = 186 self.expression() self.state = 187 self.match(PLambdaParser.T__1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CatchExpressionContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CATCH(self): return self.getToken(PLambdaParser.CATCH, 0) def parameter(self): return self.getTypedRuleContext(PLambdaParser.ParameterContext,0) def expression(self, i:int=None): if i is None: return self.getTypedRuleContexts(PLambdaParser.ExpressionContext) else: return self.getTypedRuleContext(PLambdaParser.ExpressionContext,i) def getRuleIndex(self): return PLambdaParser.RULE_catchExpression def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterCatchExpression" ): listener.enterCatchExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitCatchExpression" ): listener.exitCatchExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitCatchExpression" ): return visitor.visitCatchExpression(self) else: return visitor.visitChildren(self) def catchExpression(self): localctx = PLambdaParser.CatchExpressionContext(self, self._ctx, self.state) self.enterRule(localctx, 12, self.RULE_catchExpression) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 189 self.match(PLambdaParser.T__0) self.state = 190 self.match(PLambdaParser.CATCH) self.state = 191 self.parameter() self.state = 193 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 192 self.expression() self.state = 195 self._errHandler.sync(self) _la = self._input.LA(1) if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << PLambdaParser.T__0) | (1 << PLambdaParser.STRING) | (1 << PLambdaParser.NONE) | (1 << PLambdaParser.ID))) != 0)): break self.state = 197 self.match(PLambdaParser.T__1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class RangeExpressionContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expression(self): return self.getTypedRuleContext(PLambdaParser.ExpressionContext,0) def getRuleIndex(self): return PLambdaParser.RULE_rangeExpression def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterRangeExpression" ): listener.enterRangeExpression(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitRangeExpression" ): listener.exitRangeExpression(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitRangeExpression" ): return visitor.visitRangeExpression(self) else: return visitor.visitChildren(self) def rangeExpression(self): localctx = PLambdaParser.RangeExpressionContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_rangeExpression) try: self.enterOuterAlt(localctx, 1) self.state = 199 self.expression() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class DataContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(PLambdaParser.ID, 0) def NUMBER(self): return self.getToken(PLambdaParser.NUMBER, 0) def getRuleIndex(self): return PLambdaParser.RULE_data def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterData" ): listener.enterData(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitData" ): listener.exitData(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitData" ): return visitor.visitData(self) else: return visitor.visitChildren(self) def data(self): localctx = PLambdaParser.DataContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_data) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 201 _la = self._input.LA(1) if not(_la==PLambdaParser.ID or _la==PLambdaParser.NUMBER): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TokenContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(PLambdaParser.ID, 0) def STRING(self): return self.getToken(PLambdaParser.STRING, 0) def getRuleIndex(self): return PLambdaParser.RULE_token def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterToken" ): listener.enterToken(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitToken" ): listener.exitToken(self) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitToken" ): return visitor.visitToken(self) else: return visitor.visitChildren(self) def token(self): localctx = PLambdaParser.TokenContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_token) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 203 _la = self._input.LA(1) if not(_la==PLambdaParser.STRING or _la==PLambdaParser.ID): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx
Pioneers in delivering asset tracking, asset security and asset recovery solutions for the global market since 2001, NFC Group are best known as the creators of the award-winning Orion Data Network. This ground-breaking, low-cost, scalable, radio frequency security and logistics network enables real-time visibility, tracking and analytics, while reducing operational costs by more than 75%. CMatt has spent 25 years working in the defence and telemetry arena. He has a degree in GIS (Geographical Information Systems) and remote sensing. Initially as a defence contractor, he was promoted quickly to board level. From there, in a business development role, he secured a major contract that lead to the formation of a new business that was spun off from the parent company. After running that business for a number of years, he went to join his wife, who had set up New Forest Communications (NFC). NFC evolved from component sales into solution sales, and finally into being focused on delivering the privately-owned Orion Data Network. Creating disruptive technical solutions has always been Matt’s business goal. Jonathan Olliff-Cooper is a co-founder of the NFC Group, and now the Group’s CTO. Following university in London, Jonathan spent several years in the City, primarily working for companies in the financial sector, including Merrill Lynch, Credit Suisse, KPMG, RBS and HP. Jonathan also worked as the personal technical liaison to Rothschild Bank reporting directly to Evelyn and Lady de Rothschild. After being headhunted, Jonathan moved to a permanent position at IBM where his principal responsibility was the development and maintenance of the company’s flagship Z10 supercomputers. One of our other greatest assets are the people who make up our global teams. Take a look at their backgrounds and expertise to see how they contribute to achieving our Mission, Core Values and commitment to excellent client service. One of the things that makes NFC Group unique is our privately-owned Orion Data Network. A cost-effective alternative to traditional GSM and satellite tracking technologies, the Orion Data Network has redefined the business benefits of real-time data analytics for our clients. Unique Mobile and SIM-free data transmission that simplifies data communications and reduces your operational and capital expenditure and your carbon footprint. A comprehensive, flexible and scalable solution that allows the you to choose the services and roll-out that suits your particular requirements & budget, increasing your supply chain productivity and efficiency.
#!/usr/bin/env python # coding: utf-8 import argparse import os import re from datetime import date import pymysql os.environ['PYWIKIBOT_DIR'] = os.path.dirname(os.path.realpath(__file__)) import pywikibot from dateutil.relativedelta import relativedelta from config import host, password, user # pylint: disable=E0611,W0614 parser = argparse.ArgumentParser() parser.add_argument('--page') parser.add_argument('--months', type=int, default=0) args = parser.parse_args() print(args) title = args.page if title is None: rundate = date.today() + relativedelta(months=args.months) title = 'Wikipedia:維基百科政策簡報/存檔/{:04}-{:02}'.format(rundate.year, rundate.month) site = pywikibot.Site('zh', 'wikipedia') site.login() print(title) page = pywikibot.Page(site, title) if not page.exists(): print('page is not exists') exit() text = page.text # print(text) m = re.search(r'過去一個月((\d+)年(\d+)月(\d+)日至(\d+)年(\d+)月(\d+)日)內', text) if m: time1 = '{:04d}{:02d}{:02d}000000'.format(int(m.group(1)), int(m.group(2)), int(m.group(3))) time2 = '{:04d}{:02d}{:02d}235959'.format(int(m.group(4)), int(m.group(5)), int(m.group(6))) print(time1, time2) else: exit('Failed to get date range') if not page.botMayEdit(): print('page is locked') exit() ignoreRevids = [] pos1 = text.index("'''方針與指引重要變動'''") pos2 = text.index("'''其他方針與指引雜項修訂'''") policyText = text[pos1:pos2] # print(policyText) for temp in re.findall(r'\[\[Special:Diff/(\d+)/(\d+)\|', policyText): ignoreRevids.append((int(temp[0]), int(temp[1]))) for temp in re.findall(r'\[\[Special:Permalink/(\d+)\|', policyText): ignoreRevids.append((0, int(temp))) talkPage = page.toggleTalkPage() if talkPage.exists(): talkText = talkPage.text try: pos1 = talkText.index('<!-- bot ignore start -->') pos2 = talkText.index('<!-- bot ignore end -->') talkText = talkText[pos1:pos2] print(talkText) for temp in re.findall(r'\[\[Special:Diff/(\d+)/(\d+)(?:\||\]\])', talkText): ignoreRevids.append((int(temp[0]), int(temp[1]))) except ValueError: print('cannot find flag') print('ignoreRevids', ignoreRevids) conn = pymysql.connect( host=host, user=user, password=password, charset="utf8" ) # https://quarry.wmflabs.org/query/33421 with conn.cursor() as cur: cur.execute('use zhwiki_p') cur.execute(""" SELECT rev_id, rev_parent_id, rev_timestamp, page_id, page_title, comment_text FROM revision LEFT JOIN page ON revision.rev_page = page.page_id LEFT JOIN comment ON revision.rev_comment_id = comment.comment_id WHERE revision.rev_timestamp >= '{}' AND revision.rev_timestamp <= '{}' AND revision.rev_page IN ( SELECT page.page_id FROM pagelinks LEFT JOIN page ON pagelinks.pl_title = page.page_title AND pagelinks.pl_namespace = page.page_namespace WHERE pl_from = 1608664 AND pl_namespace = 4 AND page_id NOT IN ( 590741, # 嵌入包含 977277 # 模板文檔頁模式 ) ) ORDER BY revision.rev_timestamp ASC """.format(time1, time2)) res = cur.fetchall() record = {} revid2page_id = {} for row in res: rev_id = row[0] rev_parent_id = row[1] rev_timestamp = row[2].decode() page_id = row[3] page_title = row[4].decode() revid2page_id[rev_id] = page_id revid2page_id[rev_parent_id] = page_id if page_id not in record: record[page_id] = { 'page_title': page_title, 'history': [], } record[page_id]['history'].append({ 'revid': rev_id, 'rev_parent_id': rev_parent_id, 'rev_timestamp': rev_timestamp, 'minor': True }) for revids in ignoreRevids: if revids[1] not in revid2page_id: continue page_id = revid2page_id[revids[1]] idx1 = 0 if revids[0] != 0: while record[page_id]['history'][idx1]['rev_parent_id'] != revids[0]: idx1 += 1 idx2 = 0 while record[page_id]['history'][idx2]['revid'] != revids[1]: idx2 += 1 for i in range(idx1, idx2 + 1): record[page_id]['history'][i]['minor'] = False # print(json.dumps(record, indent=4, ensure_ascii=False)) policyList = [ 1040126, # IP封禁例外 661388, # 新頁面巡查 35, # 方針與指引 138006, # 五大支柱 140143, # 忽略所有规则 314, # 中立的观点 1007580, # 可供查證 1007588, # 非原创研究 3036, # 避免地域中心 796, # 维基百科不是什么 22766, # 维基百科不是词典 621588, # 自傳 1165683, # 生者傳記 586519, # 用戶查核方針 70668, # 快速删除方针 351, # 文件使用方针 1089503, # 侵犯著作权 121628, # 保護方針 311, # 命名常规 318685, # 命名常规_(人名) 6023660, # 命名常规_(化学) 3570009, # 命名常规_(电子游戏) 6628518, # 命名常规_(页面分类) 104452, # 文明 142344, # 共识 139444, # 不要人身攻击 40126, # 編輯戰 1187041, # 編輯禁制方針 16795, # 编辑方针 1497462, # 修訂巡查 828098, # 騷擾 122511, # 破坏 138734, # 条目所有权 1050650, # 封禁方针 1041919, # 删除方针 1279762, # 修訂版本刪除 3905475, # 存廢覆核方針 7426, # 用户名 5757315, # 機械人方針 1454, # 管理员 160825, # 管理員的離任 503284, # 管理戰 6890438, # 权限申请 5902631, # 解除權限方針 1001002, # 回退功能 919595, # 基金會行動 1082699, # 傀儡 6134707, # 儿童保护 1038748, # 监督 1696159, # 人事任免投票資格 1139217, # 志愿者回复团队 1466707, # 机器用户 282654, # 行政员 5323514, # 大量帳號建立者 6108916, # 檔案移動員 6213290, # 介面管理員 5373689, # 使用条款 5373678, # 有償編輯方針 267252, # 誹謗 6786601, # 版权信息 5307465, # 非歧视方针 1077124, # 非自由内容使用准则 5723648, # 模板編輯員 ] minorPolicyChanges = {} minorGuidelineChanges = {} for page_id in record: idx1 = 0 while idx1 < len(record[page_id]['history']): if record[page_id]['history'][idx1]['minor']: idx2 = idx1 while idx2 < len(record[page_id]['history']) and record[page_id]['history'][idx2]['minor']: idx2 += 1 if page_id in policyList: if page_id not in minorPolicyChanges: minorPolicyChanges[page_id] = { 'page_title': record[page_id]['page_title'], 'first_time': int(record[page_id]['history'][idx1]['rev_timestamp']), 'changes': [], } minorPolicyChanges[page_id]['changes'].append(( record[page_id]['history'][idx1]['rev_parent_id'], record[page_id]['history'][idx2 - 1]['revid'], )) else: if page_id not in minorGuidelineChanges: minorGuidelineChanges[page_id] = { 'page_title': record[page_id]['page_title'], 'first_time': int(record[page_id]['history'][idx1]['rev_timestamp']), 'changes': [], } minorGuidelineChanges[page_id]['changes'].append(( record[page_id]['history'][idx1]['rev_parent_id'], record[page_id]['history'][idx2 - 1]['revid'], )) idx1 = idx2 idx1 += 1 # print(minorPolicyChanges) # print(minorGuidelineChanges) minorPolicyChanges = list(minorPolicyChanges.values()) minorPolicyChanges.sort(key=lambda v: v['first_time']) minorGuidelineChanges = list(minorGuidelineChanges.values()) minorGuidelineChanges.sort(key=lambda v: v['first_time']) # print(minorPolicyChanges) # print(minorGuidelineChanges) chineseNumber = ['一', '二', '三', '四', '五'] def formatTitle(title, isPolicy): if title == '可靠来源/布告板/评级指引': return '可靠来源布告板评级指引' title = re.sub(r'/(条目指引)', r'\1', title) title = re.sub(r'^(.+)/(.+)$', r'\g<1>(\g<2>)', title) title = re.sub(r'^(.+)_\((.+)\)$', r'\g<1>(\g<2>)', title) if not re.search(r'方[針针]|指引|格式手[冊册]|五大支柱|维基百科不是什么|命名常规|忽略所有规则', title): if isPolicy: title = re.sub(r'^(.+?)((.+?))?$', r'\g<1>方針\g<2>', title) else: title = re.sub(r'^(.+?)((.+?))?$', r'\g<1>指引\g<2>', title) title = re.sub(r'名字空[间間]', '命名空間', title) return title policyTextList = [] for change in minorPolicyChanges: title = formatTitle(change['page_title'], True) if len(change['changes']) == 1: policyTextList.append('《[[Special:Diff/{}/{}|{}]]》'.format( change['changes'][0][0], change['changes'][0][1], title, )) else: diffList = [] for i, revids in enumerate(change['changes']): diffList.append('[[Special:Diff/{}/{}|{}]]'.format( revids[0], revids[1], chineseNumber[i], )) policyTextList.append('《{}》({})'.format( title, '、'.join(diffList), )) # print('policyTextList', policyTextList) guidelineTextList = [] for change in minorGuidelineChanges: title = formatTitle(change['page_title'], False) if len(change['changes']) == 1: guidelineTextList.append('《[[Special:Diff/{}/{}|{}]]》'.format( change['changes'][0][0], change['changes'][0][1], title, )) else: diffList = [] for i, revids in enumerate(change['changes']): diffList.append('[[Special:Diff/{}/{}|{}]]'.format( revids[0], revids[1], chineseNumber[i], )) guidelineTextList.append('《{}》({})'.format( title, '、'.join(diffList), )) # print('guidelineTextList', guidelineTextList) newPolicyText = '' if len(policyTextList) >= 2: newPolicyText = '、'.join(policyTextList[:-1]) + '及' + policyTextList[-1] elif len(policyTextList) == 1: newPolicyText = policyTextList[0] else: newPolicyText = '無' # print('newPolicyText', newPolicyText) newGuidelineText = '' if len(guidelineTextList) >= 2: newGuidelineText = '、'.join(guidelineTextList[:-1]) + '及' + guidelineTextList[-1] elif len(guidelineTextList) == 1: newGuidelineText = guidelineTextList[0] else: newGuidelineText = '無' # print('newGuidelineText', newGuidelineText) text = re.sub(r'(\[\[Special:链出更改/Category:维基百科方针\|方針]]:).*', r'\1' + newPolicyText + '。', text) text = re.sub(r'(\[\[Special:链出更改/Category:维基百科指引\|指引]]:).*', r'\1' + newGuidelineText + '。', text) # print(text) if page.text == text: print('No diff') exit() print('Diff:') pywikibot.showDiff(page.text, text) print('-' * 50) page.text = text page.save(summary='[[User:A2093064-bot/task/36|機器人36]]:自動更新雜項修訂', minor=False)
Despite Kate and Meghan's charms there's strong calls for Australia to cut ties. Despite Prince Harry and Meghan Markle charming the entire nation on their recent royal tour Labor has confirmed it will push ahead with plans for vote on a republic. As Fairfax Media reports, opposition Leader Bill Shorten has reaffirmed that if Labor is elected he’ll approve a $160 million funding plan for a republic plebiscite—not a postal vote—in parliament&apos;s next term. "We&apos;re not saying it&apos;s the most important issue but we are saying that if we are elected at the next election, it&apos;s one of the issues that Labor will attempt to deal with during our first term," Thistlethwaite told Fairfax. The last time the nation was asked if they wanted to ditch the head of state was in the 1999 referendum; that vote resulted in 55% of the population favouring the current constitutional monarchy. Despite meeting with Harry and Meghan in October, Bill Shorten has done little in the past to hide is preference for a republic. "Let us declare that our head of state should be one of us,” he said in a 2015 speech. "Let us rally behind an Australian republic - a model that truly speaks for who we are, our modern identity, our place in our region and our world." Following Labor’s announcement pro-republic group, Australian Republic Movement released a statement praising the plebiscite commitment, calling it “a huge step”. The group’s national director, Michael Cooney also told whimn.com.au that a republic would mean “more Australians will have a say about our nation&apos;s future,” adding, “it is more democratic”. But does the Australian public want a President over a Queen or King? Maybe not. An Newspoll conducted for The Australian following last month’s royal visit by the Duke and Duchess of Sussex shows just 40% of Aussies are in favour of severing royal ties; a 10% decline from an April poll. When asked about those results, young monarchist Abby Donaldson told The Australian young royals like Prince Harry and Meghan, as well as, Prince William, Kate and their children, presented alluring reasons to remain a nation with a British sovereign. “We’ve grown up in a generation where that have been no scandals surrounding the royal family and so what we’ve been able to see is their ties to charity and how important is, for example, Will and Kate talking about mental health,” she said.
import numpy as np def replace_nans(array, max_iter, tol, kernel_size=2, method="disk"): """Replace NaN elements in an array using an iterative image inpainting algorithm. The algorithm is the following: 1) For each element in the input array, replace it by a weighted average of the neighbouring elements which are not NaN themselves. The weights depend on the method type. See Methods below. 2) Several iterations are needed if there are adjacent NaN elements. If this is the case, information is "spread" from the edges of the missing regions iteratively, until the variation is below a certain threshold. Methods: localmean - A square kernel where all elements have the same value, weights are equal to n/( (2*kernel_size+1)**2 -1 ), where n is the number of non-NaN elements. disk - A circular kernel where all elements have the same value, kernel is calculated by:: if ((S-i)**2 + (S-j)**2)**0.5 <= S: kernel[i,j] = 1.0 else: kernel[i,j] = 0.0 where S is the kernel radius. distance - A circular inverse distance kernel where elements are weighted proportional to their distance away from the center of the kernel, elements farther away have less weight. Elements outside the specified radius are set to 0.0 as in 'disk', the remaining of the weights are calculated as:: maxDist = ((S)**2 + (S)**2)**0.5 kernel[i,j] = -1*(((S-i)**2 + (S-j)**2)**0.5 - maxDist) where S is the kernel radius. Parameters ---------- array : 2d or 3d np.ndarray an array containing NaN elements that have to be replaced if array is a masked array (numpy.ma.MaskedArray), then the mask is reapplied after the replacement max_iter : int the number of iterations tol : float On each iteration check if the mean square difference between values of replaced elements is below a certain tolerance `tol` kernel_size : int the size of the kernel, default is 1 method : str the method used to replace invalid values. Valid options are `localmean`, `disk`, and `distance`. Returns ------- filled : 2d or 3d np.ndarray a copy of the input array, where NaN elements have been replaced. """ kernel_size = int(kernel_size) filled = array.copy() n_dim = len(array.shape) # generating the kernel kernel = np.zeros([2 * kernel_size + 1] * len(array.shape), dtype=int) if method == "localmean": kernel += 1 elif method == "disk": dist, dist_inv = get_dist(kernel, kernel_size) kernel[dist <= kernel_size] = 1 elif method == "distance": dist, dist_inv = get_dist(kernel, kernel_size) kernel[dist <= kernel_size] = dist_inv[dist <= kernel_size] else: raise ValueError( "Known methods are: `localmean`, `disk` or `distance`." ) # list of kernel array indices # kernel_indices = np.indices(kernel.shape) # kernel_indices = np.reshape(kernel_indices, # (n_dim, (2 * kernel_size + 1) ** n_dim), # order="C").T # indices where array is NaN nan_indices = np.array(np.nonzero(np.isnan(array))).T.astype(int) # number of NaN elements n_nans = len(nan_indices) # arrays which contain replaced values to check for convergence replaced_new = np.zeros(n_nans) replaced_old = np.zeros(n_nans) # make several passes # until we reach convergence for _ in range(max_iter): # note: identifying new nan indices and looping other the new indices # would give slightly different result # for each NaN element for k in range(n_nans): ind = nan_indices[ k ] # 2 or 3 indices indicating the position of a nan element # init to 0.0 replaced_new[k] = 0.0 # generating a list of indices of the convolution window in the # array slice_indices = np.array(np.meshgrid(*[range(i - kernel_size, i + kernel_size + 1) for i in ind])) # identifying all indices strictly inside the image edges: in_mask = np.array( [ np.logical_and( slice_indices[i] < array.shape[i], slice_indices[i] >= 0 ) for i in range(n_dim) ] ) # logical and over x,y (and z) indices in_mask = np.prod(in_mask, axis=0).astype(bool) # extract window from array win = filled[tuple(slice_indices[:, in_mask])] # selecting the same points from the kernel kernel_in = kernel[in_mask] # sum of elements of the kernel that are not nan in the window non_nan = np.sum(kernel_in[~np.isnan(win)]) if non_nan > 0: # convolution with the kernel replaced_new[k] = np.nansum(win * kernel_in) / non_nan else: # don't do anything if there is only nans around replaced_new[k] = np.nan # bulk replace all new values in array filled[tuple(nan_indices.T)] = replaced_new # check if replaced elements are below a certain tolerance if np.mean((replaced_new - replaced_old) ** 2) < tol: break else: replaced_old = replaced_new return filled def get_dist(kernel, kernel_size): # generates a map of distances to the center of the kernel. This is later # used to generate disk-shaped kernels and # to fill in distance based weights if len(kernel.shape) == 2: # x and y coordinates for each points xs, ys = np.indices(kernel.shape) # maximal distance form center - distance to center (of each point) dist = np.sqrt((ys - kernel_size) ** 2 + (xs - kernel_size) ** 2) dist_inv = np.sqrt(2) * kernel_size - dist if len(kernel.shape) == 3: xs, ys, zs = np.indices(kernel.shape) dist = np.sqrt( (ys - kernel_size) ** 2 + (xs - kernel_size) ** 2 + (zs - kernel_size) ** 2 ) dist_inv = np.sqrt(3) * kernel_size - dist return dist, dist_inv
In a province that has long been known for its antiquated liquor laws there’s a new wave of new distillers popping up producing quality artisan spirits. From absinthe makes the heart grow fonder and the mind wander to sweet but not too subtle apple schnapps to knock your socks off, I came I saw and they conquered me body, soul and mind. The following are my highlights from the BC Distilled Festival – B.C. Premier Micro-distillery Festival. Odd Society Spirits (Vancouver): Odd spirits – located on Powell Street, this distillery produces vodka, gin, single malt, and Cassis Crème de Cassis with bc blackcurrants just like the kind your French momma gave you to get you to femme la boucher late at night. Long Table Distillery (Vancouver): Long Table Distillery takes their gin quite seriously and only produces small batches. There’s a gin infused with cucumber and even gin aged in bourbon barrels which I quite enjoyed. . SR Winery & Distillery produces Soju maQ which is a spirit made from 100% BC barley and has a similar taste and structure to sake. SIPsoda (Vancouver): If you’re a fan of carbonated cocktails then you should stock up on SIP carbonated drinks as the flavours of Lavendar Lemon Peel, Rosemary Lime and Coriander Orange give it a nice subtle flavour to your cocktail. The BC Distilled Festival also had food from the following restaurants: Grain Tasting Bar, Edible Canada, Forage, Blackbird Public House and The Distillery Bar + Kitchen. Deep Cove Brewers and Distillers. Dragon Mist Vodka (South Surrey): Premium vodka made only with two ingredients: wheat grown in Dawson Creek, British and pure Canadian glacial water. Then fermented, distilled and bottled at the Headspring Distillery in South Surrey. No additional neutral grain spirits or additives. Maple Leaf Spirits (Penticton): More than just maple syrup liquer, Maple Leaf Spirits also has Grappa style: Skinny Pinot Noir, Gewurtztraminer, Syrah and fruit brandys: Canadian Kirst, Pear Williams, Italian Prune and Aged Italian Prune which won gold medal Gold Medal Destillata 2013, Austria. Merridale Ciderworks Corp. (Cobble Hill): Awarded 3 medals for brandies at the American Distilling Competition. Also fortified wines of winter apple, Pomme, Oh or Mure Oh Brandies Smooth fruit based vodka called Rizz Cider. Pemberton Distillery Inc. (Pemberton): All products are pure and organic – potato vodka, gin, apple brandy, The Devils Club absinthe, single malt whisky Kartoffelschnaps – Kartoffelschnaps, which is an unique Pemberton potato spirit of local wildflower honey, bourbon cured vanilla beans and special herbs and spices. They also produce extracts – tonic syprup, vanilla, rhurbarb and giger elixir, cinnamon, and rosemary & ginger. Shelter Point Distillery (Campbell River): vodka, single malt whisky. Sons of Vancouver (North Shore): amaretto, chili infused vodka and more. The Liberty Distillery (Vancouver): Truth Vodka from 100% organic BC grown wheat, Endeavour Gin which is a versatile London Dry Style Gin made with 100% organic BC triple distilled wheat spirit and Railspur No. 1 White – single pot triple distilled unaged barley based grain spirit (aka white whiskey). Yaletown Distilling (Vancouver): Yaletown Vodka made from BC grown barley and wheat and Yaletown Gin which has been distilled three times. Yukon Shine (Whitehorse): Yukon Winter Vodka made with Yukon Gold potatoes, Canadian barley and rye and Auragin with hint of juniper, berries and citrus. Walter Craft Caesar (Whitehorse): All natural ingredients with no high fructose corn syrup, no artificial flavours and no MSG. Bittered Sling Extracts (Vancouver): A collaboration of chef Jonathan Chovancek and mixologist and sommelier Lauren Mote to produce high-quality, small-batch bitters and extracts that provides a fusion of homegrown ingredients and flavours that are now used extensively by bars to produce great cocktails as the extracts are true essences of flavour.
# coding=utf-8 from decimal import Decimal, ROUND_HALF_UP from pypinyin import pinyin, lazy_pinyin import pypinyin def format_decimal(value): """ Format a decimal with two decimal point with rounding mode ROUND_HALF_UP :param value the decimal to format """ return Decimal( Decimal(value).quantize(Decimal('.01'), rounding=ROUND_HALF_UP)) def decimal_to_percent(value, decimal_place=2): """ Format a decimal to percentage with two decimal :param value: the value to be formatted :param decimal_place default decimal place, default to 2 :return: a string in percentage format, 20.50% etc """ format_str = '{:.' + str(2) + '%}' return format_str.format(value) def get_name(last_name, first_name): """ Get name from last name and first name, if the name is in alpha, then use whitespace as the connect between them. :param last_name: Last name :param first_name: First name :return: last name + connect + first name, """ connect = '' if str(last_name).isalpha() and str(first_name).isalpha(): connect = ' ' return last_name + connect + first_name def get_pinyin_first_letters(chinese_characters): """ Get fist letters of pin yin of chinese characters, if there's any 多音字 All combinations will be returned, for example for "调向" Result of dx|tx will be returned. :param chinese_characters: Chinese characters to get pinyin. :return: first letters of pin yin of the letters """ pys = _get_pinyin_all([], chinese_characters) result = '' for py in pys: for p in py: result += p result += "|" result = result.rstrip('|') # <- Remove last "|" return result def _get_pinyin_all(existing_combinations, characters): """ Get all combinations of pinyin of some chinese characters as list, in a recurrence way, since format of result from pinyin is [['a'], ['b']] So a combination of two level loop is needed to get all the pinyin. :param existing_combinations: Existing combinations, for already calculated characters. :param characters: Characters to get combination of pinyin :return: A flat list of all combinations of pinyin for 多音字 """ first_character, other_characters = characters[0:1], characters[1:] if len(first_character) > 0: py = pinyin(first_character, style=pypinyin.FIRST_LETTER, heteronym=True) new_existing = [] for p in py: for a in p: if len(existing_combinations) > 0: for e in existing_combinations: ne = e[:] ne.append(a) new_existing.append(ne) else: ne = existing_combinations[:] ne.append(a) new_existing.append(ne) return _get_pinyin_all(new_existing, other_characters) return existing_combinations
Today’s New York Times has an interesting article on restaurant reservations (Julia Moskin, “Getting a Good Table by Flicking an App, Not Greasing a Palm,” Saturday, June 14, p. A1, As the title suggests, there are now various apps and online services that obtain hot restaurant reservations and then sell them to willing buyers. This process of course creates welfare gains for patrons who prefer paying to waiting in line (either physically or on endless telephone calls and redials). It can also create welfare gains for the restaurants themselves, both by reducing costly no-shows and sometimes by sharing in the revenue from the sale of the reservation. It is another example of the gains that can be realized by reducing transactions costs by using the internet and its progeny. Let’s be clear about the gains. Reservations at a restaurant are worth more at some times of the week (Saturday night) than at other times (Wednesday noon.) Restaurants capitalize on some of these differences – cheaper lunch menus are standard. But in general restaurants have not charged more for Friday or Saturday nights than for other days, probably because of high transactions costs of such differential pricing. These new services allow differential pricing by day of the week and other factors leading to different demand. This differential pricing is in the form of a fixed charge for reservations. If part of the premium goes to the restaurant itself, then the restaurant can increase revenue without changing menu prices. Ultimately this will lead either to increased supply of high end restaurants or to reduced menu prices, or likely some combination. Diners will benefit from reduced prices or increased availability, and restaurants will gain as well. There is an efficiency gain from saving the time wasted by diners in waiting for seats or reservations. Part of the gains will go to those developing the apps, as a reward for their efforts. Much of my recent writing has been about the dislike of markets, including an article (Folk Economics), my Presidential Address to the Southern Economic Association, and a Wall Street Journal op-ed. In the case of reservation apps, the dislike probably comes from a variant of the zero-sum fallacy – the view that new institutions redistribute money and the ignoring of real benefits created for all parties. But it is particularly sad that even successful entrepreneurs – the founders and owners of successful restaurants –do not understand the benefits from efficient institutional arrangements. Resistance to this practice may be rooted in perceptions of social class or rank. In other words, these tools enable those with greater means to buy their way to the head of the line. Now, we tolerate forms of this all the time, such as first class seating on airliners, and higher prices for the best seats at concerts, but for some, this may be one instance too many. This was the prompt, I think, to an identify-the-fallacy question on the LSAT a few years back. But I wouldn’t trust him — he got his JD via night school.