def test_config_create(self): f = tempfile.NamedTemporaryFile(mode='w+t', delete=False) f.write( '[jira_default]\nusername=username\npassword=password\nhost=host\npath=path' ) f.flush() c = config.Configuration(f.name) self.assertEqual(c.get('jira_default', 'username'), 'username') self.assertEqual(c.get('jira_default', 'password'), 'password') self.assertEqual(c.get('jira_default', 'host'), 'host') self.assertEqual(c.get('jira_default', 'path'), 'path') os.unlink(f.name)
def __init__(self, **kwargs): print >> sys.stderr, "python path is: " + ", ".join(sys.path) self.name = "demo_sequencer" # Read config file and check for errors self.config = config.Configuration(**kwargs) self.config.check() config.configure_logging(self.config) # Set up sequencer actions registry self.sequencer_actions_registry = galaxy.webapps.demo_sequencer.registry.Registry( self.config.root, self.config.sequencer_actions_config) # Security helper self.security = security.SecurityHelper( id_secret=self.config.id_secret)
def test_config_namespaces(self): # Tests the cache's ability to retrieve global or repository-specific # configuration entries. cfg_sub = config.Configuration('_foo') cfg_global = config.Configuration('*') config.set_for_repo('*', captcha_private_key='global_abcd', captcha_public_key='global_efgh', translate_api_key='global_hijk') assert cfg_global.captcha_private_key == 'global_abcd' assert cfg_global.captcha_public_key == 'global_efgh' assert cfg_global.translate_api_key == 'global_hijk' config.set_for_repo('_foo', captcha_private_key='abcd', captcha_public_key='efgh') assert cfg_sub.captcha_private_key == 'abcd' assert cfg_sub.captcha_public_key == 'efgh' # If a key isn't present for a repository, its value for # the global domain is retrieved. assert cfg_sub.translate_api_key == 'global_hijk'
def setup(self, request, *args, **kwargs): """Sets up the handler. Views aren't passed any request-specific information when they're initialized, so you can't really do much in __init__. However, having a function that gets called before dispatch is useful for all kinds of things (in particular, it's useful to have a top-down function, where the parent class functions run before those of subclasses). setup() is essentially a substitute for __init__(). Args: request (HttpRequest): The request object. *args: Unused. **kwargs: Arbitrary keyword arguments. Should include repository ID (under the key 'repo') if applicable. """ # pylint: disable=attribute-defined-outside-init # TODO(nworden): don't forget to call super.setup here once we upgrade # to Django 2.2. del request, args # unused # Set up the parameters and read in the base set of parameters. self.params = Params(self.request) self.params.read_values(get_params={'lang': utils.strip}, post_params={'lang': utils.strip}) # Set up env variable with data needed by the whole app. self.env = self.Env() self.env.repo = kwargs.get('repo', None) self.env.action = self.ACTION_ID self.env.config = config.Configuration(self.env.repo or '*') # Django will make a guess about what language to use, but Django's # guess should be overridden by the lang CGI param if it's set. # TODO(nworden): figure out how much of the logic below we still need # now that Django can do a lot of the work for us. lang = self.params.lang or self.request.LANGUAGE_CODE lang = re.sub('[^A-Za-z0-9-]', '', lang) lang = const.LANGUAGE_SYNONYMS.get(lang, lang) if lang in const.LANGUAGE_ENDONYMS.keys(): self.env.lang = lang else: self.env.lang = (self.env.config.language_menu_options[0] if self.env.config.language_menu_options else const.DEFAULT_LANGUAGE_CODE) self.env.rtl = self.env.lang in const.LANGUAGES_BIDI self.env.charset = const.CHARSET_UTF8 # TODO(nworden): try to eliminate use of global_url. It doesn't seem # great that templates are building URLs by sticking things onto this. self.env.global_url = self.build_absolute_uri('/global') self.env.fixed_static_url_base = self.build_absolute_uri('/static')
def parse_configs(config_files, base_em_dir): global is_cuda is_cuda = True configs = [] for config_file in config_files: config_file = base_em_dir+config_file+"/config.yaml" config = configuration.Configuration(model_type, config_file) config = config.config_dict is_cuda &= True if (str(config['gpu_core_num']).lower() != "none" and torch.cuda.is_available()) else False model = get_model(config) config_obj = {} config_obj['model'] = model config_obj['config']= config configs.append(config_obj) return configs
def test_edit_activation_status_config(self): # Set the time to an hour past the original update_date. utils.set_utcnow_for_test(datetime.datetime(2019, 5, 10, 12, 15, 0)) self.login_as_superadmin() self._post_with_params(activation_status=str( model.Repo.ActivationStatus.DEACTIVATED), deactivation_message_html='it is deactivated') repo = model.Repo.get_by_key_name('haiti') self.assertEqual(repo.activation_status, model.Repo.ActivationStatus.DEACTIVATED) repo_conf = config.Configuration('haiti') self.assertEqual(repo_conf.deactivation_message_html, 'it is deactivated') self.assertEqual( repo_conf.updated_date, utils.get_timestamp(datetime.datetime(2019, 5, 10, 12, 15, 0)))
def run_in_loop(hidden_layer_nodes_list, start_val, id, result_writer): for i in range(start_val, len(WIDTH_OF_HIDDEN_NODES)): hidden_layer_nodes_list[0] = WIDTH_OF_HIDDEN_NODES[i] # Create new configuration class instance with current settings configuration = config.Configuration( n_input=n_input, n_hidden_layers=len(hidden_layer_nodes_list), hidden_layer_nodes_list=hidden_layer_nodes_list, id=id) # Append labels with correct data and merge them into data_set print(len(feature_set)) print(len(label_set)) data_set = parse.create_data_set(feature_set, label_set) # Apply k-fold cross validation on data and repeat k times cross_validation(data_set, configuration, result_writer) print(hidden_layer_nodes_list)
def __init__(self, ): Window.__init__(self, "PasteWindow.glade") for lang in pastie.LANGS: self._glade.get_widget("syntax").append_text(lang) self._glade.get_widget("syntax").set_active( 0) #sets active posision in syntax list self._glade.get_widget("ok_button").connect("clicked", self._ok_button) self._glade.get_widget("cancel_button").connect( "clicked", lambda a: self._window.hide()) self.inform = Inform() self.config = config.Configuration() self.set_from_defaults() self.config.call_when_configuration_changes = self.set_from_defaults
def post(self, request, *args, **kwargs): """Serves POST requests, updating the repo's configuration.""" del request, args, kwargs # Unused. self.enforce_xsrf(self.ACTION_ID) validation_response = self._validate_input() if validation_response: return validation_response self._set_sms_config() self._set_repo_alias_config() self._set_site_info_config() self._set_recaptcha_config() self._set_ganalytics_config() self._set_gmaps_config() self._set_gtranslate_config() self._set_notification_config() # Reload the config since we just changed it. self.env.config = config.Configuration('*') return self._render_form()
def __init__( self, **kwargs ): print >> sys.stderr, "python path is: " + ", ".join( sys.path ) # Read config file and check for errors self.config = config.Configuration( **kwargs ) self.config.check() config.configure_logging( self.config ) # Determine the database url if self.config.database_connection: db_url = self.config.database_connection else: db_url = "sqlite://%s?isolation_level=IMMEDIATE" % self.config.database # Setup the database engine and ORM self.model = galaxy.model.mapping.init( self.config.file_path, db_url, self.config.database_engine_options, create_tables = True ) # Security helper self.security = security.SecurityHelper( id_secret=self.config.id_secret )
def __init__(self): b = Binance() c = config.Configuration() df = pd.DataFrame(columns=('datetime', 'price')) df.to_csv('index_price_log.csv') print('index log initialized') count = 0 while True: try: b.execute_trade() except Exception as e: print('_______ERROR_______\n', e) count += 1 if count == 10: print(dt.datetime.utcnow().strftime("%Y-%m-%d %H:%M"), ' ETH price:', b.get_price(c.trading_pair, False)) count = 0 time.sleep(c.time_interval)
def write_entry(self, file, repo, indent): repo_config = config.Configuration(repo) file.write(indent + '<entry>\n') write_element(file, 'id', '%s/%s' % (ROOT_URL, repo), indent + ' ') write_element(file, 'published', format_utc_timestamp(repo_config.published_date), indent + ' ') write_element(file, 'updated', format_utc_timestamp(repo_config.updated_date), indent + ' ') default_language = (repo_config.language_menu_options or [])[:1] self.write_titles(file, 'title', default_language, repo_config.repo_titles, indent + ' ') file.write(indent + ' <content type="text/xml">\n') file.write(indent + ' <gpf:repo>\n') self.write_fields(file, repo_config, indent + ' ' * 6) file.write(indent + ' </gpf:repo>\n') file.write(indent + ' </content>\n') file.write(indent + '</entry>\n')
def __init__(self, **kwargs): print >> sys.stderr, "python path is: " + ", ".join(sys.path) self.name = "community" # Read config file and check for errors self.config = config.Configuration(**kwargs) self.config.check() config.configure_logging(self.config) # Set up datatypes registry self.datatypes_registry = galaxy.datatypes.registry.Registry() self.datatypes_registry.load_datatypes(self.config.root, self.config.datatypes_config) # Determine the database url if self.config.database_connection: db_url = self.config.database_connection else: db_url = "sqlite:///%s?isolation_level=IMMEDIATE" % self.config.database # Initialize database / check for appropriate schema version from galaxy.webapps.community.model.migrate.check import create_or_verify_database create_or_verify_database(db_url, self.config.database_engine_options) # Setup the database engine and ORM from galaxy.webapps.community.model import mapping self.model = mapping.init(self.config.file_path, db_url, self.config.database_engine_options) # Security helper self.security = security.SecurityHelper( id_secret=self.config.id_secret) # Tag handler self.tag_handler = CommunityTagHandler() # Tool data tables - never pass a config file here because the tool shed should always have an empty dictionary! self.tool_data_tables = galaxy.tools.data.ToolDataTableManager( self.config.tool_data_path) # The tool shed has no toolbox, but this attribute is still required. self.toolbox = tools.ToolBox([], self.config.tool_path, self) # Load security policy self.security_agent = self.model.security_agent self.quota_agent = galaxy.quota.NoQuotaAgent(self.model) # TODO: Add OpenID support self.openid_providers = OpenIDProviders() self.shed_counter = self.model.shed_counter # Let the HgwebConfigManager know where the hgweb.config file is located. self.hgweb_config_manager = self.model.hgweb_config_manager self.hgweb_config_manager.hgweb_config_dir = self.config.hgweb_config_dir print >> sys.stderr, "Tool shed hgweb.config file is: ", self.hgweb_config_manager.hgweb_config
def register_repositories(self): # links each repo in config.json to their corresponding credentials logger.debug("registering repository") configuration = config.Configuration('config.json') repos = {} for repo in configuration.get('repos'): repo_type = repo.get('type') if repo_type == 'perforce': repo_name = repo.get('name') creds = config.credential_manager.get_or_create_credentials_for( repo_name, "password") if creds is None: logger.error("Failed to load credentials") return {} repo_source = PerforceSource(creds=creds, port=repo.get('server'), directory=repo.get('directory')) repos[repo_name] = { "source": repo_source, "check-every-x-minutes": 10 } elif repo_type == 'github': repo_name = repo.get('name') creds = config.credential_manager.get_or_create_credentials_for( repo_name, "password") if creds is None: logger.error("Failed to load credentials") return {} repo_source = GithubSource(creds=creds, host=repo.get('server'), owner=repo.get('owner'), repo=repo.get('directory')) repos[repo_name] = { "source": repo_source, "check-every-x-minutes": 10 } else: print "Repo Type not supported yet: " + repo_type return repos
def __init(self, *args): self.main_window = args[0] self.config = config.Configuration() self.icon = egg.trayicon.TrayIcon(NAME) self.eb = gtk.EventBox() self.eb.set_visible_window(False) self.eb.set_events(gtk.gdk.POINTER_MOTION_MASK) self.image = gtk.Image() self.image.set_from_icon_name(NAME.lower(), gtk.ICON_SIZE_BUTTON) self.eb.add(self.image) self.icon.add(self.eb) self.__build_context_menu() self.__connect_widgets() self.icon.show_all()
def post(self, request, *args, **kwargs): """Serves POST requests, updating the repo's configuration.""" del request, args, kwargs # Unused. self.enforce_xsrf(self.ACTION_ID) validation_response = self._validate_input() if validation_response: return validation_response self._set_language_config() self._set_activation_config() self._set_data_retention_config() self._set_keywords_config() self._set_forms_config() self._set_map_config() self._set_timezone_config() self._set_api_access_control_config() self._set_zero_rating_config() self._set_spam_config() # Reload the config since we just changed it. self.env.config = config.Configuration(self.env.repo) return self._render_form()
def __init__(self, *args, **kwargs): '''Please see help(Applicatioon) for more info.''' # Initialize the application and set the icon super().__init__(*args, **kwargs) self.icon = self._get_resource('icon-desaturated.icns') # Get the application support directory of the toontown engine self._toontown = rumps.application_support('Toontown Rewritten') # Initialize the configuration file and menu self.config = config.Configuration(self, 'config.ini') self.initialize_menu() # Initialize the invasion tracker and start if necessary self._interval = self.config.get_setting('interval') self._invasion_timer = rumps.Timer(self._get_invasions, self._interval) self._tracker = tooner.InvasionTracker() self._invasions = {} if self._track_option.state: self._invasion_timer.start()
def test_edit_forms_config(self): self.login_as_superadmin() self._post_with_params( use_family_name='true', family_name_first='true', use_alternate_names='true', use_postal_code='true', allow_believed_dead_via_ui='true', min_query_word_length='2', show_profile_entry='true', # The value for this doesn't really matter. profile_websites='{"arbitrary": "json"}') repo_conf = config.Configuration('haiti') self.assertIs(repo_conf.use_family_name, True) self.assertIs(repo_conf.family_name_first, True) self.assertIs(repo_conf.use_alternate_names, True) self.assertIs(repo_conf.use_postal_code, True) self.assertIs(repo_conf.allow_believed_dead_via_ui, True) self.assertEqual(repo_conf.min_query_word_length, 2) self.assertIs(repo_conf.show_profile_entry, True) self.assertEqual(repo_conf.profile_websites, {'arbitrary': 'json'})
def test_manager_edit_restrictions(self): self.login_as_manager() self._post_with_params(use_family_name='true', family_name_first='true', use_alternate_names='true', use_postal_code='true', allow_believed_dead_via_ui='true', min_query_word_length='2', show_profile_entry='true', map_default_zoom='8', map_default_center='[32.7, 85.6]', map_size_pixels='[300, 450]', time_zone_offset='5.75', time_zone_abbreviation='NPT', search_auth_key_required='true', read_auth_key_required='true', zero_rating_mode='true', bad_words='voldemort') repo_conf = config.Configuration('haiti') for key, value in AdminRepoIndexViewTests._PRIOR_CONFIG.items(): self.assertEqual(repo_conf.get(key), value)
def run(): id = 1 # Prepare data sets feature_set, label_set, data_size = parse.create_feature_label_set( features_file=config.FEATURES_FILE, labels_file=config.LABELS_FILE) # Prepare output file csv_file = open(config.OUTPUT_FILE, mode="w") result_writer = csv.writer(csv_file) result_writer.writerow( ('Id', 'Epochs', 'Learning rate', 'Keep rate', 'Accuracy')) # create new configuration class instance configuration = config.Configuration(id=id) id = id + 1 # Apply k-fold cross validation on data and repeat k times cross_validation(feature_set, label_set, configuration, result_writer, data_size) csv_file.close()
def _alert_callback(alert_action): alert_config_key = alert_action.get("alert config") alert_config = self._alert_configs.get(alert_config_key) if alert_config is None: logger.error("Alert config for [%s] is None", alert_config_key); return if alert_config.get("email"): default_email = config.Configuration('config.json').get(('email', 'to')) to_email = alert_config.get("email", default_email) patch_lines = u'\n'.join(repo_patch.diff.additions).encode('utf-8').strip() subject = alert_action.get("subject","Unknown Subject") (text, html) = self.create_alert_email(subject, data, repo_patch.repo_commit) ea = EmailAlert(Alert(subject=subject, message=text.encode('utf-8'), message_html=html.encode('utf-8')), to_email=to_email) if (self.test_mode == True): print ea else: ea.send() else: logger.warn("Alert type unknown %s" % (alert_config))
def put(self, key=config.CONFIG_SINGLETON_KEY): model_key = ndb.Key(config.Configuration, key) old_model = model_key.get() if not old_model: raise NotFound('{} with key {} does not exist'.format('Configuration', key)) # the history mechanism doesn't work unless we make a copy. So a put is always a clone, never # an actual update. model = config.Configuration(**old_model.to_dict()) model.key = model_key model.configuration = request.get_json(force=True) self.validate(model) date = None if config.getSettingJson(config.ALLOW_NONPROD_REQUESTS, False): date = request.headers.get('x-pretend-date', None) if date is not None: date = parse_date(date) client_id = app_util.get_oauth_id() config.store(model, date=date, client_id=client_id) return model.configuration
def __get_options(self): """Get command line options.""" try: opts, args = getopt.getopt(sys.argv[1:], "dh", ["debug", "header=", "help"]) except getopt.GetoptError: opts = [] args = sys.argv[1:] debug = False headers = {} for o, a in opts: if o in ("-d", "--debug"): debug = True elif o in ("--header"): kv = a.split("=") if (len(kv) == 2): headers[kv[0]] = kv[1] elif o in ("-h", "--help"): self.__print_usage() self.config = config.Configuration(debug) return [args, headers]
def __init__(self, download): self.download = download self.config = config.Configuration() self.status_icon = TrayIcon() pynotify.init(NAME) self.notification = pynotify.Notification( _("Download Completed"), _("%s has been downloaded successfully.") % self.download.file_name) if self.download.pixbuf: self.notification.set_icon_from_pixbuf(self.download.pixbuf) else: pixbuf = gui.load_icon(NAME.lower(), 32, 32) self.notification.set_icon_from_pixbuf(pixbuf) # Position notification at status icon if its shown if self.config.show_status_icon: # self.notification.attach_to_status_icon(self.status_icon.icon) (x, y) = self.__get_position() self.notification.set_hint_int32("x", x) self.notification.set_hint_int32("y", y) self.notification.set_timeout(TIMEOUT) # One minute if not download.is_metalink: self.notification.add_action("file", _("Open"), self.__action_invoked) self.notification.add_action("folder", _("Open folder"), self.__action_invoked) self.notification.connect("closed", self.__closed) if not self.notification.show(): print "Failed to show notification."
def __init__( self, **kwargs ): print >> sys.stderr, "python path is: " + ", ".join( sys.path ) # Read config file and check for errors self.config = config.Configuration( **kwargs ) self.config.check() config.configure_logging( self.config ) # Set up datatypes registry self.datatypes_registry = galaxy.datatypes.registry.Registry() # TODO: Handle datatypes included in repositories - the following will only load datatypes_conf.xml. self.datatypes_registry.load_datatypes( self.config.root, self.config.datatypes_config ) # Determine the database url if self.config.database_connection: db_url = self.config.database_connection else: db_url = "sqlite://%s?isolation_level=IMMEDIATE" % self.config.database # Initialize database / check for appropriate schema version from galaxy.webapps.community.model.migrate.check import create_or_verify_database create_or_verify_database( db_url, self.config.database_engine_options ) # Setup the database engine and ORM from galaxy.webapps.community.model import mapping self.model = mapping.init( self.config.file_path, db_url, self.config.database_engine_options ) # Security helper self.security = security.SecurityHelper( id_secret=self.config.id_secret ) # Tag handler self.tag_handler = CommunityTagHandler() # Tool data tables self.tool_data_tables = galaxy.tools.data.ToolDataTableManager( self.config.tool_data_table_config_path ) # The tool shed has no toolbox, but this attribute is still required. self.toolbox = None # Load security policy self.security_agent = self.model.security_agent self.quota_agent = galaxy.quota.NoQuotaAgent( self.model ) # TODO: Add OpenID support self.openid_providers = OpenIDProviders() self.shed_counter = self.model.shed_counter
def __init__(self, **kwargs): print >> sys.stderr, "python path is: " + ", ".join(sys.path) self.name = "reports" # Read config file and check for errors self.config = config.Configuration(**kwargs) self.config.check() config.configure_logging(self.config) # Determine the database url if self.config.database_connection: db_url = self.config.database_connection else: db_url = "sqlite:///%s?isolation_level=IMMEDIATE" % self.config.database # Setup the database engine and ORM self.model = galaxy.model.mapping.init( self.config.file_path, db_url, self.config.database_engine_options, create_tables=True) self.targets_mysql = self.config.database_connection and 'mysql' in self.config.database_connection # Security helper self.security = security.SecurityHelper( id_secret=self.config.id_secret) # used for cachebusting -- refactor this into a *SINGLE* UniverseApplication base. self.server_starttime = int(time.time())
def test_create_repo(self): """Tests POST requests to create a new repo.""" get_doc = self.to_doc(self.client.get( '/global/admin/create_repo/', secure=True)) xsrf_token = get_doc.cssselect_one('input[name="xsrf_token"]').get( 'value') post_resp = self.client.post('/global/admin/create_repo/', { 'xsrf_token': xsrf_token, 'new_repo': 'idaho' }, secure=True) # Check that the user's redirected to the repo's main admin page. self.assertIsInstance(post_resp, django.http.HttpResponseRedirect) self.assertEqual(post_resp.url, '/idaho/admin') # Check that the repo object is put in datastore. repo = model.Repo.get_by_key_name('idaho') self.assertIsNotNone(repo) self.assertEqual( repo.activation_status, model.Repo.ActivationStatus.STAGING) self.assertIs(repo.test_mode, False) # Check a couple of the config fields that are set by default. repo_conf = config.Configuration('idaho') self.assertEqual(repo_conf.language_menu_options, ['en', 'fr']) self.assertIs(repo_conf.launched, False) self.assertEqual(repo_conf.time_zone_abbreviation, 'UTC')
def __init__(self, uri="", headers={}): self.headers = headers self.config = config.Configuration() self.__get_widgets() self.__connect_widgets() self.clipboard = gtk.Clipboard(selection="PRIMARY") self.owner_change_id = self.clipboard.connect("owner-change", self.__clipboard_owner_change) if uri: self.uri_entry.set_text(uri) else: self.uri_entry.set_text(gui.get_uri_from_clipboard() or "") # self.uri_entry.paste_clipboard() # self.uri_entry.select_region(0, -1) folder = utils.get_folder_for_extension(uri) if not folder: folder = self.config.default_folder self.download_filechooserbutton.set_current_folder(folder) self.download = None
def setup_env(request): """Constructs the 'env' object, which contains various template variables that are commonly used by most handlers.""" env = utils.Struct() env.repo, env.action = get_repo_and_action(request) env.config = config.Configuration(env.repo or '*') env.analytics_id = config.get('analytics_id') env.amp_gtm_id = config.get('amp_gtm_id') env.maps_api_key = config.get('maps_api_key') # Internationalization-related stuff. env.charset = select_charset(request) env.lang = select_lang(request, env.config) env.rtl = env.lang in const.LANGUAGES_BIDI env.virtual_keyboard_layout = const.VIRTUAL_KEYBOARD_LAYOUTS.get(env.lang) # Used for parsing query params. This must be done before accessing any # query params which may have multi-byte value, such as "given_name" below # in this function. request.charset = env.charset # Determine the resource bundle to use. env.default_resource_bundle = config.get('default_resource_bundle', '1') env.resource_bundle = (request.cookies.get('resource_bundle', '') or env.default_resource_bundle) # Information about the request. env.url = utils.set_url_param(request.url, 'lang', env.lang) env.scheme, env.netloc, env.path, _, _ = urlparse.urlsplit(request.url) env.force_https = False env.domain = env.netloc.split(':')[0] env.global_url = utils.get_repo_url(request, 'global') # Commonly used information that's rendered or localized for templates. env.language_options = get_language_options(request, env.config, env.lang) env.repo_options = get_repo_options(request, env.lang) env.expiry_options = [ utils.Struct(value=value, text=const.PERSON_EXPIRY_TEXT[value]) for value in sorted(const.PERSON_EXPIRY_TEXT.keys(), key=int) ] env.status_options = [ utils.Struct(value=value, text=const.NOTE_STATUS_TEXT[value]) for value in pfif.NOTE_STATUS_VALUES if (value != 'believed_dead' or not env.config or env.config.allow_believed_dead_via_ui) ] env.hidden_input_tags_for_preserved_query_params = ( get_hidden_input_tags_for_preserved_query_params(request)) ui_param = request.get('ui', '').strip().lower() # Interprets "small" and "style" parameters for backward compatibility. # TODO(ichikawa): Delete these in near future when we decide to drop # support of these parameters. small_param = request.get('small', '').strip().lower() style_param = request.get('style', '').strip().lower() if not ui_param and small_param == 'yes': ui_param = 'small' elif not ui_param and style_param: ui_param = style_param if ui_param: env.ui = ui_param elif user_agents.is_jp_tier2_mobile_phone(request): env.ui = 'light' else: env.ui = 'default' # UI configurations. # # Enables features which require JavaScript. env.enable_javascript = True # Enables operations which requires Captcha. env.enable_captcha = True # Enables photo upload. env.enable_photo_upload = True # Enables to flag/unflag notes as spam, and to reveal spam notes. env.enable_spam_ops = True # Enables duplicate marking mode. env.enable_dup_mode = True # Shows a logo on top of the page. env.show_logo = True # Shows language menu. env.show_language_menu = True # Uses short labels for buttons. env.use_short_buttons = False # Optional "target" attribute for links to non-small pages. env.target_attr = '' # Shows record IDs in the results page. env.show_record_ids_in_results = True # Shows non AMP HTML pages by default. env.amp = False if env.ui == 'small': env.show_logo = False env.target_attr = ' target="_blank" ' elif env.ui == 'light': # Disables features which requires JavaScript. Some feature phones # doesn't support JavaScript. env.enable_javascript = False # Disables operations which requires Captcha because Captcha requires # JavaScript. env.enable_captcha = False # Uploading is often not supported in feature phones. env.enable_photo_upload = False # Disables spam operations because it requires JavaScript and # supporting more pages on ui=light. env.enable_spam_ops = False # Disables duplicate marking mode because it doesn't support # small screens and it requires JavaScript. env.enable_dup_mode = False # Hides the logo on the top to save the space. Also, the logo links # to the global page which doesn't support small screens. env.show_logo = False # Hides language menu because the menu in the current position is # annoying in feature phones. # TODO(ichikawa): Consider layout of the language menu. env.show_language_menu = False # Too long buttons are not fully shown in some feature phones. env.use_short_buttons = True # To make it simple. env.show_record_ids_in_results = False env.back_chevron = u'\xab' back_chevron_in_charset = True try: env.back_chevron.encode(env.charset) except UnicodeEncodeError: # u'\xab' is not in the charset (e.g. Shift_JIS). back_chevron_in_charset = False if not back_chevron_in_charset or env.ui == 'light': # Use ASCII characters on ui=light too because some feature phones # support UTF-8 but don't render UTF-8 symbols such as u'\xab'. env.back_chevron = u'<<' env.enable_maps = (env.enable_javascript and not env.config.zero_rating_mode and env.maps_api_key) env.enable_analytics = (env.enable_javascript and not env.config.zero_rating_mode and env.analytics_id) env.enable_translate = (env.enable_javascript and not env.config.zero_rating_mode and env.config.translate_api_key) env.admin = AdminEnv(request) # Repo-specific information. if env.repo: # repo_url is the root URL for the repository. env.repo_url = utils.get_repo_url(request, env.repo) # start_url is like repo_url but preserves parameters such as 'ui'. env.start_url = utils.get_url(request, env.repo, '') # URL of the link in the heading. The link on ui=small links to the # normal UI. env.repo_title_url = (env.repo_url if env.ui == 'small' else env.start_url) # URL to force default UI. Note that we show ui=light version in some # user agents when ui parameter is not specified. env.default_ui_url = utils.get_url(request, env.repo, '', ui='default') env.repo_path = urlparse.urlsplit(env.repo_url)[2] env.repo_title = get_localized_message(env.config.repo_titles, env.lang, '?') env.start_page_custom_html = get_localized_message( env.config.start_page_custom_htmls, env.lang, '') env.results_page_custom_html = get_localized_message( env.config.results_page_custom_htmls, env.lang, '') env.view_page_custom_html = get_localized_message( env.config.view_page_custom_htmls, env.lang, '') env.seek_query_form_custom_html = get_localized_message( env.config.seek_query_form_custom_htmls, env.lang, '') env.footer_custom_html = get_localized_message( env.config.footer_custom_htmls, env.lang, '') # If the repository is deactivated, we should not show test mode # notification. env.repo_test_mode = (env.config.test_mode and not env.config.deactivated) env.force_https = env.config.force_https env.params_full_name = request.get('full_name', '').strip() if not env.params_full_name: # Preformat the name from 'given_name' and 'family_name' parameters. given_name = request.get('given_name', '').strip() family_name = request.get('family_name', '').strip() env.params_full_name = utils.get_full_name(given_name, family_name, env.config) return env
str(email_address)) return False if len(break_up_email.groups()) != 3: logger.error("Email address [%s] did not parse correctly", str(email_address)) return False safe_to_email = "@".join( (break_up_email.groups()[0], break_up_email.groups()[2])) safe_to_email_addresses.append(safe_to_email) s.sendmail(from_email, safe_to_email_addresses, msg.as_string()) logger.info("Email sent to [%s] with subject [%s]", msg['To'], msg['Subject']) s.quit() return True if __name__ == "__main__": templateVars = { "title": "Test Example 3", "description": "A simple inquiry of function.", "rule": "Rule test X", "github_link": "#", "code": "\n".join(["a", "b", "c"]) } (text, html) = EmailAlert.email_templates(templateVars, "templates/test_email.txt", "templates/test.html") EmailAlert().send(Alert(message=text, message_html=html), to_email=config.Configuration('config.json').get( ('email', 'to')))