def show_in_panel(cls, panel_name, message_str):
panel = cls.panels.get(panel_name)
window = sublime.active_window()
if not panel:
panel = window.get_output_panel(panel_name)
panel.settings().set('syntax', 'Packages/Java/Java.tmLanguage')
panel.settings().set('color_scheme', 'Packages/Color Scheme - Default/Monokai.tmTheme')
panel.settings().set('word_wrap', True)
panel.settings().set('gutter', True)
panel.settings().set('line_numbers', True)
cls.panels[panel_name] = panel
window.run_command('show_panel', {
'panel': 'output.' + panel_name
})
if message_str:
message_str += '\n'
panel.run_command("append", {
"characters": message_str
})
python类get()的实例源码
def del_comment(soql):
result = soql
if soql:
# TODO
# soql = soql.strip().replace('\t', ' ').replace('\r\n', ' ').replace('\n', ' ')
soql = soql.strip().replace('\t', ' ')
# delete // comment
result1, number = re.subn("//.*", "", soql)
# delete /**/ comment
result, number = re.subn("/\*([\s|\S]*?)\*/", "", result1, flags=re.M)
result = result.strip()
# show_in_panel(result)
return result
# get sobject name from soql
def _delayed_open_web_browser(url, delay, new=0, autoraise=True, specific_browser=None):
'''
Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the
same time. Insert a small sleep before opening a web-browser
this gives Flask a chance to start running before the browser starts requesting data from Flask.
'''
def _sleep_and_open_web_browser(url, delay, new, autoraise, specific_browser):
sleep(delay)
browser = webbrowser
# E.g. On OSX the following would use the Chrome browser app from that location
# specific_browser = 'open -a /Applications/Google\ Chrome.app %s'
if specific_browser:
browser = webbrowser.get(specific_browser)
browser.open(url, new=new, autoraise=autoraise)
thread = Thread(target=_sleep_and_open_web_browser,
kwargs=dict(url=url, new=new, autoraise=autoraise, delay=delay, specific_browser=specific_browser))
thread.daemon = True # Force to quit on main quitting
thread.start()
def attempt_open(url):
import os
import webbrowser
if 'DISPLAY' not in os.environ:
print('The DISPLAY variable is not set, so not attempting to open a web browser\n')
return False
for name in 'windows-default chrome chromium mozilla firefox opera safari'.split():
# LATER: prepend `macosx` to this list when <http://bugs.python.org/issue30392> is fixed.
try:
b = webbrowser.get(name)
except:
pass
else:
if b.open(url):
return True
return False
def handleRequest(self, env, start_response):
path = env["PATH_INFO"]
if env.get("QUERY_STRING"):
get = dict(cgi.parse_qsl(env['QUERY_STRING']))
else:
get = {}
ui_request = UiRequest(self, get, env, start_response)
if config.debug: # Let the exception catched by werkezung
return ui_request.route(path)
else: # Catch and display the error
try:
return ui_request.route(path)
except Exception, err:
logging.debug("UiRequest error: %s" % Debug.formatException(err))
return ui_request.error500("Err: %s" % Debug.formatException(err))
# Reload the UiRequest class to prevent restarts in debug mode
flask_socket_helpers.py 文件源码
项目:Cozmo-Explorer-Tool
作者: GrinningHermit
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def _delayed_open_web_browser(url, delay, new=0, autoraise=True, specific_browser=None):
"""
Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the
same time. Insert a small sleep before opening a web-browser
this gives Flask a chance to start running before the browser starts requesting data from Flask.
"""
def _sleep_and_open_web_browser(url, delay, new, autoraise, specific_browser):
sleep(delay)
browser = webbrowser
# E.g. On OSX the following would use the Chrome browser app from that location
# specific_browser = 'open -a /Applications/Google\ Chrome.app %s'
if specific_browser:
browser = webbrowser.get(specific_browser)
browser.open(url, new=new, autoraise=autoraise)
thread = Thread(target=_sleep_and_open_web_browser,
kwargs=dict(url=url, new=new, autoraise=autoraise, delay=delay, specific_browser=specific_browser))
thread.daemon = True # Force to quit on main quitting
thread.start()
def generateNewTorrentAPIToken(error=False):
global auth_token
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'}
refresh_url = 'https://torrentapi.org/pubapi_v2.php?get_token=get_token'
try:
auth_token = json.loads(requests.get(refresh_url, headers=headers).text)['token'].encode('utf-8')
if error != False:
success_string = '[RARBG] Success : Generated new token! '
print colored.blue(success_string)
except requests.exceptions.ConnectionError, e:
err_string = str(e).split(',')[0]
if 'Connection aborted' in err_string:
print colored.red("Server cannot be reached. Check Internet connectivity!")
sys.exit(1)
except SysCallError, e:
print colored.red("SysCallError for RARBG search. Fix?")
def searchRarbg(search_string=defaultQuery):
global auth_token, results_rarbg, error_detected_rarbg
# API Documentaion : https://torrentapi.org/apidocs_v2.txt
# https://torrentapi.org/pubapi_v2.php?mode=search&search_string=Suits%20S06E10&format=json_extended&ranked=0&token=cy6xjhtmev
generateNewTorrentAPIToken()
search_string = search_string.replace(" ", "%20")
base_url = 'https://torrentapi.org/pubapi_v2.php?'
new_token = 'get_token=get_token'
search_criteria = 'mode=search&search_string=' + search_string + "&"
options = 'format=json_extended&ranked=0&token=' + auth_token
url = base_url + search_criteria + options
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'}
response = requests.get(url, headers=headers)
response_json = json.loads(response.text)
#print response_json
results_rarbg = []
error_detected_rarbg = checkResponseForErrors(response_json)
if(error_detected_rarbg == False):
results_rarbg = parse_results_rarbg(response_json)
return results_rarbg
def module_run(self):
sources = self.query('SELECT COUNT(source), source FROM pushpins GROUP BY source')
media_content, map_content = self.build_content(sources)
meta_content = (self.options['latitude'], self.options['longitude'], self.options['radius'])
# create the media report
media_content = meta_content + media_content
media_filename = self.options['media_filename']
self.write_markup(os.path.join(self.data_path, 'template_media.html'), media_filename, media_content)
self.output('Media data written to \'%s\'' % (media_filename))
# order the map_content tuple
map_content = meta_content + map_content
order=[4,0,1,2,3,5]
map_content = tuple([map_content[i] for i in order])
# create the map report
map_filename = self.options['map_filename']
self.write_markup(os.path.join(self.data_path, 'template_map.html'), map_filename, map_content)
self.output('Mapping data written to \'%s\'' % (map_filename))
# open the reports in a browser
w = webbrowser.get()
w.open(media_filename)
time.sleep(2)
w.open(map_filename)
def dispres(url):
"""
Display result page
:param url: URL of the search result
:return:
"""
global question_post
global header_for_display
global LOOP
randomheaders()
res_page = requests.get(url, headers=header)
captchacheck(res_page.url)
header_for_display = Header()
question_title, question_desc, question_stats, answers = get_question_stats_and_answer(url)
question_post = QuestionPage((answers, question_title, question_desc, question_stats, url))
LOOP = EditedMainLoop(question_post, palette)
LOOP.run()
def __init__(self):
"""Class constructor."""
self._fields_to_check = ['description', 'name', 'summary', 'reviews']
self._minimum_monthly_discount = int(settings.get('MINIMUM_MONTHLY_DISCOUNT', None))
self._minimum_weekly_discount = int(settings.get('MINIMUM_WEEKLY_DISCOUNT', None))
self._skip_list = settings.get('SKIP_LIST', None)
self._cannot_have_regex = settings.get('CANNOT_HAVE', None)
if self._cannot_have_regex:
self._cannot_have_regex = re.compile(str(self._cannot_have_regex), re.IGNORECASE)
self._must_have_regex = settings.get('MUST_HAVE', None)
if self._must_have_regex:
self._must_have_regex = re.compile(str(self._must_have_regex), re.IGNORECASE)
self._web_browser = settings.get('WEB_BROWSER', None)
if self._web_browser:
self._web_browser += ' %s' # append URL placeholder (%s)
def select_and_open (url, cfg):
"""Select the browser to use via configuration and open the URL"""
# set default browser
log.debug("Initialise with default browser")
selected_browser = webbrowser.get(cfg.browser_default)
# set browser according to rules
for r in cfg.rules:
url_pattern = r.get('url_pattern')
url_replace = r.get('url_replace')
browser_id = r.get('browser_id')
if isinstance(url_pattern, basestring):
p = re.compile(url_pattern)
if p.search(url):
if isinstance(url_replace, basestring):
url = p.sub(url_replace, url)
if isinstance(browser_id, basestring):
log.debug("-- Set browser to browser '%s'" % browser_id)
selected_browser = webbrowser.get(browser_id)
log.info("Selected browser: '%s %s'" % (selected_browser.name,
' '.join(selected_browser.args)))
log.info("URL to open via 'open_new_tab': '%s'" % url)
selected_browser.open_new_tab(url)
log.debug("'open_new_tab' done")
def sf_oauth2():
from .libs import auth
settings = setting.load()
default_project_value = settings["default_project_value"]
is_sandbox = default_project_value["is_sandbox"]
if refresh_token():
return
server_info = sublime.load_settings("sfdc.server.sublime-settings")
client_id = server_info.get("client_id")
client_secret = server_info.get("client_secret")
redirect_uri = server_info.get("redirect_uri")
oauth = auth.SalesforceOAuth2(client_id, client_secret, redirect_uri, is_sandbox)
authorize_url = oauth.authorize_url()
print('authorize_url-->')
print(authorize_url)
start_server()
open_in_default_browser(authorize_url)
def _delayed_open_web_browser(url, delay, new=0, autoraise=True, specific_browser=None):
'''
Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the
same time. Insert a small sleep before opening a web-browser
this gives Flask a chance to start running before the browser starts requesting data from Flask.
'''
def _sleep_and_open_web_browser(url, delay, new, autoraise, specific_browser):
sleep(delay)
browser = webbrowser
# E.g. On OSX the following would use the Chrome browser app from that location
# specific_browser = 'open -a /Applications/Google\ Chrome.app %s'
if specific_browser:
browser = webbrowser.get(specific_browser)
browser.open(url, new=new, autoraise=autoraise)
thread = Thread(target=_sleep_and_open_web_browser,
kwargs=dict(url=url, new=new, autoraise=autoraise, delay=delay, specific_browser=specific_browser))
thread.daemon = True # Force to quit on main quitting
thread.start()
def _delayed_open_web_browser(url, delay, new=0, autoraise=True, specific_browser=None):
'''
Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the
same time. Insert a small sleep before opening a web-browser
this gives Flask a chance to start running before the browser starts requesting data from Flask.
'''
def _sleep_and_open_web_browser(url, delay, new, autoraise, specific_browser):
sleep(delay)
browser = webbrowser
# E.g. On OSX the following would use the Chrome browser app from that location
# specific_browser = 'open -a /Applications/Google\ Chrome.app %s'
if specific_browser:
browser = webbrowser.get(specific_browser)
browser.open(url, new=new, autoraise=autoraise)
thread = Thread(target=_sleep_and_open_web_browser,
kwargs=dict(url=url, new=new, autoraise=autoraise, delay=delay, specific_browser=specific_browser))
thread.daemon = True # Force to quit on main quitting
thread.start()
def module_run(self):
sources = self.query('SELECT COUNT(source), source FROM pushpins GROUP BY source')
media_content, map_content = self.build_content(sources)
meta_content = (self.options['latitude'], self.options['longitude'], self.options['radius'])
# create the media report
media_content = meta_content + media_content
media_filename = self.options['media_filename']
self.write_markup(os.path.join(self.data_path, 'template_media.html'), media_filename, media_content)
self.output('Media data written to \'%s\'' % (media_filename))
# order the map_content tuple
map_content = meta_content + map_content
order=[4,0,1,2,3,5]
map_content = tuple([map_content[i] for i in order])
# create the map report
map_filename = self.options['map_filename']
self.write_markup(os.path.join(self.data_path, 'template_map.html'), map_filename, map_content)
self.output('Mapping data written to \'%s\'' % (map_filename))
# open the reports in a browser
w = webbrowser.get()
w.open(media_filename)
time.sleep(2)
w.open(map_filename)
def _solve_google_captcha(self, resp):
# set up the captcha page markup for parsing
tree = fromstring(resp.text)
# extract and request the captcha image
resp = self.request('https://ipv4.google.com' + tree.xpath('//img/@src')[0], redirect=False, cookiejar=self.cookiejar, agent=self.user_agent)
# store the captcha image to the file system
with tempfile.NamedTemporaryFile(suffix='.jpg') as fp:
fp.write(resp.raw)
fp.flush()
# open the captcha image for viewing in gui environments
w = webbrowser.get()
w.open('file://' + fp.name)
self.alert(fp.name)
_payload = {'captcha':raw_input('[CAPTCHA] Answer: ')}
# temporary captcha file removed on close
# extract the form elements for the capctah answer request
form = tree.xpath('//form[@action="CaptchaRedirect"]')[0]
for x in ['continue', 'id', 'submit']:
_payload[x] = form.xpath('//input[@name="%s"]/@value' % (x))[0]
# send the captcha answer
return self.request('https://ipv4.google.com/sorry/CaptchaRedirect', payload=_payload, cookiejar=self.cookiejar, agent=self.user_agent)
def browse_website(self, browser=None):
"""
Launch web browser at project's homepage
@param browser: name of web browser to use
@type browser: string
@returns: 0 if homepage found, 1 if no homepage found
"""
if len(self.all_versions):
metadata = self.pypi.release_data(self.project_name, \
self.all_versions[0])
self.logger.debug("DEBUG: browser: %s" % browser)
if metadata.has_key("home_page"):
self.logger.info("Launching browser: %s" \
% metadata["home_page"])
if browser == 'konqueror':
browser = webbrowser.Konqueror()
else:
browser = webbrowser.get()
browser.open(metadata["home_page"], 2)
return 0
self.logger.error("No homepage URL found.")
return 1
def browse_website(self, browser=None):
"""
Launch web browser at project's homepage
@param browser: name of web browser to use
@type browser: string
@returns: 0 if homepage found, 1 if no homepage found
"""
if len(self.all_versions):
metadata = self.pypi.release_data(self.project_name, \
self.all_versions[0])
self.logger.debug("DEBUG: browser: %s" % browser)
if metadata.has_key("home_page"):
self.logger.info("Launching browser: %s" \
% metadata["home_page"])
if browser == 'konqueror':
browser = webbrowser.Konqueror()
else:
browser = webbrowser.get()
browser.open(metadata["home_page"], 2)
return 0
self.logger.error("No homepage URL found.")
return 1
def module_run(self):
sources = self.query('SELECT COUNT(source), source FROM pushpins GROUP BY source')
media_content, map_content = self.build_content(sources)
meta_content = (self.options['latitude'], self.options['longitude'], self.options['radius'])
# create the media report
media_content = meta_content + media_content
media_filename = self.options['media_filename']
self.write_markup(os.path.join(self.data_path, 'template_media.html'), media_filename, media_content)
self.output('Media data written to \'%s\'' % (media_filename))
# order the map_content tuple
map_content = meta_content + map_content
order=[4,0,1,2,3,5]
map_content = tuple([map_content[i] for i in order])
# create the map report
map_filename = self.options['map_filename']
self.write_markup(os.path.join(self.data_path, 'template_map.html'), map_filename, map_content)
self.output('Mapping data written to \'%s\'' % (map_filename))
# open the reports in a browser
w = webbrowser.get()
w.open(media_filename)
time.sleep(2)
w.open(map_filename)
def _solve_google_captcha(self, resp):
# set up the captcha page markup for parsing
tree = fromstring(resp.text)
# extract and request the captcha image
resp = self.request('https://ipv4.google.com' + tree.xpath('//img/@src')[0], redirect=False, cookiejar=self.cookiejar, agent=self.user_agent)
# store the captcha image to the file system
with tempfile.NamedTemporaryFile(suffix='.jpg') as fp:
fp.write(resp.raw)
fp.flush()
# open the captcha image for viewing in gui environments
w = webbrowser.get()
w.open('file://' + fp.name)
self.alert(fp.name)
_payload = {'captcha':raw_input('[CAPTCHA] Answer: ')}
# temporary captcha file removed on close
# extract the form elements for the capctah answer request
form = tree.xpath('//form[@action="index"]')[0]
for x in ['q', 'continue', 'submit']:
_payload[x] = form.xpath('//input[@name="%s"]/@value' % (x))[0]
# send the captcha answer
return self.request('https://ipv4.google.com/sorry/index', payload=_payload, cookiejar=self.cookiejar, agent=self.user_agent)
def open_in_browser(file_location):
"""Attempt to open file located at file_location in the default web
browser."""
# If just the name of the file was given, check if it's in the Current
# Working Directory.
if not os.path.isfile(file_location):
file_location = os.path.join(os.getcwd(), file_location)
if not os.path.isfile(file_location):
raise IOError("\n\nFile not found.")
# For some reason OSX requires this adjustment (tested on 10.10.4)
if sys.platform == "darwin":
file_location = "file:///"+file_location
new = 2 # open in a new tab, if possible
webbrowser.get().open(file_location, new=new)
def open_in_browser(file_location):
"""Attempt to open file located at file_location in the default web
browser."""
# If just the name of the file was given, check if it's in the Current
# Working Directory.
if not os.path.isfile(file_location):
file_location = os.path.join(os.getcwd(), file_location)
if not os.path.isfile(file_location):
raise IOError("\n\nFile not found.")
# For some reason OSX requires this adjustment (tested on 10.10.4)
if sys.platform == "darwin":
file_location = "file:///"+file_location
new = 2 # open in a new tab, if possible
webbrowser.get().open(file_location, new=new)
def create_or_reset_admin(context, settings_path=None):
'''
Creates an admin user or resets the password for an existing one
'''
# Find the path to the settings and setup the django environment
setup_django_environment(settings_path)
# can't be imported in global scope as it already requires
# the settings module during import
from wger.manager.models import User
try:
admin = User.objects.get(username="admin")
print("*** Password for user admin was reset to 'admin'")
except User.DoesNotExist:
print("*** Created default admin user")
# os.chdir(os.path.dirname(inspect.stack()[0][1]))
# current_dir = os.path.join(os.getcwd(), 'wger')
current_dir = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(current_dir, 'wger', 'core', 'fixtures/')
call_command("loaddata", path + "users.json")
def callbackEditUnicodeText(self, sender):
# this is the callback for the unicode textbox.
# if text is edited here, find the glyphs that are used in the text
# and add those to the selection. This way we can quickly add characters
# from cut / paste text to the selection
f = CurrentFont()
text = sender.get()
text = text.replace("\r", " ")
text = text.replace("\n", " ")
self._typing = True
if text:
glyphSelection = findText(self.data, text)
glyphSelection.sort()
items = [g.asDict(self._unicodes, self._names, self.joiningTypes) for g in glyphSelection]
items = sorted(items, key=lambda x: x['uni'], reverse=False)
self.w.selectedNames.set(items)
self.w.selectionUnicodeText.set(text)
self._typing = False
self.checkSampleSize()
def demo(base_url):
"""Login through a third-party OAuth handler and print some stats.
Parameters
----------
base_url : str
Base URL of the CMS server.
"""
session = requests.Session()
adapter = HTTPAdapter(max_retries=Retry(total=3, backoff_factor=0.02))
session.mount('{}://'.format(urlparse(base_url).scheme), adapter)
wb = webbrowser.get()
login_url = os.path.join(base_url, "login?complete=no")
session.get(login_url)
wb.open(login_url)
auth_url = input("Enter the URL returned after authentication:")
response = session.get(auth_url.replace("complete=no", 'complete=yes'))
assert response.status_code == 200
print(session.get(os.path.join(base_url, 'me')).content)
def _github_connect(self, msg_widget, user_checked, window):
link = 'https://api.github.com/repos/giantas/sorter/releases/latest'
try:
with urllib.request.urlopen(link, timeout=5) as response:
html = response.read()
except urllib.request.URLError:
message = 'Update check failed. Could not connect to the Internet.'
msg_widget.config(text=message, relief=SUNKEN)
self.logger.warning(message)
else:
items = json.loads(html.decode('utf-8'))
latest_tag = items.get('tag_name')
if latest_tag.strip('v') > SORTER_VERSION:
items.get('html_url')
body = items.get('body')
features = body.replace('*', '')
message = 'Update available!\n\nSorter {tag}.\n\n{feat} ....\n\nMore information on the'.format(
tag=latest_tag, feat=features[:500])
msg_widget.config(text=message)
self._official_website_label(master=window, window=window)
else:
if user_checked:
message = 'No update found.\n\nYou have the latest version installed. Always stay up-to-date with fixes and new features.\n\nStay tuned for more!'
msg_widget.config(text=message, relief=FLAT)
def get_tokens():
tokens = None
try:
# if we already have tokens, load and use them
tokens = load_data_from_file(DATA_FILE)['tokens']
except:
pass
if not tokens:
# if we need to get tokens, start the Native App authentication process
tokens = do_native_app_authentication(CLIENT_ID, REDIRECT_URI, SCOPES)
try:
save_data_to_file(DATA_FILE, 'tokens', tokens)
except:
pass
return tokens
def get_ip():
import subprocess
return subprocess.check_output('dig +short myip.opendns.com @resolver1.opendns.com'.split()).strip().decode('ascii')
# import socket
# sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# sock.connect(('resolver1.opendns.com', 53))
# sock.send(b'\0\0\1\0\0\1\0\0\0\0\0\0\4myip\7opendns\3com\0\0\1\0\1')
# resp = sock.recv(1000)
# return '.'.join(str(b) for b in resp[-4:])
# import requests, re
# data = requests.get('http://checkip.dyndns.com/').text
# return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
def _solve_google_captcha(self, resp):
# set up the captcha page markup for parsing
tree = fromstring(resp.text)
# extract and request the captcha image
#captchaUrl = 'https://ipv4.google.com' + tree.xpath('//img/@src')[0]
#print(captchaUrl)
resp = self.request('https://ipv4.google.com' + tree.xpath('//img/@src')[0], redirect=False, cookiejar=self.cookiejar, agent=self.user_agent)
# store the captcha image to the file system
with open('/tmp/111.jpg','w') as fp:
fp.write(resp.raw)
fp.flush()
print(fp.name)
# open the captcha image for viewing in gui environments
w = webbrowser.get()
w.open('file://' + fp.name)
self.alert(fp.name)
_payload = {'captcha':raw_input('[CAPTCHA] Answer: ')}
# temporary captcha file removed on close
# extract the form elements for the capctah answer request
form = tree.xpath('//form[@action="index"]')[0]
for x in ['q', 'continue', 'submit']:
_payload[x] = form.xpath('//input[@name="%s"]/@value' % (x))[0]
# send the captcha answer
return self.request('https://ipv4.google.com/sorry/CaptchaRedirect', payload=_payload, cookiejar=self.cookiejar, agent=self.user_agent)