content stringlengths 5 1.05M |
|---|
# Auto generated by 'inv collect-airflow'
from airfly._vendor.airflow.sensors.base import BaseSensorOperator
class CassandraRecordSensor(BaseSensorOperator):
table: "str"
keys: "typing.Dict[str, str]"
cassandra_conn_id: "str"
|
import warnings
import matplotlib
warnings.filterwarnings('ignore', category=matplotlib.MatplotlibDeprecationWarning)
warnings.filterwarnings('ignore', category=UserWarning)
import os
import acopy
import samepy
import tsplib95
import networkx as nx
import matplotlib.pyplot as plt
import copy
from acopy.plugins import StatsRecorder, DrawGraph, Printout, InitialEdgePheromone, MaxMinPheromoneRestrict
from acopy.utils.plot import Plotter
# K = int(input())
K = 4
# -------------------------------------------------
# 初期グラフの作成
print("init-graph")
problem_path = os.path.join('tsp_model', 'bays29.tsp')
problem = tsplib95.load_problem(problem_path)
graph = problem.get_graph()
labels = {i: str(i) for i in graph.nodes()}
colony = acopy.Colony()
solver = acopy.Solver(top=1)
recorder = StatsRecorder('init_data')
printer = Printout()
restricter = MaxMinPheromoneRestrict(save_path='init_data')
solver.add_plugins(recorder, printer, restricter)
limit = 1000
init_ans = solver.solve(graph, colony, limit=limit // 4)
print(init_ans)
print("\n\n\n")
def draw_graph(G, path, title, is_save=False, save_path=""):
plt.figure(dpi=400)
_, ax = plt.subplots()
pos = problem.display_data or problem.node_coords
nx.draw_networkx_nodes(G, pos=pos, ax=ax)
nx.draw_networkx_edges(G, pos=pos, edgelist=path, arrows=False)
nx.draw_networkx_labels(G, pos=pos, labels=labels, font_color='w')
ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)
ax.set_title(title)
if is_save:
plt.savefig(save_path)
plt.show()
# -------------------------------------------------
# make average graph
print("make average graph")
colony = samepy.Colony()
solver = samepy.Solver()
ave_graph = copy.deepcopy(graph)
average_solutions = solver.solve(ave_graph, colony, limit=limit, gen_size=K, problem=problem, pheromone_update=True)
cnt = 0
for sol in average_solutions:
print(sol)
path = sol.path
title = f"average cost {sol.cost}"
print(path)
cnt += 1
print("\n\n\n")
# -------------------------------------------------
# pheromone update fix graph
#
print("test opt2 fix update")
colony = samepy.Colony()
solver = samepy.Solver()
update_graph = copy.deepcopy(graph)
average_solutions = solver.solve(update_graph, colony, limit=limit, gen_size=K, problem=problem, pheromone_update=True, is_opt2=True)
cnt = 0
for sol in average_solutions:
print(sol)
path = sol.path
title = f"average cost {sol.cost}"
print(path)
cnt += 1
print("\n\n\n")
# -------------------------------------------------
# pheromone update fix graph
#
print("only opt2")
colony = samepy.Colony()
solver = samepy.Solver()
update_graph = copy.deepcopy(graph)
average_solutions = solver.solve(update_graph, colony, limit=limit, gen_size=K, problem=problem, is_opt2=True)
cnt = 0
for sol in average_solutions:
print(sol)
path = sol.path
title = f"average cost {sol.cost}"
print(path)
cnt += 1
print("\n\n\n")
# -------------------------------------------------
# Greedy解の構築
print("greedy min k-path")
greedy_graph = copy.deepcopy(graph)
greedy_solutions = []
for k in range(K):
print("k-greedy-path: ", k)
colony = acopy.Colony()
solver = acopy.Solver()
greedy_ans = solver.exploit(greedy_graph, colony, limit=100)
print(greedy_ans, "\n")
for p in greedy_ans:
x, y = p[0], p[1]
greedy_graph.edges[x, y]['pheromone'] = 0
greedy_graph.edges[y, x]['pheromone'] = 0
greedy_graph.edges[x, y]['weight'] = 1e100
greedy_graph.edges[y, x]['weight'] = 1e100
greedy_solutions.append(greedy_ans)
print("\n\n\n")
# -------------------------------------------------
# 異なるパスの計算
print("異なるエッジの計算")
greedy_st = set()
same_st = set()
different_st = set()
for sol in greedy_solutions:
for p in sol:
x, y = min(p[0], p[1]), max(p[0], p[1])
greedy_st.add((x, y))
for sol in average_solutions:
for p in sol:
x, y = min(p[0], p[1]), max(p[0], p[1])
if (x, y) not in greedy_st:
different_st.add((x, y))
else:
same_st.add((x, y))
print("共通エッジ", len(same_st), same_st)
print("異なるエッジ", len(different_st), different_st)
print("\n\n\n")
# -------------------------------------------------
# make average graph
print("make average graph with same or different")
def draw_graph_color_st(G, same_path, diff_path, title, is_save=False, save_path=""):
plt.figure(dpi=400)
_, ax = plt.subplots()
pos = problem.display_data or problem.node_coords
nx.draw_networkx_nodes(G, pos=pos, ax=ax)
nx.draw_networkx_edges(G, pos=pos, edgelist=same_path, arrows=False, edge_color='blue')
nx.draw_networkx_edges(G, pos=pos, edgelist=diff_path, arrows=False, edge_color='red')
ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)
ax.set_title(title)
if is_save:
plt.savefig(save_path)
plt.show()
cnt = 0
for sol in average_solutions:
print(sol)
path = sol.path
same_path = []
diff_path = []
for x, y in path:
x, y = min(x, y), max(x, y)
if (x, y) in greedy_st:
same_path.append((x, y))
else:
diff_path.append((x, y))
title = f"average cost {sol.cost}"
draw_graph_color_st(graph, same_path, diff_path, title, is_save=True, save_path=f"average_sample/color_{cnt}.png")
cnt += 1
|
###
#
# Lenovo Redfish examples - Set BMC vlan id
#
# Copyright Notice:
#
# Copyright 2018 Lenovo Corporation
#
# 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 sys
import redfish
import json
import traceback
import lenovo_utils as utils
def set_bmc_vlanid(ip, login_account, login_password, vlanid, vlanEnable):
"""Set BMC vlan id
:params ip: BMC IP address
:type ip: string
:params login_account: BMC user name
:type login_account: string
:params login_password: BMC user password
:type login_password: string
:params vlanid: vlan id by user specified
:type vlanid: string
:params vlanEnable: vlanenable type by user specified
:type vlanEnable: string
:returns: returns set manager vlanid result when succeeded or error message when failed
"""
result = {}
login_host = "https://"+ip
# Connect using the BMC address, account name, and password
# Create a REDFISH object
REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout,
password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE)
# Login into the server and create a session
try:
REDFISH_OBJ.login(auth=utils.g_AUTH)
except:
traceback.print_exc()
result = {'ret': False, 'msg': "Please check the username, password, IP is correct"}
return result
try:
# GET the managers url
base_url = "/redfish/v1"
response_base_url = REDFISH_OBJ.get(base_url, None)
if response_base_url.status == 200:
managers_url = response_base_url.dict['Managers']['@odata.id']
else:
result = {'ret': False, 'msg': "response base url Error code %s" % response_base_url.status}
REDFISH_OBJ.logout()
return result
response_managers_url = REDFISH_OBJ.get(managers_url, None)
if response_managers_url.status == 200:
count = response_managers_url.dict["Members@odata.count"]
for i in range(count):
manager_url = response_managers_url.dict['Members'][i]['@odata.id']
response_manager_url = REDFISH_OBJ.get(manager_url, None)
# Get the ethernet interface url
if response_manager_url.status == 200:
ethernet_interface = response_manager_url.dict['EthernetInterfaces']['@odata.id']
response_ethernet_interface = REDFISH_OBJ.get(ethernet_interface, None)
if response_ethernet_interface.status == 200:
vlan_found = False
for i in range(response_ethernet_interface.dict['Members@odata.count']):
interface_url = response_ethernet_interface.dict['Members'][i]['@odata.id']
if "NIC" in interface_url or "eth" in interface_url:
# get etag to set If-Match precondition
response_interface_url = REDFISH_OBJ.get(interface_url, None)
if response_interface_url.status != 200:
error_message = utils.get_extended_error(response_interface_url)
result = {'ret': False, 'msg': "Url '%s' get failed. response Error code %s \nerror_message: %s" % (
interface_url, response_interface_url.status, error_message)}
return result
if "VLAN" not in response_interface_url.text:
continue
vlan_found = True
if "@odata.etag" in response_interface_url.dict:
etag = response_interface_url.dict['@odata.etag']
else:
etag = ""
headers = {"If-Match": etag}
ivlanid = int(vlanid)
parameter = {"VLAN":{"VLANId":ivlanid,"VLANEnable": bool(int(vlanEnable))}}
response_interface_url = REDFISH_OBJ.patch(interface_url, body=parameter, headers=headers)
if response_interface_url.status in [200,204]:
result = {'ret': True, 'msg': "set BMC vlanid successfully"}
else:
error_message = utils.get_extended_error(response_interface_url)
result = {'ret': False,
'msg': "Url '%s' response Error code %s \nerror_message: %s" % (
interface_url, response_interface_url.status,
error_message)}
return result
if vlan_found == False:
result = {'ret': False, 'msg': "VLAN does not exist."}
else:
error_message = utils.get_extended_error(response_ethernet_interface)
result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (
ethernet_interface, response_ethernet_interface.status, error_message)}
return result
else:
error_message = utils.get_extended_error(response_manager_url)
result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (
manager_url, response_manager_url.status, error_message)}
return result
else:
error_message = utils.get_extended_error(response_managers_url)
result = {'ret': False, 'msg': "Url '%s' response Error code %s \nerror_message: %s" % (
managers_url, response_managers_url.status, error_message)}
return result
except Exception as e:
traceback.print_exc()
result = {'ret': False, 'msg': "error_message: %s" % (e)}
finally:
# Logout of the current session
try:
REDFISH_OBJ.logout()
except:
pass
return result
import argparse
def add_helpmessage(parser):
parser.add_argument('--vlanid', type=str, required=True, help='Input the vlanid of BMC')
parser.add_argument('--vlanenable', type=str, required=True, help='0:false, 1:true')
def add_parameter():
"""Add manager vlanid parameter"""
argget = utils.create_common_parameter_list()
add_helpmessage(argget)
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
parameter_info['vlanid'] = args.vlanid
parameter_info['vlanEnable'] = args.vlanenable
return parameter_info
if __name__ == '__main__':
# Get parameters from config.ini and/or command line
parameter_info = add_parameter()
# Get connection info from the parameters user specified
ip = parameter_info['ip']
login_account = parameter_info["user"]
login_password = parameter_info["passwd"]
# Get set info from the parameters user specified
try:
vlanid = parameter_info['vlanid']
vlanEnable = parameter_info['vlanEnable']
except:
sys.stderr.write("Please run the command 'python %s -h' to view the help info" % sys.argv[0])
sys.exit(1)
# Set manager vlanid result and check result
result = set_bmc_vlanid(ip, login_account, login_password, vlanid, vlanEnable)
if result['ret'] is True:
del result['ret']
sys.stdout.write(json.dumps(result['msg'], sort_keys=True, indent=2))
else:
sys.stderr.write(result['msg'] + '\n')
sys.exit(1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
requirements = [
'Click>=6.7',
'bioblend',
'wrapt',
'pyyaml',
'justbackoff',
'xunit-wrapper',
'future',
]
test_requirements = [
# TODO: put package test requirements here
]
version = '1.0.3-rc1'
subpackages = [x.replace('/', '.') for x in glob.glob('parsec/commands/*') if not x.endswith('.py')]
setup(
name='galaxy-parsec',
version=version,
description='Command-line utilities to assist in interacting with Galaxy servers (http://galaxyproject.org/).',
long_description=readme,
author='Galaxy Project and Community',
author_email='rasche.eric@gmail.com',
url='https://github.com/galaxy-iuc/parsec',
packages=[
'parsec',
'parsec.commands',
] + subpackages,
entry_points='''
[console_scripts]
parsec=parsec.cli:parsec
''',
package_dir={'parsec': 'parsec'},
install_requires=requirements,
license="AFL",
keywords='parsec',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements
)
|
## Remove duplicate words
## 7 kyu
## https://www.codewars.com//kata/5b39e3772ae7545f650000fc
def remove_duplicate_words(s):
s = s.split()
unique_words = []
for word in s:
if word not in unique_words:
unique_words.append(word)
return ' '.join(unique_words) |
import pytest
from feeds.util import epoch_ms
def test_epoch_ms():
'''
Just make sure it's an int with 13 digits. Be more rigorous later. At least, before year 2287.
'''
t = epoch_ms()
assert len(str(t)) == 13 |
from django.db import models
# Create your models here.
class materias(models.Model):
id = models.AutoField(primary_key=True)
esporte = models.CharField(
max_length=255,
null=False,
blank=False
)
class Meta:
db_table = "materias" |
from onegov.fsi.collections.course_event import CourseEventCollection
from onegov.fsi.models import CourseSubscription, CourseAttendee, CourseEvent, \
Course
from onegov.user import User
def test_locked_course_event_reservations(client_with_db):
client = client_with_db
client.login_admin()
session = client.app.session()
course = session.query(Course).first()
# Add a new course event
page = client.get(f'/fsi/events/add?course_id={course.id}')
page.form['presenter_name'] = 'Presenter'
page.form['presenter_company'] = 'Presenter'
page.form['presenter_email'] = 'presenter@example.org'
page.form['locked_for_subscriptions'] = True
page.form['start'] = '2050-10-04 10:00'
page.form['end'] = '2050-10-04 12:00'
page.form['location'] = 'location'
page.form['max_attendees'] = 20
# goes to the event created
new = page.form.submit().follow()
assert 'Eine neue Durchführung wurde hinzugefügt' in new
client.login_editor()
# Hinzufügen - Teilnehmer als editor
add_subscription = new.click('Teilnehmer', href='reservations', index=0)
page = add_subscription.form.submit()
assert 'Diese Durchführung kann (nicht) mehr gebucht werden.' in page
client.login_admin()
add_subscription = new.click('Teilnehmer', href='reservations', index=0)
page = add_subscription.form.submit().follow()
assert 'Neue Anmeldung wurde hinzugefügt' in page
assert 'Diese Durchführung kann (nicht) mehr gebucht werden.' not in page
def test_reservation_collection_view(client_with_db):
view = '/fsi/reservations'
client = client_with_db
client.get(view, status=403)
client.login_member(to=view)
# is the current attendee registered for two courses
page = client.get(view)
assert 'Meine Kursanmeldungen' in page
assert 'Course' in page
assert '01.01.2050' in page
assert '01.01.1950' in page
def test_reservation_details(client_with_db):
client = client_with_db
session = client.app.session()
attendee = session.query(CourseAttendee).first()
subscription = attendee.subscriptions.first()
view = f'/fsi/reservation/{subscription.id}'
# This view has just the delete method
client.get(view, status=405)
def test_edit_reservation(client_with_db):
client = client_with_db
session = client.app.session()
subscription = session.query(CourseSubscription).filter(
CourseSubscription.attendee_id != None).first()
placeholder = session.query(CourseSubscription).filter(
CourseSubscription.attendee_id == None).first()
events = session.query(CourseEvent).all()
assert events[1].id != subscription.course_event_id
# --- Test edit a placeholder --
client.login_admin()
view = f'/fsi/reservation/{placeholder.id}/edit-placeholder'
page = client.get(view)
assert page.form['course_event_id'].value == str(
placeholder.course_event_id)
# The default dummy desc will be set in the view
assert page.form['dummy_desc'].value == 'Placeholder'
page.form['dummy_desc'] = ''
page = page.form.submit().maybe_follow()
assert 'Platzhalter aktualisiert' in page
page = client.get(view)
# check if empty placeholder is replaced by default
assert page.form['dummy_desc'].value == 'Platzhalter-Reservation'
# --- Test a normal subscription ---
view = f'/fsi/reservation/{subscription.id}/edit'
client.login_editor()
client.get(view, status=403)
client.login_admin()
edit = client.get(view)
assert 'Anmeldung bearbeiten' in edit
assert edit.form['course_event_id'].value == str(
subscription.course_event_id)
assert edit.form['attendee_id'].value == str(subscription.attendee_id)
options = [opt[2] for opt in edit.form['attendee_id'].options]
# Returns event.possible_subscribers, tested elsewhere
# Planner (admin) and attendee have subscription, not editor_attendee (PE)
# L, F is the normal attendee
assert options == ['L, F', 'PE, PE']
# course must be fixed
options = [opt[2] for opt in edit.form['course_event_id'].options]
assert options == ['Course - 01.01.1950 01:00']
new_id = edit.form['attendee_id'].options[1][0]
edit.form['attendee_id'] = new_id
page = edit.form.submit().maybe_follow()
assert 'Anmeldung wurde aktualisert' in page
page = client.get(view)
assert page.form['attendee_id'].value == new_id
def test_own_reservations(client_with_db):
client = client_with_db
client.login_editor()
page = client.get('/topics/informationen')
# check if the management bar shows the correct number of subscriptions
res_count = page.pyquery('a.open-tickets').attr('data-count')
assert res_count == '1'
page = page.click('Kursanmeldung', href='attendee_id')
assert 'Keine Einträge gefunden' not in page
def test_create_delete_reservation(client_with_db):
client = client_with_db
session = client.app.session()
attendee = session.query(CourseAttendee).first()
att_res = attendee.subscriptions.all()
assert len(att_res) == 2
# Lazy loading not possible
member = session.query(User).filter_by(role='member').first()
coll = CourseEventCollection(session, upcoming_only=True)
events = coll.query().all()
# one of the three is past
assert len(events) == 2
assert events[0].start.year == 2050 # ascending order, other is 2060
assert events[1].id not in [e.course_event_id for e in att_res]
assert attendee.user_id == member.id
assert attendee.organisation == 'ORG'
view = f'/fsi/reservations/add'
client.login_editor()
# Check filtering down the courses when the attendee is given
page = client.get(f'/fsi/reservations/add?attendee_id={attendee.id}')
options = [opt[2] for opt in page.form['course_event_id'].options]
assert options == [
'Course - 01.01.2060 01:00'
]
client.get(view)
# Add - Subscription as editor having the permissions to see one attendee
new = client.get(view).click('Anmeldung')
assert new.form['attendee_id'].options[0] == (
str(attendee.id), False, str(attendee))
# the fixture also provides a past event which should not be an option
options = [opt[2] for opt in new.form['course_event_id'].options]
print(options)
assert options == [
'Course - 01.01.2050 01:00',
'Course - 01.01.2060 01:00'
]
# select course_id where there is no registration done (2060)
new.form['course_event_id'] = str(events[1].id)
page = new.form.submit().maybe_follow()
assert 'Alle Kursanmeldungen' in page
assert 'Course' in page
assert '01.01.2060' in page
page = client.get(view).form.submit()
msg = 'Für dieses Jahr gibt es bereits andere Anmeldungen für diesen Kurs'
assert msg in page
# Settings the attendee id should filter down to events the attendee
# hasn't any subscription
page = client.get(f'/fsi/reservations/add?attendee_id={attendee.id}')
options = [opt[2] for opt in page.form['course_event_id'].options]
assert options == [
'Keine'
]
# Test adding placeholder with editor not allowed
view = '/fsi/reservations/add-placeholder'
client.get(view, status=403)
client.login_admin()
#
new = client.get(view)
options = [opt[2] for opt in new.form['course_event_id'].options]
# must asscending order from newest to oldest, past events excluded
assert options == ['Course - 01.01.2050 01:00', 'Course - 01.01.2060 01:00']
new.form['dummy_desc'] = 'Safe!'
page = new.form.submit().follow()
assert 'Safe!' in page
page.click('Safe!').click('Löschen')
page = client.get('/fsi/reservations')
assert 'Safe!' not in page
|
#!/usr/bin/env python3
"""
This receives text from stdin and does a sentiment analysis on each line
"""
import sys
import nltk
from nltk.corpus import stopwords
def read_lines_stdin():
lines = []
for line in sys.stdin:
lines.append(line)
[line.replace('\n', '') for line in lines]
return lines
if __name__ == '__main__':
tweets = read_lines_stdin()
default_stopwords = set(nltk.corpus.stopwords.words('english'))
words = nltk.word_tokenize(" ".join(tweets))
# Cleanup
words = [word for word in words if len(word) > 1]
words = [word for word in words if not word.isnumeric()]
words = [word.lower() for word in words]
words = [word for word in words if word not in default_stopwords]
# Calculate frequency distribution
fdist = nltk.FreqDist(words)
# print(words)
for word, frequency in fdist.most_common(50):
print(u'{};{}'.format(word, frequency)) |
import json
import pytest
from django.http import HttpResponse
from jcasts.shared.htmx import with_hx_trigger
class TestWithHxTrigger:
@pytest.fixture
def response(self):
return HttpResponse()
def test_no_data(self, response):
response = with_hx_trigger(response, "")
assert "HX-Trigger" not in response
def test_string(self, response):
response = with_hx_trigger(response, "reload-queue")
assert json.loads(response["HX-Trigger"]) == {"reload-queue": ""}
def test_dict(self, response):
response = with_hx_trigger(response, {"remove-queue-item": 1})
assert json.loads(response["HX-Trigger"]) == {"remove-queue-item": 1}
def test_append_to_string(self, response):
response["HX-Trigger"] = "testme"
response = with_hx_trigger(response, {"remove-queue-item": 1})
assert json.loads(response["HX-Trigger"]) == {
"remove-queue-item": 1,
"testme": "",
}
def test_append_to_dict(self, response):
response["HX-Trigger"] = json.dumps({"testme": "test"})
response = with_hx_trigger(response, {"remove-queue-item": 1})
assert json.loads(response["HX-Trigger"]) == {
"remove-queue-item": 1,
"testme": "test",
}
|
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Sensor
from sites.serializers import SensorSerializer
SENSOR_URL = reverse('sites:sensor-list')
class PublicSensorsApiTests(TestCase):
"""Test the publicly available sensors API"""
def setUp(self):
self.client = APIClient()
def test_login_required(self):
"""Test that login is required for retrieving sensors"""
res = self.client.get(SENSOR_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateSensorsApiTests(TestCase):
"""Test the authorized user sensors API"""
def setUp(self):
self.user = get_user_model().objects.create_user(
'shahab@yahoo.com',
'password123'
)
self.client = APIClient()
self.client.force_authenticate(self.user)
def test_retrieve_sensors(self):
"""Test retrieving sensors"""
Sensor.objects.create(user=self.user, name='Space')
Sensor.objects.create(user=self.user, name='Temperature')
res = self.client.get(SENSOR_URL)
sensors = Sensor.objects.all().order_by('-name')
serializer = SensorSerializer(sensors, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
def test_sensor_limited_to_user(self):
"""Test that sensors are for authenticated user"""
user2 = get_user_model().objects.create_user(
'other@yahoo.com',
'testpass'
)
Sensor.objects.create(user=user2, name='Space')
sensor = Sensor.objects.create(user=self.user, name='Temperature')
res = self.client.get(SENSOR_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data[0]['name'], sensor.name)
def test_create_sensor_successful(self):
"""Test Creating a new sensor"""
payload = {'name': 'Temperature'}
self.client.post(SENSOR_URL, payload)
exists = Sensor.objects.filter(
user=self.user,
name=payload['name']
).exists()
self.assertTrue(exists)
def test_create_sensor_invalid(self):
"""Test creating a new sensor with invalid payload"""
payload = {'name': ''}
res = self.client.post(SENSOR_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
# def test_retrieve_sensors_assigned_to_recipes(self):
# """Test filtering sensors by those assigned to recipes"""
# sensor1 = Sensor.objects.create(user=self.user, name='Egg')
# sensor2 = Sensor.objects.create(user=self.user, name='Cheese')
# recipe = Recipe.objects.create(
# title='Coriander eggs on toast',
# time_minutes=10,
# price=5.00,
# user=self.user
# )
# recipe.sensors.add(sensor1)
#
# res = self.client.get(SENSOR_URL, {'assigned_only': 1})
#
# serializer1 = SensorSerializer(sensor1)
# serializer2 = SensorSerializer(sensor2)
# self.assertIn(serializer1.data, res.data)
# self.assertNotIn(serializer2.data, res.data)
#
# def test_retrieve_sensors_assigned_unique(self):
# """Test filtering sensors by assiging returns unique items"""
# sensor = Sensor.objects.create(user=self.user, name='Egg')
# Sensor.objects.create(user=self.user, name='Cheese')
# recipe1 = Recipe.objects.create(
# title='Coriander eggs on toast',
# time_minutes=10,
# price=5.00,
# user=self.user
# )
# recipe1.sensors.add(sensor)
# recipe2 = Recipe.objects.create(
# title='Steak',
# time_minutes=10,
# price=5.00,
# user=self.user
# )
# recipe2.sensors.add(sensor)
#
# res = self.client.get(SENSOR_URL, {'assigned_only': 1})
#
# self.assertEqual(len(res.data), 1)
|
import os
import sys
from setuptools import setup, find_packages
if os.getuid() != 0:
print('ERROR: Need to run as root')
sys.exit(1)
print('INFO: Checking and installing requirements')
os.system('! dpkg -S python-imagingtk && apt-get -y install python-imaging-tk')
print('INFO: Generating the requirements form requirements.txt')
package = []
for line in open('requirements.txt').read():
if not line.startswith('#'):
package.append(line.strip())
setup(
name='SmartMirror',
version='1.0.0',
install_requires=package,
packages=find_packages(),
url='https://github.com/PWRxPSYCHO/SmartMirror',
license='MIT License',
author='PWRxPSYCHO',
author_email='',
description=''
)
|
import machine
import pyb
import lvgl as lv
import os
pyb.country('US') # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU
pyb.main('main.py') # main script to run after this one
pyb.usb_mode('VCP+MSC') # act as a serial and a storage device
lv.init() # LVGL needs to be initialized before it's used |
import getpass
import os
import sys
import consulate
from fabric.api import run, local, cd, env, roles, execute
import requests
CODE_DIR = '/home/deploy/www/iodocs'
env.forward_agent = True
consul = consulate.Session()
def group_map():
ansible_group_list = consul.kv.find('ansible/groups')
ansible_group_map = {}
for path, groups in ansible_group_list.iteritems():
host = os.path.basename(path)
for group in groups.split(','):
if group in ansible_group_map:
ansible_group_map[group].append(host)
else:
ansible_group_map[group] = [host]
return ansible_group_map
env.roledefs = group_map()
def deploy():
# pre-roll checks
check_user()
# do a local git pull, so the revision # when we record the deploy is correct
local("git pull")
# do the roll.
# execute() will call the passed-in function, honoring host/role decorators.
execute(update_and_restart)
@roles('apps-web')
def update_and_restart():
with cd(CODE_DIR):
run("git pull")
run("npm install")
run("supervisorctl restart iodocs")
def check_user():
if getpass.getuser() != 'deploy':
print "This command should be run as deploy. Run like: sudo -u deploy fab deploy"
sys.exit(1)
|
#!/usr/bin/env python3
# Enumerate a certificate and trust chain
import contextlib
import datetime
import socket
import sys
import json
from OpenSSL import SSL
@contextlib.contextmanager
def open_tls_socket(hostname):
port = 443
if ":" in hostname:
(hostname, port) = hostname.split(":")
port = int(port)
context = SSL.Context(method=SSL.TLSv1_2_METHOD)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = SSL.Connection(context=context, socket=sock)
sock.settimeout(5)
sock.set_tlsext_host_name(hostname.encode())
try:
sock.connect((hostname, port))
sock.setblocking(1)
sock.do_handshake()
yield sock
except SSL.Error as exc:
sys.stderr.write(f"ERROR: Failed to negotiate TLS with {hostname}:{port}\n")
raise exc
except OSError as exc:
sys.stderr.write(
f"ERROR: Failed to resolve or connect with {hostname}:{port}\n"
)
raise exc
finally:
sock.shutdown()
sock.close()
def fetch_cert_expiration_time(sock):
notafter = sock.get_peer_certificate().get_notAfter().decode("ascii")
return datetime.datetime.strptime(notafter, "%Y%m%d%H%M%SZ").isoformat()
def nice_subject(cert_subject):
# Remove surrounding noise - Just return a subject path
# In: "<X509Name object '/C=US/O=Let's Encrypt/CN=R3'>""
# Out: "/C=US/O=Let's Encrypt/CN=R3"
return "'".join(cert_subject.__str__().split("'")[1:-1])
def enumerate_cert_chain(sock):
chain = {}
for cert in sock.get_peer_cert_chain():
subject = nice_subject(cert.get_subject())
chain[subject] = {
"serial": cert.get_serial_number(),
"issuer": nice_subject(cert.get_issuer()),
}
return chain
def main():
if len(sys.argv) < 2:
sys.stderr.write(
"Please specify at least one FQDN (with option port) to connect to\n"
)
sys.exit(1)
out = {}
for hostname in sorted(sys.argv[1:]):
with open_tls_socket(hostname) as sock:
out[hostname] = {
"expiration": fetch_cert_expiration_time(sock),
"chain": enumerate_cert_chain(sock),
}
# All that to get a fully sorted record dump. :sigh:
print(json.dumps(out, indent=4))
sys.exit(0)
if __name__ == "__main__":
main()
|
# Generated by Django 3.0 on 2019-12-18 11:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hatvp', '0009_auto_20191217_2147'),
]
operations = [
migrations.RemoveField(
model_name='exercices',
name='date_fin',
),
migrations.RemoveField(
model_name='exercices',
name='exercice_sans_activite',
),
migrations.RemoveField(
model_name='exercices',
name='nombre_activites',
),
migrations.AlterField(
model_name='exercices',
name='date_debut',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterField(
model_name='exercices',
name='date_publication',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterField(
model_name='informations_generales',
name='date_premiere_publication',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterField(
model_name='informations_generales',
name='derniere_publication_activite',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterField(
model_name='objets_activites',
name='date_publication_activite',
field=models.DateTimeField(blank=True, null=True),
),
]
|
# encoding:utf-8
import requests
import time
from lxml import etree
import json
class TemporaryEmail:
"""临时邮箱
使用http://24mail.chacuo.net/10分钟邮箱,
监听并返回收到的邮件内容,用以接受验证码
"""
def __init__(self):
self.headers = {
'Pragma': 'no-cache',
'Origin': 'http://24mail.chacuo.net',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': '*/*',
'Cache-Control': 'no-cache',
'X-Requested-With': 'XMLHttpRequest',
'Connection': 'keep-alive',
'Referer': 'http://24mail.chacuo.net/',
}
# 使用会话先获取邮箱id
self.session = requests.Session()
r = self.session.get('http://24mail.chacuo.net/', headers=self.headers)
selector = etree.HTML(r.text)
self.email_id = selector.xpath('//*[@id="converts"]/@value')
self.mid = ''
def get_email_address(self):
return self.email_id[0]+'@chacuo.net'
def check_received_email(self):
# 发送刷新检查是否有邮件并得到邮件id
data = {
'data': self.email_id,
'type': 'refresh',
'arg': ''
}
time.sleep(3)
r = self.session.post('http://24mail.chacuo.net/', data=data)
r_json = json.loads(r.text)
try:
mid = r_json['data'][0]['list'][0]['MID']
self.mid = mid
return True
except IndexError:
return False
def get_email_content(self):
# 获取邮件内容
data2 = {
'data': self.email_id,
'type': 'mailinfo',
'arg': 'f=' + str(self.mid)
}
r2 = self.session.post('http://24mail.chacuo.net/', data=data2)
r2_json = json.loads(r2.text)
return r2_json['data'][0][1][0]['DATA']
if __name__ == '__main__':
t_email = TemporaryEmail()
print(t_email.get_email_address())
while True:
if t_email.check_received_email():
content = t_email.get_email_content()
print(content)
break
|
from sympy import symbols, sin, cos
from ga import Ga
from printer import Format, xpdf
Format()
(u, v) = uv = symbols('u,v',real=True)
(g2d, eu, ev) = Ga.build('e_u e_v', coords=uv)
print '#$A$ is a general 2D linear transformation'
A2d = g2d.lt('A')
print 'A =', A2d
print '\\f{\\det}{A} =', A2d.det()
print '\\f{\\Tr}{A} =', A2d.tr()
B2d = g2d.lt('B')
print 'B =', B2d
print 'A + B =', A2d + B2d
print 'AB =', A2d * B2d
print 'A - B =', A2d - B2d
a = g2d.mv('a','vector')
b = g2d.mv('b','vector')
print r'a|\f{\overline{A}}{b}-b|\f{\underline{A}}{a} =',((a|A2d.adj()(b))-(b|A2d(a))).simplify()
m4d = Ga('e_t e_x e_y e_z', g=[1, -1, -1, -1],coords=symbols('t,x,y,z',real=True))
T = m4d.lt('T')
print '#$T$ is a linear transformation in Minkowski space'
print r'\underline{T} =',T
print r'\overline{T} =',T.adj()
print r'\f{\mbox{tr}}{\underline{T}} =',T.tr()
a = m4d.mv('a','vector')
b = m4d.mv('b','vector')
print r'a|\f{\overline{T}}{b}-b|\f{\underline{T}}{a} =',((a|T.adj()(b))-(b|T(a))).simplify()
xpdf(paper='landscape',crop=True)
|
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.append(os.path.join(os.path.abspath(os.pardir), 'sample'))
import sample
|
"""Divide a raster by the m^2 area of the wgs84 pixel."""
import logging
import math
import sys
from osgeo import gdal
import numpy
import pygeoprocessing
pixel_size = 0.083
lat = 0
logging.basicConfig(
stream=sys.stdout,
level=logging.DEBUG,
format=(
'%(asctime)s (%(relativeCreated)d) %(processName)s %(levelname)s '
'%(name)s [%(funcName)s:%(lineno)d] %(message)s'))
LOGGER = logging.getLogger(__name__)
def area_of_pixel_km2(pixel_size, center_lat):
"""Calculate km^2 area of a wgs84 square pixel.
Adapted from: https://gis.stackexchange.com/a/127327/2397
Parameters:
pixel_size (float): length of side of pixel in degrees.
center_lat (float): latitude of the center of the pixel. Note this
value +/- half the `pixel-size` must not exceed 90/-90 degrees
latitude or an invalid area will be calculated.
Returns:
Area of square pixel of side length `pixel_size` centered at
`center_lat` in km^2.
"""
a = 6378137 # meters
b = 6356752.3142 # meters
e = math.sqrt(1 - (b/a)**2)
area_list = []
for f in [center_lat+pixel_size/2, center_lat-pixel_size/2]:
zm = 1 - e*math.sin(math.radians(f))
zp = 1 + e*math.sin(math.radians(f))
area_list.append(
math.pi * b**2 * (
math.log(zp/zm) / (2*e) +
math.sin(math.radians(f)) / (zp*zm)))
# mult by 1e-6 to convert m^2 to km^2
return pixel_size / 360. * (area_list[0] - area_list[1]) * 1e-6
def divide_op(num_array, denom_array, nodata):
result = numpy.empty(shape=num_array.shape)
result[:] = nodata
valid_mask = ~numpy.isclose(num_array, nodata)
result[valid_mask] = num_array[valid_mask] / denom_array[valid_mask]
return result
if __name__ == '__main__':
raster_path = (
'realized_fwfish_distrib_catch_md5_995d3d330ed5fc4462a47f7db44225e9.tif')
target_raster = 'per_km_2_%s' % raster_path
raster_info = pygeoprocessing.get_raster_info(raster_path)
n_cols, n_rows = raster_info['raster_size']
gt = raster_info['geotransform']
lat_area_km2 = numpy.empty(shape=(n_rows, 1))
for row_index in range(n_rows):
_, lat_a = gdal.ApplyGeoTransform(gt, 0, row_index)
_, lat_b = gdal.ApplyGeoTransform(gt, 0, row_index+1)
lat_center = (lat_a+lat_b)/2.0
lat_area_km2[row_index][0] = area_of_pixel_km2(
raster_info['pixel_size'][0], lat_center)
pygeoprocessing.raster_calculator(
[(raster_path, 1), lat_area_km2, (raster_info['nodata'][0], 'raw')],
divide_op, target_raster, raster_info['datatype'],
raster_info['nodata'][0])
|
from setuptools import setup, find_packages
import os,sys
def readme():
with open('README.md') as f:
return f.read()
# Hackishly inject a constant into builtins to enable importing of the
# package before the library is built.
import sys
if sys.version_info[0] < 3:
import __builtin__ as builtins
else:
import builtins
builtins.__THISTOTHAT_SETUP__ = True
import thistothat
version = thistothat.__version__
setup(name = "thistothat",
version = version,
description = "Tools for interpolating various astrophysical relations, many related to M dwarf physical properties.",
long_description = readme(),
author = "Zachory K. Berta-Thompson",
author_email = "zach.bertathompson@colorado.edu",
url = "https://github.com/zkbt/thistothat",
packages = find_packages(),
package_data = {'thistothat':['data/*.txt', 'data/baraffe/*.txt']},
include_package_data=True,
scripts = [],
classifiers=[
'Intended Audience :: Science/Research',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Astronomy'
],
install_requires=['numpy', 'astropy', 'scipy', 'matplotlib' ],
zip_safe=False,
license='MIT',
)
|
import tensorflow as tf
import numpy as np
class BaseLogger:
"""
Creates a summary writer for tensorboard logging.
Args:
name (string): Name of the model.
log_dir (string): Path that indicates which dataset is used.
"""
def __init__(self, name, log_dir):
self.name = name
#logdir = "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S")
self.file_writer = tf.summary.create_file_writer(log_dir+"/"+name)
self.file_writer.set_as_default()
def log_scalar(self, tag, value, step):
"""Log a scalar variable.
Args:
tag (string): Name of the scalar
value (float): Value of the scalar
step (int): Training iteration
"""
tf.summary.scalar(tag, value, step=step)
self.file_writer.flush()
class TrainingLogger(BaseLogger):
def __init__(self, name, log_dir):
super().__init__(name, log_dir)
self.mean_per_episode_dict = {}
def log_mean(self, tag, value):
if tag in set(self.mean_per_episode_dict.keys()):
self.mean_per_episode_dict[tag].append(value)
else:
self.mean_per_episode_dict[tag] = [value]
def print_status(self, episode):
print('\nname:', self.name)
print('Episode:', str(episode))
for key in self.mean_per_episode_dict.keys():
if len(self.mean_per_episode_dict[key]) > 1:
self.mean_per_episode_dict[key] = np.mean(self.mean_per_episode_dict[key])
else:
self.mean_per_episode_dict[key] = float(np.squeeze(self.mean_per_episode_dict[key]))
print('{}: {}'.format(key, self.mean_per_episode_dict[key]))
self.log_scalar(key, self.mean_per_episode_dict[key], episode)
self.mean_per_episode_dict.clear()
class StatusPrinter:
def __init__(self, name):
self.name = name
self.mean_per_episode_dict = {}
def log_mean(self, tag, value):
if tag in set(self.mean_per_episode_dict.keys()):
self.mean_per_episode_dict[tag].append(value)
else:
self.mean_per_episode_dict[tag] = [value]
def print_status(self, steps=None, episode=None):
print('\nname:', self.name)
if not episode is None:
print('episode:', str(episode))
if not steps is None:
print('steps:', str(steps))
for key in self.mean_per_episode_dict.keys():
if len(self.mean_per_episode_dict[key]) > 1:
self.mean_per_episode_dict[key] = np.mean(self.mean_per_episode_dict[key])
else:
self.mean_per_episode_dict[key] = float(np.squeeze(self.mean_per_episode_dict[key]))
print('{}: {}'.format(key, self.mean_per_episode_dict[key]))
self.mean_per_episode_dict.clear()
class TestingLogger(BaseLogger):
def __init__(self, name, log_dir):
super().__init__(name, log_dir)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
sys.path.append('/home/osboxes/github/mininet-wifi')
from math import sqrt
from time import sleep, time
from future.utils import iteritems
from mininet import log
from mininet.node import Controller, Node, Docker
from mininet_wifi.wifi.node import OVSKernelAP, Station, DockerStation
from mininet_wifi.wifi.cli import CLI_wifi
from mininet_wifi.wifi.net import Mininet_wifi
log.setLogLevel('debug')
class Topo(object):
def __init__(self):
self.ap_dict = {}
self.sw_dict = {}
self.host_dict = {}
self.sta_dict = {}
self.net = Mininet_wifi(accessPoint=OVSKernelAP)
self.net.propagationModel(model="logDistance", exp=3)
self.c1 = Controller('c1')
self.add_nodes()
def start(self):
log.info("*** Starting network\n")
# self.net.plotGraph(max_x=200, max_y=200)
self.ts_netstart = time()
# trigger attachment
self.net.startMobility(time=0, repetitions=1)
for sta_name, sta_obj in iteritems(self.sta_dict):
self.net.mobility(sta_obj, 'start', time=1, position='0,0,0')
self.net.mobility(sta_obj, 'stop', time=2, position='0,0,0')
self.net.stopMobility(time=3)
self.net.build()
self.c1.start()
for ap_name, ap_obj in iteritems(self.ap_dict):
ap_obj.start([self.c1])
sleep(5) # wait for setup
CLI_wifi(self.net)
# TODO: clean this shit
result = self.exec_cmd(
'h1',
'ping 10.0.0.13 -c 1')
log.info(result)
result = self.exec_cmd(
'sta1',
'ping 10.0.0.11 -c 1')
log.info(result)
result = self.exec_cmd(
'sta2',
'ping 10.0.0.12 -c 1')
log.info(result)
result = self.exec_cmd(
'h1',
'python main.py color_finder 10.0.0.11:18800 10.0.0.13:18800 &')
log.info(result)
result = self.exec_cmd(
'sta1',
'python main.py data_forwarder 172.17.0.2:18800 10.0.0.11:18800 True &')
log.info(result)
result = self.exec_cmd(
'sta2',
'python main.py data_forwarder 10.0.0.13:18800 192.168.56.102:18900 False &')
log.info(result)
def run_cli(self):
log.info("*** Running CLI\n")
CLI_wifi(self.net)
def stop(self):
log.info("*** Stopping network\n")
self.net.stop()
def exec_cmd(self, node_name, cmd):
if node_name in self.sta_dict:
node = self.sta_dict[node_name]
elif node_name in self.host_dict:
node = self.host_dict[node_name]
else:
assert False, 'no such node {}'.format(node_name)
return node.cmd(cmd)
def move_station(self, sta_name, next_pos=None, speed=None):
assert sta_name in self.sta_dict
sta = self.sta_dict[sta_name]
if 'position' in sta.params:
cur_x, cur_y, cur_z = sta.params['position']
cur_x, cur_y, cur_z = float(cur_x), float(cur_y), float(cur_z)
else:
cur_x, cur_y, cur_z = 0.0, 0.0, 0.0
if not next_pos:
next_x, next_y, next_z = cur_x, cur_y, cur_z
else:
next_x, next_y, next_z = next_pos
if not speed:
duration = 1
else:
duration = int(sqrt(
(next_x - cur_x)**2 + (next_y - cur_y)**2
+ (next_z - cur_z)**2) / speed)
log.info(
'[I] move {} from ({} {} {}) to ({} {} {}), dur={}\n'.format(
sta_name,
cur_x, cur_y, cur_z,
next_x, next_y, next_z,
duration))
sta.setPosition('{}, {}, {}'.format(next_x, next_y, next_z))
if duration > 0:
sleep(duration)
log.info('{} rssi: {}'.format(sta_name, sta.params['rssi']))
def add_nodes(self, mode='containernet'):
"""
add nodes to net.
Args:
mode (str): miminet or containernet
Returns:
ap_dict, sw_dict, host_dict, sta_dict
"""
log.info("*** Creating nodes\n")
if mode == 'mininet':
h1 = self.net.addHost(
'h1', cls=Node, mac='00:00:00:00:00:01', ip='10.0.0.11/8')
sta1 = self.net.addStation(
'sta1', cls=Station, mac='00:00:00:00:00:02', ip='10.0.0.12/8')
sta2 = self.net.addStation(
'sta2', cls=Station, mac='00:00:00:00:00:03', ip='10.0.0.13/8')
else:
dimage_name = 'kumokay/ubuntu_wifi:v4'
h1 = self.net.addHost(
'h1', cls=Docker, dimage=dimage_name,
mac='00:00:00:00:00:01', ip='10.0.0.11/8')
sta1 = self.net.addStation(
'sta1', cls=DockerStation, dimage=dimage_name,
mac='00:00:00:00:00:02', ip='10.0.0.12/8')
sta2 = self.net.addStation(
'sta2', cls=DockerStation, dimage=dimage_name,
mac='00:00:00:00:00:03', ip='10.0.0.13/8')
ap1 = self.net.addAccessPoint(
'ap1', ssid='new-ssid', mode='g', channel='1',
position='0,0,0', range=100)
ap2 = self.net.addAccessPoint(
'ap2', ssid='new-ssid', mode='g', channel='1',
position='-100,0,0', range=60)
ap3 = self.net.addAccessPoint(
'ap3', ssid='new-ssid', mode='g', channel='1',
position='-150,0,0', range=100)
self.net.addController(self.c1)
# add all nodes to dict
self.ap_dict['ap1'] = ap1
self.ap_dict['ap2'] = ap2
self.ap_dict['ap3'] = ap3
self.host_dict['h1'] = h1
self.sta_dict['sta1'] = sta1
self.sta_dict['sta2'] = sta2
log.info("*** Configuring wifi nodes\n")
self.net.configureWifiNodes()
log.info("*** Associating and Creating links\n")
self.net.addLink(ap1, h1, delay='5ms')
self.net.addLink(ap1, ap2, delay='10ms')
self.net.addLink(ap2, ap3, delay='10ms')
def test():
topo = Topo()
topo.start()
# topo.move_station('sta1', next_pos=(20.0, 40.0, 0.0), speed=1)
topo.move_station('sta2', next_pos=(30.0, 20.0, 0.0), speed=10)
topo.run_cli()
topo.stop()
|
def logged(function):
def wrapper(*args):
retval = f'you called {function.__name__}{args}\n'
retval += f'it returned {function(*args)}'
return retval
return wrapper
@logged
def func(*args):
return 3 + len(args)
@logged
def sum_func(a, b):
return a + b
print(func(4, 4, 4))
print(sum_func(1, 4))
|
from __future__ import absolute_import
from page_object.page_object import PageObject
from page_object.page_factory import on, visit
from page_object.browser import Browser
|
from src import __version__, __version_info__
def test_version():
assert len(__version__) == 6
def test_version_info():
assert len(__version_info__) == 3
|
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog, QLabel, QTextEdit, QComboBox, QMainWindow
from PyQt5.QtGui import QPixmap
import cv2 as cv
import os
import tempfile
from pupil import Pupil
class Window(QWidget):
def __init__(self):
super().__init__()
self.__title = "Pupil Center Detection"
self.__right = 200
self.__down = 100
self.__width = 800
self.__height = 300
self.dir = tempfile.TemporaryDirectory()
self.img_path = ""
self.temp_dir = os.path.join(self.dir.name, 'browsed.png')
self.method = "parallelogram"
print(self.temp_dir)
self.Init()
def Init(self):
self.setWindowTitle(self.__title)
self.setGeometry(self.__right, self.__down, self.__width, self.__height)
btn_browse = QPushButton("Browse Image", self)
btn_browse.setGeometry(100, 10, 100, 22)
btn_browse.clicked.connect(self.getImage)
btn_process = QPushButton("Find center", self)
btn_process.setGeometry(600, 10, 100, 22)
btn_process.clicked.connect(self.processImage)
self.img_browsed = QLabel(self)
self.img_browsed.setText("Browsed image")
self.img_browsed.setGeometry(50, 50, 200, 200)
self.img_processed = QLabel(self)
self.img_processed.setText("Processed image")
self.img_processed.setGeometry(550, 50, 200, 200)
self.comboBox = QComboBox(self)
self.comboBox.addItem("Parallelogram Method")
self.comboBox.move(340, 10)
self.comboBox.currentIndexChanged.connect(self.comboChange)
self.textbox = QTextEdit(self)
self.textbox.setGeometry(300, 50, 200, 200)
self.textbox.setAlignment(Qt.AlignLeft)
self.show()
def getImage(self):
file_name = QFileDialog.getOpenFileName(self, 'Open file',
'c:\\', "Image files (*.jpg *.gif *.bmp *.tif *.png)")
self.img_path = file_name[0]
img = cv.imread(self.img_path, 0)
img = cv.resize(img, dsize=(200, 200), interpolation=cv.INTER_AREA)
cv.imwrite(self.temp_dir, img)
pix_map = QPixmap(self.temp_dir)
self.img_browsed.setPixmap(QPixmap(pix_map))
def comboChange(self):
if self.comboBox.currentText() == "Parallelogram Method":
self.method = "parallelogram"
def processImage(self):
x, y, a, b, fangle = 0, 0, 0, 0, 0
if self.img_path != "":
processed_path = os.path.join(self.dir.name, 'processed.png')
print(processed_path)
pupil = Pupil(self.img_path, processed_path)
if self.method == "parallelogram":
x, y, a, b, fangle = pupil.parallelogram()
text = f"Pupil center:\nX = {x}\nY = {y}\n\nPupil elipse:\na = {a}\nb = {b}\nfangle = {fangle}"
self.textbox.setText(text)
img = cv.imread(processed_path, 1)
# cv.imshow("Pieknie", img)
img = cv.resize(img, dsize=(200, 200), interpolation=cv.INTER_AREA)
resized_path = os.path.join(self.dir.name, 'resized.png')
cv.imwrite(resized_path, img)
pix_map = QPixmap(resized_path)
self.img_processed.setPixmap(QPixmap(pix_map))
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
|
# Modified version of https://github.com/snorkel-team/snorkel-tutorials/blob/master/spam/utils.py
import glob
import os
import subprocess
from collections import OrderedDict
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
def load_spam_dataset(load_train_labels: bool = False, split_dev_valid: bool = False):
if os.path.basename(os.getcwd()) == "snorkel-tutorials":
os.chdir("spam")
try:
subprocess.run(["bash", "download_data.sh"], check=True, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
print(e.stderr.decode())
raise e
filenames = sorted(glob.glob("data/Youtube*.csv"))
dfs = []
for i, filename in enumerate(filenames, start=1):
df = pd.read_csv(filename)
# Lowercase column names
df.columns = map(str.lower, df.columns)
# Remove comment_id field
df = df.drop("comment_id", axis=1)
# Add field indicating source video
df["video"] = [i] * len(df)
# Rename fields
df = df.rename(columns={"class": "label", "content": "text"})
# Shuffle order
df = df.sample(frac=1, random_state=123).reset_index(drop=True)
dfs.append(df)
df_train = pd.concat(dfs[:4])
df_dev = df_train.sample(100, random_state=123)
if not load_train_labels:
df_train["label"] = np.ones(len(df_train["label"])) * -1
df_valid_test = dfs[4]
df_valid, df_test = train_test_split(
df_valid_test, test_size=250, random_state=123, stratify=df_valid_test.label
)
if split_dev_valid:
return df_train, df_dev, df_valid, df_test
else:
return df_train, df_test
|
import os
import logging
import smtplib
import base64
try:
from ConfigParser import ConfigParser
except:
from configparser import ConfigParser
try:
from email.MIMEMultipart import MIMEMultipart
except:
from email.mime.multipart import MIMEMultipart
try:
from email.MIMEText import MIMEText
except:
from email.mime.text import MIMEText
try:
from email.MIMEBase import MIMEBase
except:
from email.mime.base import MIMEBase
try:
from email import Encoders
except:
from email import encoders as Encoders
class Email(object):
def __init__(self, LOGLEVEL="loglevel.INFO"):
"""Creates an object for an Email smtp connection. These methods are implemented:
SendMsg(subject, body)
SendAttachment(subject, body, file)"""
# create file strings from os environment variables
lbplog = os.environ['LBPLOG'] + "/synology/synology.log"
lbpconfig = os.environ['LBPCONFIG'] + "/synology/plugin.cfg"
logging.basicConfig(filename=lbplog,level=LOGLEVEL,format='%(asctime)s: %(message)s ')
cfg = ConfigParser()
cfg.read(lbpconfig)
self.email_user = cfg.get("EMAIL", "USER")
self.mail_to = cfg.get("DISKSTATION", "NOTIFICATION")
self.smtp_server = cfg.get("EMAIL", "SERVER")
self.smtp_port = int(cfg.get("EMAIL", "PORT"))
try:
self.email_pwd = base64.b64decode(cfg.get("EMAIL", "PWD")).decode()
except:
logging.info("<ERROR> mail.py: password could not be decoded!")
def GetVars(self):
"""print out all variables used in this class"""
print(self.email_user)
print(self.mail_to)
print(self.smtp_server)
print(self.smtp_port)
def ServerConnect(self, msg):
"""makes the connection to the smtp server and sends the mail"""
try:
server = smtplib.SMTP(self.smtp_server, self.smtp_port)
server.ehlo()
server.starttls()
server.login(self.email_user, self.email_pwd)
server.sendmail(self.email_user, self.mail_to, msg)
server.quit()
return True
except:
logging.info("<ERROR> SMTP server connection failed")
return False
def SendMsg(self, subj, body):
"""Send Email as text message"""
try:
msg = MIMEText(body)
msg['Subject'] = subj
msg['From'] = self.email_user
msg['To'] = self.mail_to
response = self.ServerConnect(msg.as_string())
logging.debug("<DEBUG> mail.py: ServerConnect response: %s" % response)
if (response == True):
return True
else:
return False
except:
logging.info("<ERROR> mail not sent")
return False
def SendAttachment(self, subj, body, filename):
"""Send Email with attachment"""
try:
msg = MIMEMultipart()
msg['Subject'] = subj
msg['From'] = self.email_user
msg['To'] = self.mail_to
part = MIMEBase('application', "octet-stream")
try:
part.set_payload(open(filename, "rb").read())
except:
logging.info("<ERROR> snapshot could not be opened")
return False
Encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename=%s" % filename)
msg.attach(part)
response = self.ServerConnect(msg.as_string())
logging.debug("<DEBUG> mail.py: ServerConnect response: %s" % response)
if (response == True):
return True
else:
return False
except e:
logging.info("<ERROR> mail not sent")
return False
|
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 1 Module Part 3 - Practice Quiz
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Scripting examples encountered during the Module Part 3 Practice Quiz:
# 01. Fill in the correct Python command to put “My first Python program” onto the screen.
# ___("My first Python program")
print("My first Python program")
# 03. Convert this Bash command into Python.
# echo Have a nice day
print("Have a nice day")
# 04. Fill in the correct Python commands to put “This is fun!” onto the screen 5 times.
# for i in __:
# ___("This is fun!")
for i in range(5):
print("This is fun!")
# 05. Select the Python code snippet that corresponds to the following Javascript snippet:
# for (let i = 0; i < 10; i++) {
# console.log(i);
# }
for i in range(10):
print(i) |
# -*- coding:utf-8 -*-
from spiders.baidu import BaiduSpider
from spiders.douban import DoubanSpider
class BaiduPipeline(object):
def process_item(self, item, spider):
if isinstance(spider, BaiduSpider):
print(u"BaiduSpider item:{}".format(item.data))
return item
class DoubanPipeline(object):
def process_item(self, item, spider):
if isinstance(spider, DoubanSpider):
print(u"DoubanSpider item:{}".format(item.data))
# UnicodeEncodeError-->此处位置不添加u会报的错误
# 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
return item
|
from pylab import *
rc("font", size=16, family="serif", serif="Computer Sans")
rc("text", usetex=True)
num = 41
mu = linspace(100, 120, num)
prior1 = 0.5/(num-1)*ones(num)
prior1[-1] = 0.5
prior2 = exp(-0.5*((mu - 120.)/5)**2)
prior2[0:(num-1)] *= 0.7/sum(prior2[0:(num-1)])
prior2[-1] = 0.3
prior3 = 1./(1. + ((mu - 120.))**2)
prior3 /= sum(prior3)
plot(mu, prior1, 'bo-', markersize=5, linewidth=2, label='Prior 1')
plot(mu, prior2, 'ro-', markersize=5, linewidth=2, label='Prior 2')
plot(mu, prior3, 'go-', markersize=5, linewidth=2, label='Prior 3')
xlim([99., 121.])
ylim([0., 0.55])
legend(loc='upper left')
xlabel('Parameter $\\mu$')
ylabel('Prior Probability')
title('Three Different Priors')
savefig('testing_priors.pdf', bbox_inches='tight')
#show()
|
import requests
import json
# Change this vars as you need
bookstack_url = "https://wiki.bookstack.local" # Bookstack Base URL
header = {'Authorization': 'Token <<TokenID>>:<<TokenSecret>>'} # API Token
verify_ssl = True # Set to False if you have a selfsigned certificate
# create the structure of the book
chapters = {
"Chapter 1": {
"Page 1": "No content yet",
},
"Chapter 2": {
"Page 1": "No content yet",
"Page 2": "No content yet",
"Page 3": "No content yet",
"Page 4": "No content yet",
},
}
# Initialize variables
book_name = input("Book Name: ")
book_create_url = bookstack_url + "/api/books"
chapter_create_url = bookstack_url + "/api/chapters"
site_create_url = bookstack_url + "/api/pages"
book_payload = {"name": book_name}
# Create Book
print("Create book " + book_name)
book_create = requests.post(book_create_url, data=book_payload, headers=header, verify=verify_ssl)
book_data = json.dumps(book_create.json(), separators=(',', ':'))
book_data_loads = json.loads(book_data)
for chapter in chapters:
# Create chapters
print("Create chapter " + chapter)
chapter_create = requests.post(chapter_create_url, data={"book_id": book_data_loads['id'], "name": chapter}, headers=header, verify=verify_ssl)
chapter_data = json.dumps(chapter_create.json(), separators=(',', ':'))
chapter_data_loads = json.loads(chapter_data)
for sites in chapters[chapter]:
# Create pages
print("Create page " + sites)
requests.post(site_create_url, data={"chapter_id": chapter_data_loads['id'], "name": sites, "html": chapters[chapter][sites]}, headers=header, verify=verify_ssl)
print("Book " + book_name + " successfully created")
exit(0)
|
""" Actions that can be performed on the database. """
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, drop_database, create_database
from . import schema as db
def delete_db(uri, **create_engine_kwargs):
"""Deletes database if it exists.
Args:
uri: Database connection uri.
**create_engine_kwargs: Keyword args passed to sqlalchemy.create_engine method.
Returns:
SQLAlchemy engine.
"""
engine = create_engine(uri, **create_engine_kwargs)
if database_exists(engine.url):
drop_database(engine.url)
return engine
def create_db(uri, **create_engine_kwargs):
"""Creates database if not already exists.
Args:
uri: Database connection uri.
**create_engine_kwargs: Keyword args passed to sqlalchemy.create_engine method.
Returns:
SQLAlchemy engine.
"""
engine = create_engine(uri, **create_engine_kwargs)
if not database_exists(engine.url):
create_database(engine.url)
db.Base.metadata.create_all(engine)
return engine
|
import pygame
from controller.ai.execution_template.bfs import BFS
from controller.ai.execution_template.dfs import DFS
from controller.ai.execution_template.iterative_deepening import IterativeDeepening
from controller.events.event_manager_strategy.home_event_manager import HomeEventManager
from controller.menu_state.menu_state import MenuState
from controller.menu_state.states.choose_heuristic_state import ChooseHeuristicState
from model.elements.button import Button
from model.menu_models.home_state_model import HomeStateModel
from model.menu_models.playing_state_model import PlayingStateModel
class ChooseBotState(MenuState):
def __init__(self, game, model):
super().__init__(game, model)
self._event_manager = HomeEventManager(model)
button_dfs = Button(pygame.Rect(model.width // 4 - 200 // 2, 2 * model.height // 6, 200, 100),
"DFS", self.change_state_dfs)
button_bfs = Button(pygame.Rect(model.width // 2 - 200 // 2, 2 * model.height // 6, 200, 100),
"BFS", self.change_state_bfs)
button_iterative_deepening = Button(pygame.Rect(model.width // 2 + 300 // 2, 2 * model.height // 6, 300, 100),
"Iterative Deepening", self.change_state_iterative_deepening)
button_greedy = Button(pygame.Rect(model.width // 2 - 300, 3 * model.height // 6, 300, 100),
"Greedy", self.change_state_greedy)
button_a_star = Button(pygame.Rect(model.width // 2 + 50, 3 * model.height // 6, 300, 100),
"A Star", self.change_state_a_star)
button_back = Button(pygame.Rect(model.width // 2 - 400 // 2, 4 * model.height // 6, 400, 100),
"Back", self.change_state_home)
self.model.buttons.append(button_dfs)
self.model.buttons.append(button_bfs)
self.model.buttons.append(button_iterative_deepening)
self.model.buttons.append(button_greedy)
self.model.buttons.append(button_a_star)
self.model.buttons.append(button_back)
self.running = True
def run(self):
while self.running:
self.model.update()
self.model.draw(self.game.view)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
pygame.quit()
break
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
button = self._event_manager.handle_mouse_event(event)
if button is not None:
self.running = False
return button.callback()
def change_state_home(self):
from controller.menu_state.states.home_state import HomeState
from model.menu_models.home_state_model import HomeStateModel
self.game.menu_state = HomeState(self.game,
HomeStateModel((self.game.view.width, self.game.view.height)))
self.game.run()
def change_state_dfs(self):
self.game.menu_state = DFS(self.game, PlayingStateModel((self.game.view.width, self.game.view.height)))
self.game.run()
def change_state_bfs(self):
self.game.menu_state = BFS(self.game, PlayingStateModel((self.game.view.width, self.game.view.height)))
self.game.run()
def change_state_iterative_deepening(self):
self.game.menu_state = IterativeDeepening(self.game,
PlayingStateModel((self.game.view.width, self.game.view.height)))
self.game.run()
def change_state_greedy(self):
self.game.menu_state = ChooseHeuristicState(self.game,
HomeStateModel((self.game.view.width, self.game.view.height)),
"GREEDY")
self.game.run()
def change_state_a_star(self):
self.game.menu_state = ChooseHeuristicState(self.game,
HomeStateModel((self.game.view.width, self.game.view.height)),
"A_STAR")
self.game.run()
|
from any_board_game.components.cards import Card as Card_
class Card(Card_):
def __gt__(self, other):
# Compare two cards
# If same suit, biggest suit wins, otherwise the spade wins
if self.state['suit'] == other.state['suit']:
return self.state['value'] > other.state['value']
if self.state['suit'] == "S":
return True
elif other.state['suit'] == "S":
return False
return self.state['value'] > other.state['value']
def __lt__(self, other):
return not self.__gt__(other) and not self.__eq__(other)
def __le__(self, other):
return not self.__gt__(other)
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
def __eq__(self, other):
return self.state['suit'] == other.state['suit'] and self.state['value'] == other.state['value']
|
hrsraw = raw_input("Enter Hours:")
hrs = float(hrsraw)
rateraw = raw_input("Enter Rate:")
rate = float(rateraw)
if hrs < 40 :
gross = rate * hrs
elif hrs > 40 :
extragross = (hrs - 40) * (rate * 1.5)
gross = rate * 40
gross = extragross + gross
print gross
|
#!/usr/bin/python
import pygame
pygame.mixer.init()
pygame.mixer.music.load("whizzer.wav")
pygame.mixer.music.play()
tcnt = 0
while pygame.mixer.music.get_busy() == True:
tcnt +=1
print("We are in a loop: %s" % tcnt)
continue
|
# Copyright (c) 2017-2022 The Molecular Sciences Software Institute, Virginia Tech
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Tests for the BSE IO functions
"""
# Most functionality is covered under other tests.
# This tests the remainder
import os
import pytest
from basis_set_exchange import fileio
from .common_testvars import data_dir
# yapf: disable
@pytest.mark.parametrize('file_path', ['cc-pVDZ.0.table.json',
'CRENBL.0.table.json',
'dunning/cc-pVDZ.1.element.json',
'crenb/CRENBL.0.element.json',
'dunning/cc-pVDZ.1.json',
'crenb/CRENBL.0.json',
'crenb/CRENBL-ECP.0.json'])
# yapf: enable
def test_read_write_basis(file_path):
# needed to be tested to make sure something isn't left
# out of the sort lists, etc
full_path = os.path.join(data_dir, file_path)
full_path_new = full_path + '.new'
data = fileio.read_json_basis(full_path)
fileio.write_json_basis(full_path_new, data)
os.remove(full_path_new)
@pytest.mark.parametrize('file_path', ['REFERENCES.json'])
def test_read_write_references(file_path):
# needed to be tested to make sure something isn't left
# out of the sort lists, etc
full_path = os.path.join(data_dir, file_path)
full_path_new = full_path + '.new'
data = fileio.read_references(full_path)
fileio.write_references(full_path_new, data)
os.remove(full_path_new)
|
d = 1
i = 2
def hh()
print'666'
a = 6
|
import functools
import json
import parse
import requests
from sretoolbox.utils import retry
class SentryClient:
ORGANIZATION = "sentry"
def __init__(self, host, token):
self.host = host
self.auth_token = token
@retry()
def _do_sentry_api_call_(self, method, path, slugs, payload=None):
url = f"{self.host}/api/0/{path}/"
if len(slugs) > 0:
url = f"{url}{'/'.join(slugs)}/"
headers = {"Authorization": "Bearer " + self.auth_token}
call = getattr(requests, method, None)
if call is None:
raise ValueError(f"invalid http method {method}")
response = call(url, headers=headers, json=payload)
response.raise_for_status()
try:
all_results = response.json()
except json.decoder.JSONDecodeError:
return
# there may be more pages if the response contains a link header
# link is a string of comma separated items
# with the following structure:
# <URL>; rel="previous/next"; results="false/true"; cursor="value"
item_format = '<{}>; rel="{}"; results="{}"; cursor="{}"'
while True:
link = response.headers.get('link')
if not link:
break
# 2nd item is the next page
next_item = link.split(', ')[1]
# copied with love from
# https://stackoverflow.com/questions/10663093/
# use-python-format-string-in-reverse-for-parsing
_, rel, results, cursor = parse.parse(item_format, next_item)
if rel != 'next' or results != 'true':
break
response = \
call(f"{url}?&cursor={cursor}", headers=headers, json=payload)
response.raise_for_status()
# if there are pages, each response is a list to extend
all_results += response.json()
return all_results
# Organization functions
@functools.lru_cache()
def get_organizations(self):
response = self._do_sentry_api_call_("get", "organizations", [])
return response
def get_organization(self, slug):
response = self._do_sentry_api_call_("get", "organizations", [slug])
return response
# Project functions
@functools.lru_cache()
def get_projects(self):
response = self._do_sentry_api_call_("get", "projects", [])
return response
def get_project(self, slug):
response = self._do_sentry_api_call_("get", "projects",
[self.ORGANIZATION, slug])
return response
def create_project(self, team_slug, name, slug=None):
params = {"name": name}
if slug is not None:
params["slug"] = slug
response = self._do_sentry_api_call_("post", "teams",
[self.ORGANIZATION, team_slug,
"projects"], payload=params)
return response
def delete_project(self, slug):
response = self._do_sentry_api_call_("delete", "projects",
[self.ORGANIZATION, slug])
return response
def get_project_key(self, slug):
response = self._do_sentry_api_call_("get", "projects",
[self.ORGANIZATION, slug, "keys"])
keys = {"dsn": response[0]["dsn"]["public"],
"deprecated": response[0]["dsn"]["secret"]}
return keys
def update_project(self, slug, options):
params = {}
required_fields = self.required_project_fields()
for k, v in required_fields.items():
if v in options:
params[k] = options[v]
self.validate_project_options(options)
optional_fields = self.optional_project_fields()
for k, v in optional_fields.items():
if v in options:
params[k] = options[v]
response = self._do_sentry_api_call_("put", "projects",
[self.ORGANIZATION, slug],
payload=params)
return response
@staticmethod
def required_project_fields():
required_fields = {
"platform": "platform",
"subjectPrefix": "email_prefix"
}
return required_fields
@staticmethod
def optional_project_fields():
optional_fields = {
"sensitiveFields": "sensitive_fields",
"safeFields": "safe_fields",
"resolveAge": "auto_resolve_age",
"allowedDomains": "allowed_domains",
}
return optional_fields
def validate_project_options(self, options):
# If the resolve age is not one of these then sentry will set to 0.
# These are the values selectable in the sentry UI in number of hours
valid_resolve_age = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 18, 21,
24, 30, 36, 48, 72, 96, 120, 144, 168, 192, 216,
240, 288, 312, 336, 360, 384, 408, 432, 456, 480,
504, 528, 552, 576, 600, 624, 648, 672, 696, 720]
optional_fields = self.optional_project_fields()
resolve_age_field = optional_fields["resolveAge"]
if resolve_age_field in options and \
options[resolve_age_field] not in valid_resolve_age:
# If an option is set and invalid, raise exception rather than
# potentially destroying setting by trying to set invalid value
raise ValueError(
f"invalid {resolve_age_field} {options[resolve_age_field]}")
def get_project_alert_rules(self, slug):
response = self._do_sentry_api_call_("get", "projects",
[self.ORGANIZATION, slug,
"rules"])
return response
def delete_project_alert_rule(self, slug, rule):
response = self._do_sentry_api_call_("delete", "projects",
[self.ORGANIZATION, slug, "rules",
rule['id']])
return response
def get_project_owners(self, slug):
teams = self._do_sentry_api_call_("get", "projects",
[self.ORGANIZATION, slug, "teams"])
return teams
def add_project_owner(self, project_slug, team_slug):
response = self._update_project_owner_("post", project_slug, team_slug)
return response
def delete_project_owner(self, project_slug, team_slug):
response = self._update_project_owner_("delete", project_slug,
team_slug)
return response
def _update_project_owner_(self, method, pslug, tslug):
params = {
"organization_slug": self.ORGANIZATION,
"project_slug": pslug,
"team_slug": tslug
}
response = self._do_sentry_api_call_(method, "projects",
[self.ORGANIZATION, pslug,
"teams", tslug], payload=params)
return response
# Team functions
def get_teams(self):
response = self._do_sentry_api_call_("get", "organizations",
[self.ORGANIZATION, "teams"])
return response
def get_team_members(self, team_slug):
response = self._do_sentry_api_call_("get", "teams",
[self.ORGANIZATION, team_slug,
"members"])
return response
def create_team(self, slug):
params = {"slug": slug}
response = self._do_sentry_api_call_("post", "organizations",
[self.ORGANIZATION, "teams"],
payload=params)
return response
def delete_team(self, slug):
response = self._do_sentry_api_call_("delete", "teams",
[self.ORGANIZATION, slug])
return response
def get_team_projects(self, slug):
response = self._do_sentry_api_call_("get", "teams",
[self.ORGANIZATION, slug,
"projects"])
return response
# User/Member functions
@functools.lru_cache()
def get_users(self):
response = self._do_sentry_api_call_("get", "organizations",
[self.ORGANIZATION, "members"])
return response
def get_user(self, email):
users = self.get_users()
user_list = []
for u in users:
if u["email"] == email:
user_list.append(u)
response = []
for user in user_list:
resp = self._do_sentry_api_call_("get", "organizations",
[self.ORGANIZATION, "members",
user["id"]])
if resp is not None:
response.append(resp)
return response
def create_user(self, email, role, teams=[]):
params = {"email": email, "role": role, "teams": teams}
response = self._do_sentry_api_call_("post", "organizations",
[self.ORGANIZATION, "members"],
payload=params)
return response
def delete_user(self, email):
user_list = self.get_user(email)
resp = []
for user in user_list:
response = self._do_sentry_api_call_("delete", "organizations",
[self.ORGANIZATION, "members",
user["id"]])
if response is not None and len(response) > 0:
resp.append(response)
return resp
def delete_user_by_id(self, id):
response = self._do_sentry_api_call_("delete", "organizations",
[self.ORGANIZATION, "members",
id])
return response
def set_user_teams(self, email, teams):
user_list = self.get_user(email)
if len(user_list) > 1:
raise ValueError("set_user_teams will only work for 1 user per "
f"e-mail. E-mail {email} has {len(user_list)} "
"accounts")
user = user_list[0]
params = {"teams": teams}
response = self._do_sentry_api_call_("put", "organizations",
[self.ORGANIZATION, "members",
user["id"]], payload=params)
return response
def remove_user_from_teams(self, email, teams):
user_list = self.get_user(email)
if len(user_list) > 1:
raise ValueError("remove_user_from_teams will only work for 1 "
f"user per e-mail. E-mail {email} has "
f"{len(user_list)} accounts")
user = user_list[0]
user_teams = user["teams"]
for t in teams:
if t in user_teams:
user_teams.remove(t)
params = {"teams": user_teams}
response = self._do_sentry_api_call_("put", "organizations",
[self.ORGANIZATION, "members",
user["id"]], payload=params)
return response
def change_user_role(self, email, role):
user_list = self.get_user(email)
if len(user_list) > 1:
raise ValueError("change_user_role will only work for 1 user per "
f"e-mail. E-mail {email} has {len(user_list)} "
"accounts")
user = user_list[0]
params = {"role": role}
response = self._do_sentry_api_call_("put", "organizations",
[self.ORGANIZATION, "members",
user["id"]], payload=params)
return response
|
from tensorflow.keras.models import Model, load_model
from tensorflow.keras import preprocessing
import numpy as np
from utils.Preprocess import Preprocess
p = Preprocess(word2index_dic='../../train_tools/dict/chatbot_dict.bin',
userdic='../../utils/user_dic.tsv')
new_sentence = '오늘 오전 13시 2분에 탕수육 주문 하고 싶어요'
pos = p.pos(new_sentence)
keywords = p.get_keywords(pos, without_tag=True)
new_seq = p.get_wordidx_sequence(keywords)
max_len = 40
new_padded_seqs = preprocessing.sequence.pad_sequences([new_seq], padding="post", value=0, maxlen=max_len)
print("새로운 유형의 시퀀스 : ", new_seq)
print("새로운 유형의 시퀀스 : ", new_padded_seqs)
# NER 예측
model = load_model('ner_model.h5')
p = model.predict(np.array([new_padded_seqs[0]]))
p = np.argmax(p, axis=-1) # 예측된 NER 인덱스 값 추출
print("{:10} {:5}".format("단어", "예측된 NER"))
print("-" * 50)
index_to_ner = {1: 'O', 2: 'B_DT', 3: 'B_FOOD', 4: 'I', 5: 'B_OG', 6: 'B_PS', 7: 'B_LC', 8: 'NNP', 9: 'B_TI', 0: 'PAD'}
for w, pred in zip(keywords, p[0]):
print("{:10} {:5}".format(w, index_to_ner[pred]))
# 새로운 유형의 시퀀스 : [39, 214, 117, 194, 404, 3, 2, 9]
# 새로운 유형의 시퀀스 : [[ 39 214 117 194 404 3 2 9 0 0 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
# 0 0 0 0]] |
def power_t(x,n=2):
s=1
while n>0:
n-=1
s*=x
return s
|
# encoding: utf-8
# module PySide.QtGui
# from C:\Python27\lib\site-packages\PySide\QtGui.pyd
# by generator 1.147
# no doc
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
class QTableWidgetItem(__Shiboken.Object):
# no doc
def background(self, *args, **kwargs): # real signature unknown
pass
def checkState(self, *args, **kwargs): # real signature unknown
pass
def clone(self, *args, **kwargs): # real signature unknown
pass
def column(self, *args, **kwargs): # real signature unknown
pass
def data(self, *args, **kwargs): # real signature unknown
pass
def flags(self, *args, **kwargs): # real signature unknown
pass
def font(self, *args, **kwargs): # real signature unknown
pass
def foreground(self, *args, **kwargs): # real signature unknown
pass
def icon(self, *args, **kwargs): # real signature unknown
pass
def isSelected(self, *args, **kwargs): # real signature unknown
pass
def read(self, *args, **kwargs): # real signature unknown
pass
def row(self, *args, **kwargs): # real signature unknown
pass
def setBackground(self, *args, **kwargs): # real signature unknown
pass
def setCheckState(self, *args, **kwargs): # real signature unknown
pass
def setData(self, *args, **kwargs): # real signature unknown
pass
def setFlags(self, *args, **kwargs): # real signature unknown
pass
def setFont(self, *args, **kwargs): # real signature unknown
pass
def setForeground(self, *args, **kwargs): # real signature unknown
pass
def setIcon(self, *args, **kwargs): # real signature unknown
pass
def setSelected(self, *args, **kwargs): # real signature unknown
pass
def setSizeHint(self, *args, **kwargs): # real signature unknown
pass
def setStatusTip(self, *args, **kwargs): # real signature unknown
pass
def setText(self, *args, **kwargs): # real signature unknown
pass
def setTextAlignment(self, *args, **kwargs): # real signature unknown
pass
def setToolTip(self, *args, **kwargs): # real signature unknown
pass
def setWhatsThis(self, *args, **kwargs): # real signature unknown
pass
def sizeHint(self, *args, **kwargs): # real signature unknown
pass
def statusTip(self, *args, **kwargs): # real signature unknown
pass
def tableWidget(self, *args, **kwargs): # real signature unknown
pass
def text(self, *args, **kwargs): # real signature unknown
pass
def textAlignment(self, *args, **kwargs): # real signature unknown
pass
def toolTip(self, *args, **kwargs): # real signature unknown
pass
def type(self, *args, **kwargs): # real signature unknown
pass
def whatsThis(self, *args, **kwargs): # real signature unknown
pass
def write(self, *args, **kwargs): # real signature unknown
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass
def __lshift__(self, y): # real signature unknown; restored from __doc__
""" x.__lshift__(y) <==> x<<y """
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass
def __rlshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rlshift__(y) <==> y<<x """
pass
def __rrshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rrshift__(y) <==> y>>x """
pass
def __rshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rshift__(y) <==> x>>y """
pass
ItemType = None # (!) real value is "<type 'PySide.QtGui.QTableWidgetItem.ItemType'>"
Type = PySide.QtGui.QTableWidgetItem.ItemType.Type
UserType = PySide.QtGui.QTableWidgetItem.ItemType.UserType
|
from ch01.creativity.c_1_13 import reverse
from ch01.creativity.c_1_14 import has_odd_product_pair
from ch01.creativity.c_1_15 import are_distinct
from ch01.creativity.c_1_20 import my_shuffle
from ch01.creativity.c_1_21 import reverse_read
|
import ivy
import sys
try:
import shortcodes
except ImportError:
shortcodes = None
# Use a single parser instance to parse all files.
parser = None
# The bare 'shortcodes' attribute for custom settings is deprecated.
if shortcodes:
@ivy.filters.register('node_text')
def render(text, node):
global parser
if parser is None:
new_settings = ivy.site.config.get('shortcode_settings')
old_settings = ivy.site.config.get('shortcodes')
settings = new_settings or old_settings or {}
parser = shortcodes.Parser(**settings)
try:
return parser.parse(text, node)
except shortcodes.ShortcodeError as err:
msg = "Shortcode Error\n"
msg += f">> Node: {node.url}\n"
msg += f">> {err.__class__.__name__}: {err}"
if (cause := err.__cause__):
msg += f"\n>> Cause: {cause.__class__.__name__}: {cause}"
sys.exit(msg)
|
# copied and adpated from https://github.com/tensorflow/models/blob/master/official/transformer/model/embedding_layer.py
import tensorflow as tf
class EmbeddingSharedWeights(tf.layers.Layer):
"""Calculates input embeddings and pre-softmax linear with shared weights."""
def __init__(self, scope, vocab_size, hidden_size):
"""Specify characteristic parameters of embedding layer.
Args:
vocab_size: Number of tokens in the embedding. (Typically ~32,000)
hidden_size: Dimensionality of the embedding. (Typically 512 or 1024)
"""
super(EmbeddingSharedWeights, self).__init__()
self.scope = scope
self.vocab_size = vocab_size
self.hidden_size = hidden_size
def build(self, _):
with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
# Create and initialize weights. The random normal initializer was chosen
# randomly, and works well.
self.shared_weights = tf.get_variable(
"weights", [self.vocab_size, self.hidden_size],
initializer=tf.random_normal_initializer(
0., self.hidden_size ** -0.5))
self.built = True
def call(self, x):
"""Get token embeddings of x.
Args:
x: An int64 tensor with shape [batch_size, length]
Returns:
embeddings: float32 tensor with shape [batch_size, length, embedding_size]
padding: float32 tensor with shape [batch_size, length] indicating the
locations of the padding tokens in x.
"""
with tf.name_scope("embedding"):
# Create binary mask of size [batch_size, length]
mask = tf.to_float(tf.not_equal(x, 0))
embeddings = tf.gather(self.shared_weights, x)
embeddings *= tf.expand_dims(mask, -1)
# Scale embedding by the sqrt of the hidden size
embeddings *= self.hidden_size ** 0.5
return embeddings
def linear(self, x):
"""Computes logits by running x through a linear layer.
Args:
x: A float32 tensor with shape [batch_size, length, hidden_size]
Returns:
float32 tensor with shape [batch_size, length, vocab_size].
"""
with tf.name_scope("presoftmax_linear"):
batch_size = tf.shape(x)[0]
length = tf.shape(x)[1]
x = tf.reshape(x, [-1, self.hidden_size])
logits = tf.matmul(x, self.shared_weights, transpose_b=True)
return tf.reshape(logits, [batch_size, length, self.vocab_size])
|
from .logger import Logger |
import torch
import numpy as np
import os
from torch.nn.functional import interpolate
from torch.utils.data import DataLoader
import torch.optim as optim
from sklearn import metrics
from dataset import ESMH
from models import *
from utils import *
import torch.backends.cudnn as cudnn
import argparse
np.set_printoptions(precision=4)
cudnn.benchmark = True
def train(root_dir='/home/cvip/dataset/ESMH/cropped_patches/na_pd_2d/manual',
test_dir=None,
result_dir='/home/cvip/dataset/ESMH/subtype_results/curr_results',
net='resnet', max_epochs=500, env_name='nnunet',
fold=None, batch_size=32, num_classes=5, in_channels=3):
plotter = VisdomLinePlotter(env_name=env_name)
# data loader
if fold is not None:
data_path = os.path.join(root_dir, 'fold_' + str(fold))
else:
data_path = root_dir
if test_dir is None:
test_dir = data_path
train_data_loader = DataLoader(dataset=ESMH(mode='train', data_path=data_path, dim='2d', use_phases=None, num_phases=in_channels), batch_size=batch_size, shuffle=True)
val_data_loader = DataLoader(dataset=ESMH(mode='test', data_path=test_dir, dim='2d', use_phases=None, num_phases=in_channels, label_path='/data/ESMH/subtypes.json'), batch_size=batch_size, shuffle=False)
if fold is not None:
result_dir = os.path.join(result_dir, 'fold_' + str(fold))
result_dir = os.path.join(result_dir, net)
os.makedirs(result_dir, exist_ok=True)
if net == 'resnet':
model = resnet_mod(in_channels, num_classes)
elif net == 'googlenet':
model = GoogleNet_mod(in_channels, num_classes)
elif net == 'vgg':
model = VGG_mod(in_channels, num_classes)
elif net == 'vgg3d':
model = VGG3D(in_channels, num_classes)
else:
print('wrong net name!')
model.cuda()
#weights = torch.tensor([2.0, 1.0, 1.0, 1.0, 1.0], dtype=torch.float32)
criterion = torch.nn.CrossEntropyLoss().cuda()
initial_lr = 1e-4
optimizer = optim.SGD(model.parameters(), lr=initial_lr, momentum=0.9, weight_decay=0.0002)
# optimizer = optim.Adam(model.parameters(), lr=initial_lr)
for epoch in range(max_epochs):
print('epoch: ', epoch)
optimizer.param_groups[0]['lr'] = poly_lr(epoch, max_epochs, initial_lr)
curr_lr = optimizer.param_groups[0]['lr']
loss_avg = 0
model.train()
for batch_idx, data in enumerate(train_data_loader):
image, label = data
image, label = image.cuda(), label.cuda()
optimizer.zero_grad()
output = model(image)
loss = criterion(output, label)
loss.backward()
optimizer.step()
loss_avg += loss.item()
loss_avg /= len(train_data_loader)
print('train_loss_avg: {:.2f}, lr: {:.6f}'.format(loss_avg, curr_lr))
plotter.plot('loss', 'train', 'Loss ' + result_dir.split('/')[-1], epoch, loss_avg)
loss_avg = 0
true_labels = np.array([])
output_scores = np.array([]).reshape((0, num_classes))
model.eval()
for batch_idx, data in enumerate(val_data_loader):
image, label = data
image, label = image.cuda(), label.cuda()
with torch.no_grad():
output = model(image)
loss = criterion(output, label)
loss_avg += loss.item()
output_sm = torch.nn.functional.softmax(output, dim=1)
output_np = output_sm.detach().cpu().numpy()
output_scores = np.append(output_scores, output_np, axis=0)
true_labels = np.append(true_labels, label.cpu().numpy())
auc = get_roc_auc(true_labels, output_scores, find_opt_thr=False, save_roc=True,
figure_name=os.path.join(result_dir, 'roc_val.jpg'))
conf_mat = calc_conf_mat(true_labels, output_scores)
sen, spe, acc = calc_eval_metric(conf_mat)
loss_avg /= len(val_data_loader)
print('test_loss_avg: {:.2f}, auc: {:.4f}, sen: {:.4f}, spe: {:.4f}, acc: {:.4f}, conf_mat: '.format(loss_avg, auc[5], sen[0], spe[0], acc[5]))
print(conf_mat)
plotter.plot('loss', 'test', 'Class Loss', epoch, loss_avg)
plotter.plot('acc', 'auc', 'Test acc ' + result_dir.split('/')[-2], epoch, auc[5])
plotter.plot('acc', 'auc_0', 'Test acc ' + result_dir.split('/')[-2], epoch, auc[0])
plotter.plot('acc', 'auc_1', 'Test acc ' + result_dir.split('/')[-2], epoch, auc[1])
plotter.plot('acc', 'auc_2', 'Test acc ' + result_dir.split('/')[-2], epoch, auc[2])
plotter.plot('acc', 'auc_3', 'Test acc ' + result_dir.split('/')[-2], epoch, auc[3])
plotter.plot('acc', 'auc_4', 'Test acc ' + result_dir.split('/')[-2], epoch, auc[4])
# plotter.plot('acc', 'sen', 'Test acc ' + result_dir.split('/')[-2], epoch, sen.mean())
# plotter.plot('acc', 'spe', 'Test acc ' + result_dir.split('/')[-2], epoch, spe.mean())
# plotter.plot('acc', 'acc', 'Test acc ' + result_dir.split('/')[-2], epoch, acc[5])
if epoch % 100 == 0:
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, os.path.join(result_dir, 'model.pt'))
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, os.path.join(result_dir, 'model.pt'))
print('done')
def main():
# argument parser
parser = argparse.ArgumentParser(description='ESMH')
parser.add_argument('--root_dir', type=str, default='/data/ESMH/cropped_patches/p3_2d_est/split_13/fold_0')
parser.add_argument('--test_dir', type=str, default=None)
parser.add_argument('--result_dir', type=str, default='/data/ESMH/subtype_results/p3_2d_est/split_13/fold_0')
parser.add_argument('--net', type=str, default='resnet')
parser.add_argument('--epochs', type=int, default=500)
parser.add_argument('--env_name', type=str, default='nnunet')
args = parser.parse_args()
print(args)
train(fold=None, root_dir=args.root_dir, test_dir=args.test_dir, result_dir=args.result_dir, net=args.net, max_epochs=args.epochs, env_name=args.env_name)
if __name__ == "__main__":
main()
|
from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findBottomLeftValueDFS(self, root: TreeNode) -> int:
"""
BFS Solution with queue
"""
queue = deque([root])
cur_lv = []
while queue:
cur_lv = []
for i in range(len(queue)):
cnode = queue.popleft()
if not cur_lv:
cur_lv.append(cnode.val)
if cnode.left:
queue.append(cnode.left)
if cnode.right:
queue.append(cnode.right)
return cur_lv[0]
def findBottomLeftValueBFS(self, root: TreeNode) -> int:
"""
DFS Solution with stack
"""
maxDepth = [0]
leftmost = [0]
curDepth = 0
def dfs(head, curDepth, maxDepth, leftmost):
if head:
curDepth += 1
dfs(head.right, curDepth, maxDepth, leftmost)
if curDepth >= maxDepth[0]:
leftmost[0] = head.val
maxDepth[0] = curDepth
dfs(head.left, curDepth, maxDepth, leftmost)
dfs(root, curDepth, maxDepth, leftmost)
return leftmost[0]
"""
BFS Solution
Runtime: 40 ms, faster than 83.95% of Python3 online submissions for Find Bottom Left Tree Value.
Memory Usage: 14.9 MB, less than 100.00% of Python3 online submissions for Find Bottom Left Tree Value.
"""
|
import re
import collections
from collections import Counter
def json_save(data, f_name):
import json
json = json.dumps(data)
with open(f_name +".json","w") as f:
f.write(json)
def json_read(f_name):
import json
with open(f_name) as f:
return json.load(f)
def get_filelist():
#path = '../wikiextractor/text/AA/wiki_'
path = '../wikiextractor/text/A'
fileN = '0123456789'
fileABC = 'ABCDEFG'
#file_list = "subtxt.txt,subtxt2.txt".split(',')
file_list = []
for a in fileABC:
for n in fileN:
if (a=='G') and (n=='5'):
file_list += [path+a+'/wiki_' + n + s for s in fileN[:9]]
break
else:
file_list += [path+a+'/wiki_' + n + s for s in fileN]
return file_list
def get_text(file):
with open(file, 'r') as f:
data = f.read()
p = re.compile(r'\<.*\>')
#q = re.compile(r'[^0-9a-zA-Z가-힣\-]')
#######################################################################################
q = re.compile(r'[^0-9가-힣\-]') #'_' 가 들어갈 경우 별도조치 필요 : start_ch 와 중복!!!!!!!!!!
#######################################################################################
d_out = p.sub(' ', data)
d_out = q.sub(' ', d_out)
return re.sub('\s{1,}',' ', d_out) # sentence list
def get_sentences(file):
with open(file, 'r') as f:
data = f.read()
p = re.compile(r'\<.*\>')
d_out = p.sub(' ', data)
q = re.compile(r'[^0-9a-zA-Z가-힣\-\.]')
d_out = q.sub(' ', d_out)
d_out = re.sub('\s{1,}',' ', d_out)
sentences = d_out.split('. ')
return [re.sub('\.',' ',s) for s in sentences]
def sentences_from_filelist(file_list, num_files):
sentences =[]
for f in file_list[:num_files]:
sentences += get_sentences(f)
return sentences
def count_from_file(file_list):
c = Counter()
for f in file_list:
d_out = get_text(f)
c = c + Counter(d_out.split(' '))
return c
"""
kor_alpha = CHOSUNG_LIST + ['#']*(ch_len - len(CHOSUNG_LIST)) + JUNGSUNG_LIST + ['#']*(ch_len - len(JUNGSUNG_LIST))+JONGSUNG_LIST
kor_alpha = kor_alpha+['_','$']
etc = [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'{', '|', '}', '~']
#alpha = [C for C in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]+[c for c in 'abcdefghijklmnopqrstuvwxyz']
kor_alpha += etc
"""
# 스페셜 글자를 정상적인 글자로 전환
def special_to_normal(s,key_vars):
BASE_CODE = key_vars['BASE_CODE']
return ind_char([ord(c)-BASE_CODE for c in s], key_vars)
def normal_to_special(word, key_vars):
BASE_CODE = key_vars['BASE_CODE']
special = []
for i in convert(word,key_vars)[1]:
if i != ' ':
special.append(chr(i+BASE_CODE))
else:
special.append(' ')
return ''.join(special)
#######################################################
# 자소 인덱스를 글자로 변환하여 글자를 식별할 수 있도록
#######################################################
def ind_char(idx, key_vars):
ch_len = key_vars['ch_len']
CHOSUNG = key_vars['CHOSUNG']
JUNGSUNG = key_vars['JUNGSUNG']
BASE_CODE = key_vars['BASE_CODE']
kor_alpha = key_vars['kor_alpha']
word_comb = []
nc = [CHOSUNG, JUNGSUNG, 1]
w_idx = BASE_CODE
n_ind = 0
for i,id in enumerate(idx):
if id > 83:
#print(id)
word_comb.append(kor_alpha[id])
w_idx = BASE_CODE
n_ind = 0
continue
if id<0:
word_comb.append(' ')
w_idx = BASE_CODE
n_ind = 0
continue
w_idx += nc[id//ch_len] * (id%ch_len) #초,중,종성 구분 + 각 분류에서 몇번째 인지
n_ind += 1
if i == len(idx)-1: #맨 마지막이면..
word_comb.append(chr(w_idx)) if n_ind>1 else word_comb.append(kor_alpha[id])
#n_ind = 0
elif (idx[i+1]//ch_len==0) or (idx[i+1] < 0): # or (idx[i+1]>ch_len*3): 한 글자가 끝나면..
word_comb.append(chr(w_idx)) if n_ind>1 else word_comb.append(kor_alpha[id])
w_idx = BASE_CODE
n_ind = 0
return ''.join(word_comb)
def convert(test_keyword, key_vars):
ch_len = key_vars['ch_len']
CHOSUNG = key_vars['CHOSUNG']
JUNGSUNG = key_vars['JUNGSUNG']
BASE_CODE = key_vars['BASE_CODE']
kor_alpha = key_vars['kor_alpha']
CHOSUNG_LIST = key_vars['CHOSUNG_LIST']
JUNGSUNG_LIST = key_vars['JUNGSUNG_LIST']
JONGSUNG_LIST = key_vars['JONGSUNG_LIST']
split_keyword_list = list(test_keyword)
#print(split_keyword_list)
result = list()
indexed = list()
num_etc = {}
for i,s in enumerate('0123456789-_'):
num_etc[s] = i+84
for keyword in split_keyword_list:
# 한글 여부 check 후 분리
if re.match('.*[가-힣]+.*', keyword) is not None:
char_code = ord(keyword) - BASE_CODE
char1 = int(char_code / CHOSUNG)
indexed.append(char1)
result.append(CHOSUNG_LIST[char1])
#print('초성 : {}'.format(CHOSUNG_LIST[char1]))
char2 = int((char_code - (CHOSUNG * char1)) / JUNGSUNG)
indexed.append(char2 + ch_len)
result.append(JUNGSUNG_LIST[char2])
#print('중성 : {}'.format(JUNGSUNG_LIST[char2]))
char3 = int((char_code - (CHOSUNG * char1) - (JUNGSUNG * char2)))
if char3==0:
result.append('#')
else:
result.append(JONGSUNG_LIST[char3])
indexed.append(char3 +ch_len*2)
#print('종성 : {}'.format(JONGSUNG_LIST[char3]))
else:
result.append(keyword)
if keyword in '0123456789-_':
indexed.append(num_etc[keyword])
elif keyword == ' ':
indexed.append(keyword)
#if ord(keyword) <127:
# indexed.append(ord(keyword)+54) # 한글이 아닌 경우 잠정적으로 +54 숫자, 영문 대소문자 포함
# result
return "".join(result), indexed #indexed는 자음(초성과 종성 구분), 모음 구분하여 인덱스 각 => [ㄱ ㅏ ㄱ], [0,28,57]
#def vocab_initialize(counters,BASE_CODE,ch_start,ch_end):
def vocab_initialize(counters,key_vars):
BASE_CODE = key_vars['BASE_CODE']
ch_start = key_vars['ch_start']
vocab = {}
#for k,v in counters.items():
#####################
p = re.compile(r"(?P<num1>[걔-걝]+)\s(?P<num2>[걔-걝]+)")
#####################
for k,v in counters:
_, idx = convert(k,key_vars)
#vocab[' '.join([ch_start]+[chr(i+BASE_CODE) for i in idx])] = v
###################
# 숫자 합치기
#p = re.compile(r"(?P<num1>[걔-걝]+)\s(?P<num2>[걔-걝]+)")
kw = ' '.join([ch_start]+[chr(i+BASE_CODE) for i in idx])
while p.search(kw):
kw = p.sub('\g<num1>\g<num2>', kw)
vocab[kw] = v
###################
#vocab[' '.join([ch_start]+[chr(i+BASE_CODE) for i in idx] + [ch_end])] = v
return vocab
def number_attach(counters):
vocab = {}
p = re.compile(r"(?P<num1>[걔-걝]+)\s(?P<num2>[걔-걝]+.*)")
q = re.compile(r"(?P<num3>[걟][걔-걝]*)\s(?P<num4>[걔-걝]+.*)")
num_att = [] # 체크용
for kw,v in counters.items():
i = 0 # 체크용
while p.search(kw):
kw = p.sub('\g<num1>\g<num2>', kw)
i+=1 # 체크용
kw = q.sub('\g<num3>\g<num4>', kw)
vocab[kw] = v
num_att.append(i) # 체크용
print(len(num_att), sum([1 for i in num_att if i>0]), max(num_att))
return vocab
def get_stats(vocab):
pairs = collections.defaultdict(int)
for word, freq in vocab.items():
symbols = word.split()
for i in range(len(symbols)-1):
pairs[symbols[i],symbols[i+1]] += freq
return pairs
def merge_vocab(pair, v_in):
v_out = {}
bigram = re.escape(' '.join(pair))
p = re.compile(r'(?<!\S)' + bigram + r'(?!\S)')
for word in v_in:
w_out = p.sub(''.join(pair), word)
v_out[w_out] = v_in[word]
return v_out
"""
vocab = {'l o w </w>' : 5,
'l o w e r </w>' : 2,
'n e w e s t </w>':6,
'w i d e s t </w>':3
}
"""
def dpe_iteration(vocab, iter_num):
num_merges = iter_num
for i in range(num_merges):
pairs = get_stats(vocab)
best = max(pairs, key=pairs.get)
vocab = merge_vocab(best, vocab)
#print(best)
return vocab
def voc_combined(vocab):
vocab_sub = {}
#for k, v in vocab:
for k, v in vocab.items():
for s in k.split(' '):
if s in vocab_sub.keys():
vocab_sub[s] += v
else:
vocab_sub[s] = v
return vocab_sub, len(vocab_sub)
def vocab_select(vocabs,path,iter_size, step_size,step_from_start,save_cyc):
pre_voc_volume = 0
n = 0
for i in range(iter_size//step_size):
vocabs = dpe_iteration(vocabs,step_size)
_, voc_volume = voc_combined(vocabs)
print("iter_number :{}, voc_volume : {}".format((i+1)*step_size+step_from_start, voc_volume))
iter_n = (i+1) * step_size
if iter_n % save_cyc == 0:
json_save(vocabs, path+ str(step_from_start+iter_n))
if voc_volume < pre_voc_volume:n+=1
pre_voc_volume = voc_volume
if n>3:break
step_from_start += iter_size
#json_save(vocabs, path+'vocabs_'+ str(step_from_start))
#print("iter_number :{}, voc_volume : {}".format(step_from_start, voc_volume))
return vocabs, voc_volume, step_from_start
#iter_size, step_size,step_from_start = 6,2,0
#vocs, v_vol, from_start = vocab_select(vocab, iter_size, step_size,step_from_start)
|
{
"distance_charge": 4.8e-08,
"distance_charge_all": [
14.0641263108,
12.8600114364,
6.8261429168,
2.8385734177,
1.7976439088,
0.3930232044,
0.3185748414,
0.0207838885,
0.0293630023,
0.0033425889,
0.0038933844,
0.0002397749,
6.58407e-05,
4.8137e-06,
1.8709e-06,
1.6308e-06,
4.8e-08
],
"distance_charge_units": "me/bohr^3",
"errors": [],
"info": [],
"iterations_total": 17,
"last_calc_uuid": "36177d08-8377-4c79-a38e-a45d9bd4bcd2",
"loop_count": 1,
"material": "W",
"successful": true,
"total_energy": -16166.1210541652,
"total_energy_all": [
-16166.1261375671,
-16166.1245649923,
-16166.1192980126,
-16166.1206030359,
-16166.1209158221,
-16166.12103797,
-16166.1210144268,
-16166.1210421098,
-16166.1210512503,
-16166.1210530889,
-16166.1210542938,
-16166.1210540822,
-16166.1210541372,
-16166.1210541368,
-16166.1210541662,
-16166.1210541663,
-16166.1210541652
],
"total_energy_units": "Htr",
"total_wall_time": 19,
"total_wall_time_units": "hours",
"warnings": [],
"workflow_name": "fleur_scf_wc",
"workflow_version": "0.2.1"
}
|
from gazenet.utils.registrar import *
@FaceDetectorRegistrar.register
class DlibFaceDetection(object):
def __init__(self):
import face_recognition
self.__face_recognition__ = face_recognition
def detect_frames(self, video_frames_list, match_face=None, **kwargs):
# loading the features for tracking
if match_face is not None:
p_image = self.__face_recognition__.load_image_file("face.jpg")
p_encoding = self.__face_recognition__.face_encodings(p_image)[0]
faces_locations = []
for f_idx in range(len(video_frames_list)):
# detecting the person inside the image if specified
if video_frames_list[f_idx] is not None:
boxes = self.__face_recognition__.face_locations(video_frames_list[f_idx])
if match_face is not None:
tmp_encodings = self.__face_recognition__.face_encodings(video_frames_list[f_idx])
results = self.__face_recognition__.compare_faces(tmp_encodings, p_encoding)
for id, box in enumerate(boxes):
if results[id]:
boxes = [box]
break
faces_locations.append(boxes)
else:
faces_locations.append([])
return faces_locations
@FaceDetectorRegistrar.register
class MTCNNFaceDetection(object):
def __init__(self, device="cuda:0"):
from facenet_pytorch import MTCNN
import numpy as np
self.__mtcnn__ = MTCNN(keep_all=True, device=device)
self.__np__ = np
def detect_frames(self, video_frames_list, **kwargs):
faces_locations = []
for f_idx in range(len(video_frames_list)):
# detect faces
boxes = []
if video_frames_list[f_idx] is not None:
box_vals, _ = self.__mtcnn__.detect(video_frames_list[f_idx])
if box_vals is not None:
for box in box_vals:
(left, top, right, bottom) = box.astype(self.__np__.int32).tolist()
boxes.append([top, right, bottom, left])
faces_locations.append(boxes)
return faces_locations
@FaceDetectorRegistrar.register
class SFDFaceDetection:
def __init__(self, landmarks_type=1, device='cuda:0', flip_input=False, verbose=False):
import torch
import torch.backends.cudnn as cudnn
from face_alignment.detection.sfd import FaceDetector
import numpy as np
self.__torch__ = torch
self.__np__ = np
self.device = device
self.flip_input = flip_input
self.landmarks_type = landmarks_type
self.verbose = verbose
if 'cuda' in device:
cudnn.benchmark = True
# Get the face detector
self.face_detector = FaceDetector(device=device, verbose=verbose)
def detect_frames(self, video_frames_list, **kwargs):
# images = self.__np__.asarray(video_frames_list)[..., ::-1]
# images = self.__np__.squeeze(images, axis=1)
# images = self.__torch__.FloatTensor(images)
images = self.__np__.moveaxis(self.__np__.stack(video_frames_list), -1, 1)
images = self.__torch__.from_numpy(images).to(device=self.device)
detected_faces = self.face_detector.detect_from_batch(images)
face_locations = []
for i, d in enumerate(detected_faces):
if len(d) == 0:
face_locations.append([])
continue
boxes = []
for b in d:
b = self.__np__.clip(b, 0, None)
x1, y1, x2, y2 = map(int, b[:-1])
boxes.append([y1, x2, y2, x1])
face_locations.append(boxes)
return face_locations |
"""Server for multithreaded UI."""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
class UIServer(object):
"""Server that handles comunications to different UI clients."""
def __init__(self, main, host='localHost', port=2243, bufferSize=1024, maxThreads=2):
"""Constuctor."""
self.__main = main
self.__bufferSize = bufferSize
self.__serverSocket = socket(AF_INET, SOCK_STREAM)
self.startServer(host, port, maxThreads)
self.__serverSocket.close()
def startServer(self, host, port, maxThreads):
"""Start the server and listen for new clients in the specified port.
:param host: Host name of the server.
:type host: str
:param port: Port that connects the server.
:type port: int
:param maxThreads: Maximum number of clients.
:type maxThreads: int
"""
self.__serverSocket.bind((host, port))
self.__serverSocket.listen(maxThreads)
acceptConnections = Thread(target=self.getConnections)
acceptConnections.start()
acceptConnections.join()
def getConnections(self):
"""Handle the connections of the clients."""
while True:
clientUI, clientUIAddress = self.__serverSocket.accept()
print("{client} has connected.".format(client=clientUIAddress))
Thread(target=self.clientConnection, args=(clientUI,)).start()
def clientConnection(self, client):
"""Recived all the commands from the client."""
while True:
cmd = client.recv(self.__bufferSize).decode('UTF-8')
if cmd == 'quit':
client.close()
break
elif cmd == 'current':
current = str(self.__main.getCurrentTimePerProcess())
client.send(bytes(current, "utf8"))
else:
client.send(bytes("Command no implemented", "utf8"))
|
# Copyright (c) 2020, Kis Imre. All rights reserved.
# SPDX-License-Identifier: MIT
import unittest
from rpibaremetal.packet import Packet
class TestPacket(unittest.TestCase): #pylint: disable=too-many-public-methods
""" This class is responsible for testing Packet class. """
U8 = 0x12
U16 = 0x1234
U32 = 0x12345678
U64 = 0x1234567890abcdef
DATA = [0x12, 0x34, 0x56, 0x78, 0x90]
CRC = 0xad
EMPTY_CRC = 0x00
U8_DATA = [0x12]
U16_DATA = [0x34, 0x12]
U32_DATA = [0x78, 0x56, 0x34, 0x12]
U64_DATA = [0xef, 0xcd, 0xab, 0x90, 0x78, 0x56, 0x34, 0x12]
def setUp(self):
self.packet = Packet()
def assert_packet_data(self, data):
self.assertEqual(self.packet.get_raw_data(), bytes(data), "Invalid raw data in packet")
def test_push_u8(self):
self.assertEqual(self.packet, self.packet.push_u8(self.U8))
self.assert_packet_data(self.U8_DATA)
def test_push_u16(self):
self.assertEqual(self.packet, self.packet.push_u16(self.U16))
self.assert_packet_data(self.U16_DATA)
def test_push_u32(self):
self.assertEqual(self.packet, self.packet.push_u32(self.U32))
self.assert_packet_data(self.U32_DATA)
def test_push_u64(self):
self.assertEqual(self.packet, self.packet.push_u64(self.U64))
self.assert_packet_data(self.U64_DATA)
def test_push_data(self):
self.assertEqual(self.packet, self.packet.push_data(bytes(self.DATA)))
self.assert_packet_data(self.DATA)
def test_pop_u8(self):
self.packet.push_u8(self.U8)
self.assertEqual(self.packet.pop_u8(), self.U8, "Invalid pop_u8 result")
self.assert_packet_data([])
def test_pop_u16(self):
self.packet.push_u16(self.U16)
self.assertEqual(self.packet.pop_u16(), self.U16, "Invalid pop_u16 result")
self.assert_packet_data([])
def test_pop_u32(self):
self.packet.push_u32(self.U32)
self.assertEqual(self.packet.pop_u32(), self.U32, "Invalid pop_u32 result")
self.assert_packet_data([])
def test_pop_u64(self):
self.packet.push_u64(self.U64)
self.assertEqual(self.packet.pop_u64(), self.U64, "Invalid pop_u64 result")
self.assert_packet_data([])
def test_pop_data(self):
self.packet.push_data(bytes(self.DATA))
self.assertEqual(self.packet.pop_data(len(self.DATA)), bytes(self.DATA),
"Invalid pop_data result")
self.assert_packet_data([])
def test_pop_data_remainder(self):
self.packet.push_data(bytes(self.DATA))
self.assertEqual(self.packet.pop_data(len(self.DATA) - 2), bytes(self.DATA[:-2]),
"Invalid pop result")
self.assert_packet_data(self.DATA[-2:])
def test_peek_u8(self):
self.packet.push_u8(self.U8)
self.assertEqual(self.packet.peek_u8(), self.U8, "Invalid peek_u8 result")
self.assert_packet_data(self.U8_DATA)
def test_peek_u16(self):
self.packet.push_u16(self.U16)
self.assertEqual(self.packet.peek_u16(), self.U16, "Invalid peek_u16 result")
self.assert_packet_data(self.U16_DATA)
def test_peek_u32(self):
self.packet.push_u32(self.U32)
self.assertEqual(self.packet.peek_u32(), self.U32, "Invalid peek_u32 result")
self.assert_packet_data(self.U32_DATA)
def test_peek_u64(self):
self.packet.push_u64(self.U64)
self.assertEqual(self.packet.peek_u64(), self.U64, "Invalid peek_u64 result")
self.assert_packet_data(self.U64_DATA)
def test_peek_data(self):
self.packet.push_data(bytes(self.DATA))
self.assertEqual(self.packet.peek_data(len(self.DATA)), bytes(self.DATA),
"Invalid peek_data result")
self.assert_packet_data(self.DATA)
def test_add_crc(self):
self.packet.push_data(bytes(self.DATA))
self.assertEqual(self.packet, self.packet.add_crc())
self.assert_packet_data(self.DATA + [self.CRC])
def test_add_crc_empty(self):
self.assertEqual(self.packet, self.packet.add_crc())
self.assert_packet_data([self.EMPTY_CRC])
def test_check_crc_ok(self):
self.packet.push_data(bytes(self.DATA))
self.assertEqual(self.packet, self.packet.add_crc())
self.assertEqual(self.packet.check_crc(), True, "Invalid check_crc result")
def test_check_crc_fail(self):
self.packet.push_data(bytes(self.DATA))
# No add_crc here
self.assertEqual(self.packet.check_crc(), False, "Invalid check_crc result")
if __name__ == "__main__":
unittest.main()
|
from django.urls import path
from django.views.generic import TemplateView
from django.contrib import auth
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', views.index, name = 'index'),
path('do_work/', views.do_work_view, name = 'work_view'),
path('new_board/', views.new_board_view, name = 'new_board_view'),
path('login/', auth_views.LoginView.as_view(template_name="boards/login.html", extra_context = {'user_creation_form' : UserCreationForm()})),
path('logout/',views.logout_view, name = 'logout'),
path('board_delete/', views.board_delete_view, name = 'board_delete_view'),
path('scrum/', views.scrum_view, name = 'scrum_view'),
path('scrum/submit/', views.scrum_submit_view, name ="scrum_submit_view"),
path('login/process/', auth_views.LoginView.as_view(template_name = "boards/login.html",extra_context = {'user_creation_form' : UserCreationForm()})),
path('login/createuser/', views.process_create_user, name = "process_create_user"),
path('process_task', views.process_task),
]
|
from rest_framework.routers import DefaultRouter
from editors.content.views import (
CommunityViewSet,
EditViewSet,
ProjectVideoViewSet,
ProjectViewSet,
)
router = DefaultRouter()
router.register("project", viewset=ProjectViewSet, basename="project")
router.register("community", viewset=CommunityViewSet, basename="community")
router.register("project-video", viewset=ProjectVideoViewSet, basename="project-video")
router.register("edit", viewset=EditViewSet, basename="edit")
app_name = "content"
urlpatterns = [] + router.urls
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : config.py
@Desc :
@Project : english_reading
@Contact : thefreer@outlook.com
@License : (C)Copyright 2018-2020, ZJH
@WebSite : zjh567.github.io
@Modify Time @Author @Version
------------ ------- --------
2020/01/16 15:47 ZJH 1.0
'''
# https://github.com/brightmart/nlp_chinese_corpus
# http://www.52nlp.cn/category/corpus
# 使用 replace 处理原来的标记。如 <text>替代###
structure = {
}
|
from setuptools import setup
package_name = 'ldcp_node'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='gaudat',
maintainer_email='ros@gaudat.name',
description='ROS2 driver for 3irobotix lidars speaking LDCP',
license='Apache-2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'ldcp_node = ldcp_node.ldcp_node:main'
],
},
)
|
import numpy as np
import sympy
from sympy import Matrix
DOF = 2
def name_ind(i):
if i >=0 and i < DOF:
return 'c1'
elif i >= DOF and i < 2*DOF:
return 'c2'
elif i >= 2*DOF and i < 3*DOF:
return 'c3'
else:
raise
sympy.var('A, le, xi')
sympy.var('rho, E, nu, c, s')
N1 = (1-xi)/2
N2 = (1+xi)/2
Nu = Matrix([[N1, 0, N2, 0]])
Nv = Matrix([[0, N1, 0, N2]])
# Constitutive linear stiffness matrix
#c
R = Matrix([[c, s, 0, 0],
[-s, c, 0, 0],
[0, 0, c, s],
[0, 0, -s, c]])
num_nodes = 2
BLu = Matrix([[(2/le)*N1.diff(xi), 0, (2/le)*N2.diff(xi), 0]])
Ke = A*E/le*Matrix([[1, 0, -1, 0],
[0, 0, 0, 0],
[-1, 0, 1, 0],
[0, 0, 0, 0]])
Me = (le/2)*sympy.integrate(rho*A*(Nu.T*Nu + Nv.T*Nv), (xi, -1, +1))
Me_lumped = A*rho*le/2*Matrix(
[[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
print('printing Me')
for ind, val in np.ndenumerate(Me):
if val == 0:
continue
i, j = ind
si = name_ind(i)
sj = name_ind(j)
print(' Me[%d+%s, %d+%s]' % (i%DOF, si, j%DOF, sj), '+=', Me[ind])
print('printing Me_lumped')
for ind, val in np.ndenumerate(Me_lumped):
if val == 0:
continue
i, j = ind
si = name_ind(i)
sj = name_ind(j)
print(' Me[%d+%s, %d+%s]' % (i%DOF, si, j%DOF, sj), '+=', Me_lumped[ind])
K = sympy.zeros(num_nodes*DOF, num_nodes*DOF)
M = sympy.zeros(num_nodes*DOF, num_nodes*DOF)
M_lumped = sympy.zeros(num_nodes*DOF, num_nodes*DOF)
# global
K[:, :] = R.T*Ke*R
M[:, :] = R.T*Me*R
M_lumped[:, :] = R.T*Me_lumped*R
# K represents the global stiffness matrix
# in case we want to apply coordinate transformations
print('printing K')
for ind, val in np.ndenumerate(K):
i, j = ind
si = name_ind(i)
sj = name_ind(j)
print(' K[%d+%s, %d+%s]' % (i%DOF, si, j%DOF, sj), '+=', K[ind])
print('printing M')
for ind, val in np.ndenumerate(M):
if val == 0:
continue
i, j = ind
si = name_ind(i)
sj = name_ind(j)
print(' M[%d+%s, %d+%s]' % (i%DOF, si, j%DOF, sj), '+=', M[ind])
print('printing M_lumped')
for ind, val in np.ndenumerate(M_lumped):
if val == 0:
continue
i, j = ind
si = name_ind(i)
sj = name_ind(j)
print(' M[%d+%s, %d+%s]' % (i%DOF, si, j%DOF, sj), '+=', M_lumped[ind])
|
"""
UI component loaded on the 'Datasets' tab.
Functions:
get_component():
returns a component containing the input dropdown
and a graph plot for each dataset we have.
attach_callbacks():
attaches the callback for the dropdown.
Classes:
None
"""
import dash_core_components as dcc
import dash_html_components as html
import dash
import backend.user_input as user_input
def get_params(x_cords, y_cords):
"""
Constructs the plotly specific graph parameters. This configuration
object can be passed to a Graph dash component.
Args:
x_cords = the vector containing the x-coordinates of all the points
y_cords = the vector containing the y-coordinates of all the points
Returns:
Plotly graph configuration object
"""
return {
'data': [{
'x': x_cords,
'y': y_cords,
'text': x_cords,
'textfont': dict(
family='sans serif',
size=19,
color='#1f77b4'
),
'type': 'line'
}],
'layout': {
'title': 'Index time-series',
'xaxis': {
'title': 'Date'
},
'yaxis': {
'title': 'Price'
}
}
}
def get_component():
"""
Returns a div containing the dropdown and
the graph of the dataset selected.
Args:
None
Returns:
div containing the component in this tab.
"""
return html.Div(children=[
dcc.Dropdown(
options=[
{'label': i, 'value': i} for i in user_input.INVESTMENT_CLASS_DICT
],
value=list(user_input.INVESTMENT_CLASS_DICT)[0],
id='datasets-dropdown'
),
html.Div(id='datasets-container')
])
def attach_callbacks(app):
"""
Attaches the callback to the dropdown component in this tab.
Re-renders the graph when a new value is selected in the dropdown
Args:
app: the dash app
Returns:
None
"""
@app.callback(
dash.dependencies.Output('datasets-container', 'children'),
[dash.dependencies.Input('datasets-dropdown', 'value')])
def _update_output(value):
if value is None:
return ""
dataset = user_input.INVESTMENT_CLASS_DICT[value]
return dcc.Graph(
id='datasets-graph',
figure=get_params(dataset.index, dataset.values[:, 0]))
|
from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
import os, sys
import numpy as np
import matplotlib.pyplot as plt
from scipy import loadtxt
data = loadtxt('energies.dat')
chi, phi, E = data[:,1], data[:,2], data[:,3]
chi_bins, phi_bins = int(chi/15), int(phi/30)
nchi = int(360/15) + 1
nphi = int(360/30) + 1
E_2D = np.max(E)*np.ones( (nphi, nchi), dtype=np.float )
for i in range(len(chi)):
E_2D[phi_bins[i], chi_bins[i]] = E[i]
print(E_2D)
plt.figure()
#plt.pcolor(E_2D.transpose())
plt.contour(E_2D)
plt.show()
|
from escpos.printer import Usb
from escpos import *
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import unicodedata
import datetime
import subprocess
def set_patlite_progress(progress):
if progress == 0:
subprocess.call(' '.join(['rsh', '192.168.10.1', '-l', 'pi', 'alert', '000000', '0']), shell=True)
elif progress == 1:
subprocess.call(' '.join(['rsh', '192.168.10.1', '-l', 'pi', 'alert', '002000', '0']), shell=True)
elif progress == 2:
subprocess.call(' '.join(['rsh', '192.168.10.1', '-l', 'pi', 'alert', '021000', '0']), shell=True)
elif progress == 3:
subprocess.call(' '.join(['rsh', '192.168.10.1', '-l', 'pi', 'alert', '211000', '0']), shell=True)
elif progress == 4:
subprocess.call(' '.join(['rsh', '192.168.10.1', '-l', 'pi', 'alert', '000000', '0']), shell=True)
subprocess.call(' '.join(['rsh', '192.168.10.1', '-l', 'pi', 'alert', '111000', '2']), shell=True)
def set_patlite(cmd, t):
subprocess.call(' '.join(['rsh', '192.168.10.1', '-l', 'pi', 'alert', str(cmd), str(t)]), shell=True)
def get_east_asian_width_count(text):
count = 0
for c in text:
if unicodedata.east_asian_width(c) in 'FWA':
count += 2
else:
count += 1
return count
def print_text(text, headers='', pil_obj=None):
width = 390
dt_now = datetime.datetime.now()
im_resized = None
if pil_obj is not None:
ratio = 390 / pil_obj.width
height_p = int(pil_obj.height * ratio) #(5)
if height_p >= 1000:
raise Exception('画像変換後の画像が縦1000pxを超えています')
im_resized_tmp = pil_obj.resize((390, height_p), Image.LANCZOS)
x1, y1, x2, y2 = 0, 0, 390, im_resized_tmp.height+1
im_resized = Image.new('RGB', (x2 - x1, y2 - y1), (255, 255, 255))
im_resized.paste(im_resized_tmp, (-x1, -y1))
im_resized.save('img/'+dt_now.strftime('%Y-%m-%d_%H-%M-%S')+'_IMG.png', quality=95)
# テキスト配列化
text_p = headers + text
sp_str = []
col = 0
col_str = ''
for d in list(text_p):
if col >= 27 or d == '\n':
sp_str.append(col_str)
col = 0
col_str = ''
if d == '\n':
continue
col += get_east_asian_width_count(d)
col_str += d
if len(d) > 0:
sp_str.append(col_str)
#画像化処理
height = len(sp_str) * 30
if height < 1:
raise Exception('印刷する文字がありません')
elif height > 3000:
raise Exception('100行を超えるテキストの印刷はできません')
image_tmp = Image.new('1', (width, height), 255)
draw = ImageDraw.Draw(image_tmp)
font = ImageFont.truetype('RictyDiminished-Regular.ttf', 28, encoding='unic')
#print(sp_str)
counter_h = 0
for l in sp_str:
draw.text((0, counter_h), l, font=font, fill=0)
counter_h += 30
# 画像バグ防止
x1, y1, x2, y2 = 0, 0, 390, height+1
image = Image.new('RGB', (x2 - x1, y2 - y1), (255, 255, 255))
image.paste(image_tmp, (-x1, -y1))
image.save('img/'+dt_now.strftime('%Y-%m-%d_%H-%M-%S')+'.jpg', quality=95)
set_patlite_progress(3)
# 印刷実行
p = Usb(0x0416, 0x5011, 0, 0x81, 0x01)
p.text(" ")
p.image(image)
if pil_obj is not None:
p.image(im_resized)
p.cut()
p.close()
def print_image(pil_obj):
width = 390
ratio = width / pil_obj.width
height = int(pil_obj.height * ratio) #(5)
im_resized = pil_obj.resize((width, height), Image.LANCZOS)
# 印刷実行
p = Usb(0x0416, 0x5011, 0, 0x81, 0x01)
p.text(" ")
p.image(im_resized)
p.cut()
p.close() |
# -*- coding: utf-8 -*-
# data
provinceList_json = '{"1": ["北京","beijing"],"2": ["天津","tianjin"],"3": ["河北","hebei"],"4": ["山西","shanxi"],"5": ["内蒙古","neimenggu"],"6": ["辽宁","liaoning"],"7": ["吉林","jilin"],"8": ["黑龙江","heilongjiang"],"9": ["上海","shanghai"],"10": ["江苏","jiangsu"],"11": ["浙江","zhejiang"],"12": ["安徽","anhui"],"13": ["福建","fujian"],"14": ["江西","jiangxi"],"15": ["山东","shandong"],"16": ["河南","henan"],"17": ["湖北","hubei"],"18": ["湖南","hunan"],"19": ["广东","guangdong"],"20": ["广西","guangxi"],"21": ["海南","hainan"],"22": ["重庆","chongqing"],"23": ["四川","sichuan"],"24": ["贵州","guizhou"],"25": ["云南","yunnan"],"26": ["西藏","xizang"],"27": ["陕西","shan_xi"],"28": ["甘肃","gansu"],"29": ["青海","qinghai"],"30": ["宁夏","ningxia"],"31": ["新疆","xinjiang"]}'
stationList_json = '{"24": {"黔西南州": [{"Latitude": "25.0925", "StationCode": "2589A", "PositionName": "场坝街", "Longitude": "104.9022"}, {"Latitude": "25.0992", "StationCode": "2590A", "PositionName": "坪东大道", "Longitude": "104.8811"}], "安顺市": [{"Latitude": "26.2611", "StationCode": "2581A", "PositionName": "虹机厂子校", "Longitude": "105.9556"}, {"Latitude": "26.255", "StationCode": "2582A", "PositionName": "市一中", "Longitude": "105.9278"}, {"Latitude": "26.2358", "StationCode": "2583A", "PositionName": "铁路子校", "Longitude": "105.9394"}, {"Latitude": "26.2392", "StationCode": "2584A", "PositionName": "龙岩子校", "Longitude": "105.8853"}], "遵义市": [{"Latitude": "27.6869", "StationCode": "1911A", "PositionName": "丁字口", "Longitude": "106.9222"}, {"Latitude": "27.7019", "StationCode": "1912A", "PositionName": "凤凰山", "Longitude": "106.9242"}, {"Latitude": "27.6486", "StationCode": "1913A", "PositionName": "忠庄", "Longitude": "106.8906"}, {"Latitude": "27.6506", "StationCode": "1914A", "PositionName": "舟水桥", "Longitude": "106.9231"}, {"Latitude": "27.7200", "StationCode": "1915A", "PositionName": "干田坝", "Longitude": "106.9178"}], "贵阳市": [{"Latitude": "26.6029", "StationCode": "1439A", "PositionName": "马鞍山", "Longitude": "106.6856"}, {"Latitude": "26.5689", "StationCode": "1440A", "PositionName": "市环保站", "Longitude": "106.6971"}, {"Latitude": "26.6266", "StationCode": "1441A", "PositionName": "鉴湖路", "Longitude": "106.6243"}, {"Latitude": "26.6343", "StationCode": "1442A", "PositionName": "燕子冲", "Longitude": "106.7487"}, {"Latitude": "26.4364", "StationCode": "1443A", "PositionName": "碧云窝", "Longitude": "106.6554"}, {"Latitude": "26.5155", "StationCode": "1444A", "PositionName": "中院村", "Longitude": "106.6948"}, {"Latitude": "26.6009", "StationCode": "1445A", "PositionName": "红边门", "Longitude": "106.7105"}, {"Latitude": "26.5697", "StationCode": "1446A", "PositionName": "新华路", "Longitude": "106.7164"}, {"Latitude": "26.5495", "StationCode": "1447A", "PositionName": "太慈桥", "Longitude": "106.6867"}, {"Latitude": "26.3003", "StationCode": "1552A", "PositionName": "桐木岭", "Longitude": "106.805"}], "铜仁地区": [{"Latitude": "27.7297", "StationCode": "2585A", "PositionName": "铜仁卫校", "Longitude": "109.1916"}, {"Latitude": "27.7231", "StationCode": "2586A", "PositionName": "铜仁七中", "Longitude": "109.1794"}], "毕节市": [{"Latitude": "27.3125", "StationCode": "2587A", "PositionName": "八中", "Longitude": "105.2864"}, {"Latitude": "27.2944", "StationCode": "2588A", "PositionName": "师专", "Longitude": "105.31"}], "黔南州": [{"Latitude": "26.2403", "StationCode": "2593A", "PositionName": "小围寨", "Longitude": "107.5228"}], "六盘水市": [{"Latitude": "26.5892", "StationCode": "2576A", "PositionName": "窑上", "Longitude": "104.8"}, {"Latitude": "26.5917", "StationCode": "2577A", "PositionName": "黄土坡", "Longitude": "104.83"}, {"Latitude": "26.5939", "StationCode": "2578A", "PositionName": "水钢", "Longitude": "104.89"}, {"Latitude": "26.5894", "StationCode": "2579A", "PositionName": "民中", "Longitude": "104.8475"}, {"Latitude": "26.5506", "StationCode": "2580A", "PositionName": "双水", "Longitude": "104.9544"}], "黔东南州": [{"Latitude": "26.5747", "StationCode": "2591A", "PositionName": "市环境监测站", "Longitude": "107.9783"}, {"Latitude": "26.53111111", "StationCode": "2881A", "PositionName": "凯里学院", "Longitude": "107.8908333"}]}, "25": {"曲靖市": [{"Latitude": "25.5035", "StationCode": "1916A", "PositionName": "环境监测站", "Longitude": "103.7897"}, {"Latitude": "25.5364", "StationCode": "1917A", "PositionName": "烟厂办公区", "Longitude": "103.8000"}], "红河州": [{"Latitude": "23.4626", "StationCode": "2607A", "PositionName": "雨过铺", "Longitude": "103.3113"}, {"Latitude": "23.3993", "StationCode": "2608A", "PositionName": "污水处理厂", "Longitude": "103.3772"}, {"Latitude": "23.4168", "StationCode": "2609A", "PositionName": "监测站", "Longitude": "103.386"}], "楚雄州": [{"Latitude": "25.0441", "StationCode": "2605A", "PositionName": "州环境监测站", "Longitude": "101.5482"}, {"Latitude": "25.0492", "StationCode": "2606A", "PositionName": "市经济开发区", "Longitude": "101.538"}], "大理州": [{"Latitude": "25.7054", "StationCode": "2614A", "PositionName": "大理市环境监测站", "Longitude": "100.1542"}, {"Latitude": "25.5811", "StationCode": "2615A", "PositionName": "大理古城", "Longitude": "100.2171"}], "怒江州": [{"Latitude": "25.8567", "StationCode": "2618A", "PositionName": "州监测站", "Longitude": "98.8601"}, {"Latitude": "25.8417", "StationCode": "2619A", "PositionName": "泸水一中", "Longitude": "98.8546"}], "德宏州": [{"Latitude": "24.428", "StationCode": "2616A", "PositionName": "德宏州监测站", "Longitude": "98.5842"}, {"Latitude": "24.441", "StationCode": "2617A", "PositionName": "芒市建设局", "Longitude": "98.578"}], "临沧市": [{"Latitude": "23.8822", "StationCode": "2603A", "PositionName": "市环保局", "Longitude": "100.0869"}, {"Latitude": "23.8982", "StationCode": "2604A", "PositionName": "市气象局", "Longitude": "100.0782"}], "普洱市": [{"Latitude": "22.7633", "StationCode": "2601A", "PositionName": "市环保局", "Longitude": "100.98"}, {"Latitude": "22.8322", "StationCode": "2602A", "PositionName": "普洱第二中学", "Longitude": "100.9817"}], "文山州": [{"Latitude": "23.3594", "StationCode": "2610A", "PositionName": "州水务局", "Longitude": "104.2533"}, {"Latitude": "23.3892", "StationCode": "2611A", "PositionName": "市便民服务中心", "Longitude": "104.2319"}], "玉溪市": [{"Latitude": "24.3694", "StationCode": "1715A", "PositionName": "东风水库", "Longitude": "102.5778"}, {"Latitude": "24.3702", "StationCode": "2882A", "PositionName": "玉溪一中", "Longitude": "102.5389"}, {"Latitude": "24.339", "StationCode": "2883A", "PositionName": "文体中心", "Longitude": "102.5381"}], "保山市": [{"Latitude": "25.1081", "StationCode": "2594A", "PositionName": "市环境监测站", "Longitude": "99.1678"}, {"Latitude": "25.1328", "StationCode": "2595A", "PositionName": "市环保局", "Longitude": "99.1711"}], "昆明市": [{"Latitude": "25.0124", "StationCode": "1449A", "PositionName": "关上", "Longitude": "102.743"}, {"Latitude": "24.8885", "StationCode": "1450A", "PositionName": "呈贡新区", "Longitude": "102.821"}, {"Latitude": "24.9624", "StationCode": "1451A", "PositionName": "西山森林公园", "Longitude": "102.625"}, {"Latitude": "25.0836", "StationCode": "1452A", "PositionName": "龙泉镇", "Longitude": "102.728"}, {"Latitude": "25.0405", "StationCode": "1453A", "PositionName": "东风东路", "Longitude": "102.722"}, {"Latitude": "25.067", "StationCode": "1454A", "PositionName": "金鼎山", "Longitude": "102.681"}, {"Latitude": "25.0359", "StationCode": "1455A", "PositionName": "碧鸡广场", "Longitude": "102.638"}], "昭通市": [{"Latitude": "27.3392", "StationCode": "2596A", "PositionName": "监测站", "Longitude": "103.7032"}, {"Latitude": "27.3361", "StationCode": "2597A", "PositionName": "环保局", "Longitude": "103.7225"}], "丽江市": [{"Latitude": "26.8576", "StationCode": "2598A", "PositionName": "西南郊", "Longitude": "100.2143"}, {"Latitude": "26.8802", "StationCode": "2599A", "PositionName": "丽江古城", "Longitude": "100.2497"}, {"Latitude": "26.8906", "StationCode": "2600A", "PositionName": "市中心", "Longitude": "100.2203"}], "西双版纳州": [{"Latitude": "22.0019", "StationCode": "2612A", "PositionName": "景洪市江南", "Longitude": "100.7939"}, {"Latitude": "22.0225", "StationCode": "2613A", "PositionName": "景洪市江北", "Longitude": "100.8017"}], "迪庆州": [{"Latitude": "27.8136", "StationCode": "2620A", "PositionName": "古城", "Longitude": "99.7064"}, {"Latitude": "27.8317", "StationCode": "2621A", "PositionName": "迪庆州站", "Longitude": "99.7056"}]}, "26": {"山南地区": [{"Latitude": "29.2313", "StationCode": "2624A", "PositionName": "山南监测站", "Longitude": "91.7608"}, {"Latitude": "29.261", "StationCode": "2625A", "PositionName": "山南人民医院", "Longitude": "91.7706"}], "昌都地区": [{"Latitude": "31.1278", "StationCode": "2622A", "PositionName": "昌都监测站", "Longitude": "97.1804"}, {"Latitude": "31.1254", "StationCode": "2623A", "PositionName": "昌都地区昌都坝", "Longitude": "97.1809"}], "林芝地区": [{"Latitude": "29.6376", "StationCode": "2632A", "PositionName": "林芝监测站", "Longitude": "94.3681"}, {"Latitude": "29.6632", "StationCode": "2633A", "PositionName": "林芝人民医院", "Longitude": "94.3616"}], "阿里地区": [{"Latitude": "32.5", "StationCode": "2630A", "PositionName": "阿里监测站", "Longitude": "80.1161"}, {"Latitude": "32.5039", "StationCode": "2631A", "PositionName": "阿里地委", "Longitude": "80.0895"}], "拉萨市": [{"Latitude": "29.6514", "StationCode": "1456A", "PositionName": "八廓街", "Longitude": "91.1319"}, {"Latitude": "29.6747", "StationCode": "1457A", "PositionName": "市环保局", "Longitude": "91.1221"}, {"Latitude": "29.6475", "StationCode": "1458A", "PositionName": "区监测站", "Longitude": "91.0874"}, {"Latitude": "29.6541", "StationCode": "1459A", "PositionName": "西藏大学", "Longitude": "91.1774"}, {"Latitude": "29.6588", "StationCode": "1460A", "PositionName": "区辐射站", "Longitude": "90.9798"}, {"Latitude": "29.6292", "StationCode": "1461A", "PositionName": "拉萨火车站", "Longitude": "91.0834"}], "日喀则地区": [{"Latitude": "29.2718", "StationCode": "2626A", "PositionName": "日喀则监测站", "Longitude": "88.8876"}, {"Latitude": "29.2365", "StationCode": "2627A", "PositionName": "日喀则鸿达公司", "Longitude": "88.8931"}], "那曲地区": [{"Latitude": "31.4846", "StationCode": "2628A", "PositionName": "那曲监测站", "Longitude": "92.0657"}]}, "27": {"延安市": [{"Latitude": "36.6275", "StationCode": "1926A", "PositionName": "枣园", "Longitude": "109.4131"}, {"Latitude": "36.6028", "StationCode": "1927A", "PositionName": "延大医附院", "Longitude": "109.4761"}, {"Latitude": "36.5767", "StationCode": "1928A", "PositionName": "市监测站", "Longitude": "109.4824"}, {"Latitude": "36.6106", "StationCode": "1929A", "PositionName": "百米大道", "Longitude": "109.5056"}], "宝鸡市": [{"Latitude": "34.3708", "StationCode": "1930A", "PositionName": "庙沟村", "Longitude": "107.1586"}, {"Latitude": "34.3017", "StationCode": "1931A", "PositionName": "竹园沟", "Longitude": "107.0708"}, {"Latitude": "34.3672", "StationCode": "1932A", "PositionName": "三陆医院", "Longitude": "107.1906"}, {"Latitude": "34.3547", "StationCode": "1933A", "PositionName": "监测站", "Longitude": "107.1431"}, {"Latitude": "34.3739", "StationCode": "1934A", "PositionName": "技工学校", "Longitude": "107.1186"}, {"Latitude": "34.3528", "StationCode": "1935A", "PositionName": "陈仓环保局", "Longitude": "107.3906"}, {"Latitude": "34.3497", "StationCode": "1936A", "PositionName": "文理学院", "Longitude": "107.2058"}, {"Latitude": "34.3622", "StationCode": "1937A", "PositionName": "三迪小学", "Longitude": "107.2386"}], "安康市": [{"Latitude": "32.6778", "StationCode": "2642A", "PositionName": "香溪洞", "Longitude": "109.0311"}, {"Latitude": "32.6939", "StationCode": "2643A", "PositionName": "安康市监测站", "Longitude": "109.0281"}, {"Latitude": "32.6975", "StationCode": "2644A", "PositionName": "汉滨区检察院", "Longitude": "109.0072"}], "榆林市": [{"Latitude": "38.3344", "StationCode": "2638A", "PositionName": "红石峡森林公园", "Longitude": "109.7414"}, {"Latitude": "38.2911", "StationCode": "2639A", "PositionName": "世纪广场", "Longitude": "109.7456"}, {"Latitude": "38.2839", "StationCode": "2640A", "PositionName": "实验中学", "Longitude": "109.7289"}, {"Latitude": "38.2478", "StationCode": "2641A", "PositionName": "环保监测大楼", "Longitude": "109.7336"}], "咸阳市": [{"Latitude": "34.3956", "StationCode": "1918A", "PositionName": "气象站", "Longitude": "108.7197"}, {"Latitude": "34.3181", "StationCode": "1919A", "PositionName": "中华小区", "Longitude": "108.6761"}, {"Latitude": "34.3617", "StationCode": "1920A", "PositionName": "师范学院", "Longitude": "108.7233"}, {"Latitude": "34.3164", "StationCode": "1921A", "PositionName": "中医学院", "Longitude": "108.7369"}], "渭南市": [{"Latitude": "34.5101", "StationCode": "1938A", "PositionName": "农科所", "Longitude": "109.5293"}, {"Latitude": "34.5004", "StationCode": "1939A", "PositionName": "日报社", "Longitude": "109.5049"}, {"Latitude": "34.4930", "StationCode": "1940A", "PositionName": "体育馆", "Longitude": "109.4636"}, {"Latitude": "34.5021", "StationCode": "1941A", "PositionName": "高新一小", "Longitude": "109.4266"}], "商洛市": [{"Latitude": "33.8715", "StationCode": "2645A", "PositionName": "监测站", "Longitude": "109.9154"}, {"Latitude": "33.8509", "StationCode": "2646A", "PositionName": "东龙山气象局", "Longitude": "109.966"}], "汉中市": [{"Latitude": "33.1842", "StationCode": "2634A", "PositionName": "汉川机床厂子校", "Longitude": "106.9893"}, {"Latitude": "33.0706", "StationCode": "2635A", "PositionName": "市监测站", "Longitude": "107.0154"}, {"Latitude": "33.1138", "StationCode": "2636A", "PositionName": "鑫源开发区", "Longitude": "107.0089"}, {"Latitude": "33.0323", "StationCode": "2637A", "PositionName": "南郑大河坎水厂", "Longitude": "107.007"}], "铜川市": [{"Latitude": "35.0994", "StationCode": "1922A", "PositionName": "党校", "Longitude": "109.0656"}, {"Latitude": "35.0697", "StationCode": "1923A", "PositionName": "王益区政府", "Longitude": "109.0697"}, {"Latitude": "34.9058", "StationCode": "1924A", "PositionName": "新区管委会", "Longitude": "108.9344"}, {"Latitude": "34.8731", "StationCode": "1925A", "PositionName": "新区兰芝公司", "Longitude": "108.9589"}], "西安市": [{"Latitude": "34.2749", "StationCode": "1462A", "PositionName": "高压开关厂", "Longitude": "108.882"}, {"Latitude": "34.2629", "StationCode": "1463A", "PositionName": "兴庆小区", "Longitude": "108.993"}, {"Latitude": "34.2572", "StationCode": "1464A", "PositionName": "纺织城", "Longitude": "109.06"}, {"Latitude": "34.2324", "StationCode": "1465A", "PositionName": "小寨", "Longitude": "108.94"}, {"Latitude": "34.2713", "StationCode": "1466A", "PositionName": "市人民体育场", "Longitude": "108.954"}, {"Latitude": "34.2303", "StationCode": "1467A", "PositionName": "高新西区", "Longitude": "108.883"}, {"Latitude": "34.3474", "StationCode": "1468A", "PositionName": "经开区", "Longitude": "108.935"}, {"Latitude": "34.1546", "StationCode": "1469A", "PositionName": "长安区", "Longitude": "108.906"}, {"Latitude": "34.6575", "StationCode": "1470A", "PositionName": "阎良区", "Longitude": "109.2"}, {"Latitude": "34.3731", "StationCode": "1471A", "PositionName": "临潼区", "Longitude": "109.2186"}, {"Latitude": "34.3780", "StationCode": "1472A", "PositionName": "草滩", "Longitude": "108.8690"}, {"Latitude": "34.1978", "StationCode": "1473A", "PositionName": "曲江文化产业集团", "Longitude": "108.985"}, {"Latitude": "34.3274", "StationCode": "1474A", "PositionName": "广运潭", "Longitude": "109.043"}]}, "20": {"梧州市": [{"Latitude": "23.4792", "StationCode": "2495A", "PositionName": "市环保", "Longitude": "111.2897"}, {"Latitude": "23.475", "StationCode": "2496A", "PositionName": "云盖小学", "Longitude": "111.3178"}, {"Latitude": "23.415", "StationCode": "2497A", "PositionName": "龙圩", "Longitude": "111.2353"}, {"Latitude": "23.4794", "StationCode": "2498A", "PositionName": "龙新", "Longitude": "111.26"}], "钦州市": [{"Latitude": "21.9667", "StationCode": "2502A", "PositionName": "市环保站", "Longitude": "108.6236"}, {"Latitude": "21.9508", "StationCode": "2503A", "PositionName": "市农科院", "Longitude": "108.6553"}, {"Latitude": "21.7431", "StationCode": "2504A", "PositionName": "港区一小", "Longitude": "108.5989"}], "贺州市": [{"Latitude": "24.4175", "StationCode": "2514A", "PositionName": "环保小区", "Longitude": "111.5269"}, {"Latitude": "24.4072", "StationCode": "2515A", "PositionName": "政协大楼", "Longitude": "111.5622"}], "河池市": [{"Latitude": "24.7121", "StationCode": "2516A", "PositionName": "东仁乐园", "Longitude": "108.2134"}, {"Latitude": "24.6928", "StationCode": "2517A", "PositionName": "市环保站", "Longitude": "108.054"}, {"Latitude": "24.6967", "StationCode": "2518A", "PositionName": "市疾控中心", "Longitude": "108.1009"}], "南宁市": [{"Latitude": "22.7875", "StationCode": "1401A", "PositionName": "振宁花园", "Longitude": "108.301"}, {"Latitude": "22.8561", "StationCode": "1402A", "PositionName": "北湖", "Longitude": "108.316"}, {"Latitude": "22.8225", "StationCode": "1403A", "PositionName": "市监测站", "Longitude": "108.321"}, {"Latitude": "22.805", "StationCode": "1404A", "PositionName": "大自然花园", "Longitude": "108.383"}, {"Latitude": "22.7906", "StationCode": "1405A", "PositionName": "仙葫", "Longitude": "108.439"}, {"Latitude": "22.8464", "StationCode": "1406A", "PositionName": "区农职院", "Longitude": "108.239"}, {"Latitude": "22.735", "StationCode": "1407A", "PositionName": "英华嘉园", "Longitude": "108.328"}, {"Latitude": "22.7833", "StationCode": "1408A", "PositionName": "沙井镇街道办", "Longitude": "108.244"}], "贵港市": [{"Latitude": "23.1478", "StationCode": "2505A", "PositionName": "德智高中", "Longitude": "109.5681"}, {"Latitude": "23.0672", "StationCode": "2506A", "PositionName": "江南子站", "Longitude": "109.6042"}, {"Latitude": "23.0944", "StationCode": "2507A", "PositionName": "贵城子站", "Longitude": "109.6014"}, {"Latitude": "23.1036", "StationCode": "2508A", "PositionName": "荷城子站", "Longitude": "109.5683"}], "桂林市": [{"Latitude": "25.3167", "StationCode": "1862A", "PositionName": "电子科大尧山校区", "Longitude": "110.4144"}, {"Latitude": "25.2697", "StationCode": "1863A", "PositionName": "监测站", "Longitude": "110.2819"}, {"Latitude": "25.2708", "StationCode": "1864A", "PositionName": "龙隐路小学", "Longitude": "110.3089"}, {"Latitude": "25.2178", "StationCode": "1865A", "PositionName": "八中", "Longitude": "110.2869"}], "防城港市": [{"Latitude": "21.6158", "StationCode": "2499A", "PositionName": "沙万", "Longitude": "108.3411"}, {"Latitude": "21.7631", "StationCode": "2500A", "PositionName": "防城镇政府", "Longitude": "108.3511"}, {"Latitude": "21.6414", "StationCode": "2501A", "PositionName": "大海花园", "Longitude": "108.3506"}], "柳州市": [{"Latitude": "24.3898", "StationCode": "1870A", "PositionName": "柳东小学", "Longitude": "109.4883"}, {"Latitude": "24.3304", "StationCode": "1871A", "PositionName": "环保监测站", "Longitude": "109.4108"}, {"Latitude": "24.3406", "StationCode": "1872A", "PositionName": "河西水厂", "Longitude": "109.3886"}, {"Latitude": "24.2990", "StationCode": "1873A", "PositionName": "市四中", "Longitude": "109.4221"}, {"Latitude": "24.3663", "StationCode": "1874A", "PositionName": "市九中", "Longitude": "109.3957"}, {"Latitude": "24.3158", "StationCode": "1875A", "PositionName": "古亭山", "Longitude": "109.4839"}], "北海市": [{"Latitude": "21.5958", "StationCode": "1866A", "PositionName": "牛尾岭水库", "Longitude": "109.2256"}, {"Latitude": "21.4086", "StationCode": "1867A", "PositionName": "海滩公园", "Longitude": "109.1436"}, {"Latitude": "21.4661", "StationCode": "1868A", "PositionName": "新市环保局", "Longitude": "109.0981"}, {"Latitude": "21.5233", "StationCode": "1869A", "PositionName": "北海工业园", "Longitude": "109.1778"}], "崇左市": [{"Latitude": "22.4137", "StationCode": "2521A", "PositionName": "市环保局江州分局", "Longitude": "107.3476"}, {"Latitude": "22.3708", "StationCode": "2522A", "PositionName": "城南新区", "Longitude": "107.3701"}], "百色市": [{"Latitude": "23.9011", "StationCode": "2512A", "PositionName": "市监测站", "Longitude": "106.6103"}, {"Latitude": "23.8844", "StationCode": "2513A", "PositionName": "市中心血站", "Longitude": "106.6527"}], "来宾市": [{"Latitude": "23.7208", "StationCode": "2519A", "PositionName": "来宾二中", "Longitude": "109.2131"}, {"Latitude": "23.7369", "StationCode": "2520A", "PositionName": "来冶招待所", "Longitude": "109.2317"}], "玉林市": [{"Latitude": "22.7019", "StationCode": "2509A", "PositionName": "寒山水库", "Longitude": "110.1106"}, {"Latitude": "22.6411", "StationCode": "2510A", "PositionName": "市监测站", "Longitude": "110.1675"}, {"Latitude": "22.6164", "StationCode": "2511A", "PositionName": "南江一中", "Longitude": "110.1433"}]}, "21": {"三亚市": [{"Latitude": "18.2489", "StationCode": "1876A", "PositionName": "河东子站", "Longitude": "109.5078"}, {"Latitude": "18.2681", "StationCode": "1877A", "PositionName": "河西子站", "Longitude": "109.4964"}], "海口市": [{"Latitude": "19.9507", "StationCode": "1409A", "PositionName": "东寨港", "Longitude": "110.576"}, {"Latitude": "20.0574", "StationCode": "1410A", "PositionName": "海南大学", "Longitude": "110.3232"}, {"Latitude": "20.0053", "StationCode": "1411A", "PositionName": "秀英海南医院", "Longitude": "110.283"}, {"Latitude": "19.9969", "StationCode": "1412A", "PositionName": "海南师范大学", "Longitude": "110.338"}, {"Latitude": "20.0356", "StationCode": "1413A", "PositionName": "龙华路环保局宿舍", "Longitude": "110.33"}]}, "22": {"重庆市": [{"Latitude": "29.8272", "StationCode": "1414A", "PositionName": "缙云山", "Longitude": "106.379"}, {"Latitude": "29.8264", "StationCode": "1416A", "PositionName": "天生", "Longitude": "106.424"}, {"Latitude": "29.7228", "StationCode": "1417A", "PositionName": "两路", "Longitude": "106.626"}, {"Latitude": "29.5983", "StationCode": "1418A", "PositionName": "虎溪", "Longitude": "106.296"}, {"Latitude": "29.5186", "StationCode": "1419A", "PositionName": "南坪", "Longitude": "106.54"}, {"Latitude": "29.6219", "StationCode": "1420A", "PositionName": "唐家沱", "Longitude": "106.65"}, {"Latitude": "29.4892", "StationCode": "1421A", "PositionName": "茶园", "Longitude": "106.634"}, {"Latitude": "29.4822", "StationCode": "1422A", "PositionName": "白市驿", "Longitude": "106.364"}, {"Latitude": "29.5642", "StationCode": "1423A", "PositionName": "解放碑", "Longitude": "106.571"}, {"Latitude": "29.7125", "StationCode": "1425A", "PositionName": "空港", "Longitude": "106.617"}, {"Latitude": "29.4892", "StationCode": "1426A", "PositionName": "新山村", "Longitude": "106.468"}, {"Latitude": "29.6453", "StationCode": "1427A", "PositionName": "礼嘉", "Longitude": "106.562"}, {"Latitude": "29.709", "StationCode": "1428A", "PositionName": "蔡家", "Longitude": "106.452"}, {"Latitude": "29.389", "StationCode": "1429A", "PositionName": "鱼新街", "Longitude": "106.513"}, {"Latitude": "29.53675", "StationCode": "3014A", "PositionName": "歇台子", "Longitude": "106.4959"}, {"Latitude": "29.57278", "StationCode": "3015A", "PositionName": "龙井湾", "Longitude": "106.4042"}, {"Latitude": "29.41569", "StationCode": "3016A", "PositionName": "龙洲湾", "Longitude": "106.5506"}]}, "23": {"南充市": [{"Latitude": "30.8064", "StationCode": "1905A", "PositionName": "西山风景区", "Longitude": "106.0560"}, {"Latitude": "30.8023", "StationCode": "1906A", "PositionName": "南充市委", "Longitude": "106.0789"}, {"Latitude": "30.8217", "StationCode": "1907A", "PositionName": "南充炼油厂", "Longitude": "106.1031"}, {"Latitude": "30.7856", "StationCode": "1908A", "PositionName": "高坪区监测站", "Longitude": "106.1064"}, {"Latitude": "30.7636", "StationCode": "1909A", "PositionName": "嘉陵区环保局", "Longitude": "106.0642"}, {"Latitude": "30.8388", "StationCode": "1910A", "PositionName": "市环境监测站", "Longitude": "106.1087"}], "乐山市": [{"Latitude": "29.5467", "StationCode": "2535A", "PositionName": "乐山大佛景区", "Longitude": "103.7705"}, {"Latitude": "29.5844", "StationCode": "2536A", "PositionName": "牛耳桥", "Longitude": "103.7627"}, {"Latitude": "29.6007", "StationCode": "2537A", "PositionName": "市第三水厂", "Longitude": "103.7506"}, {"Latitude": "29.5634", "StationCode": "2538A", "PositionName": "市监测站", "Longitude": "103.757"}], "泸州市": [{"Latitude": "28.9583", "StationCode": "1893A", "PositionName": "九狮山", "Longitude": "105.4306"}, {"Latitude": "28.9026", "StationCode": "1894A", "PositionName": "小市上码头", "Longitude": "105.4436"}, {"Latitude": "28.8558", "StationCode": "1895A", "PositionName": "兰田宪桥", "Longitude": "105.4322"}, {"Latitude": "28.8833", "StationCode": "1896A", "PositionName": "市环监站", "Longitude": "105.4322"}], "绵阳市": [{"Latitude": "31.4747", "StationCode": "1878A", "PositionName": "富乐山", "Longitude": "104.7778"}, {"Latitude": "31.4539", "StationCode": "1879A", "PositionName": "市人大", "Longitude": "104.7536"}, {"Latitude": "31.4656", "StationCode": "1880A", "PositionName": "高新区自来水公司", "Longitude": "104.6717"}, {"Latitude": "31.5072", "StationCode": "1881A", "PositionName": "三水厂", "Longitude": "104.7283"}], "成都市": [{"Latitude": "30.72358333", "StationCode": "1431A", "PositionName": "金泉两河", "Longitude": "103.97275"}, {"Latitude": "30.6872", "StationCode": "1432A", "PositionName": "十里店", "Longitude": "104.176"}, {"Latitude": "30.5706", "StationCode": "1433A", "PositionName": "三瓦窑", "Longitude": "104.079"}, {"Latitude": "30.63", "StationCode": "1434A", "PositionName": "沙河铺", "Longitude": "104.1113889"}, {"Latitude": "30.685", "StationCode": "1435A", "PositionName": "梁家巷", "Longitude": "104.074"}, {"Latitude": "30.6578", "StationCode": "1437A", "PositionName": "君平街", "Longitude": "104.054"}, {"Latitude": "31.0283", "StationCode": "1438A", "PositionName": "灵岩寺", "Longitude": "103.613"}, {"Latitude": "30.65638889", "StationCode": "2880A", "PositionName": "大石西路", "Longitude": "104.0238889"}], "甘孜州": [{"Latitude": "30.0506", "StationCode": "2569A", "PositionName": "将军桥", "Longitude": "101.9628"}, {"Latitude": "30.0475", "StationCode": "2570A", "PositionName": "水桥子", "Longitude": "101.9603"}], "雅安市": [{"Latitude": "30.0125", "StationCode": "2553A", "PositionName": "大兴526台", "Longitude": "103.009"}, {"Latitude": "29.9899", "StationCode": "2554A", "PositionName": "建安厂", "Longitude": "103.0013"}, {"Latitude": "29.9834", "StationCode": "2555A", "PositionName": "市政府", "Longitude": "103.0109"}, {"Latitude": "29.9816", "StationCode": "2556A", "PositionName": "川农大", "Longitude": "103.0001"}], "资阳市": [{"Latitude": "30.1366", "StationCode": "2561A", "PositionName": "莲花山", "Longitude": "104.6617"}, {"Latitude": "30.1506", "StationCode": "2562A", "PositionName": "资阳中学", "Longitude": "104.6356"}, {"Latitude": "30.1377", "StationCode": "2563A", "PositionName": "四三一厂", "Longitude": "104.6289"}, {"Latitude": "30.1142", "StationCode": "2564A", "PositionName": "师范校", "Longitude": "104.6469"}, {"Latitude": "30.1259", "StationCode": "2565A", "PositionName": "区法院", "Longitude": "104.6294"}], "凉山州": [{"Latitude": "27.8094", "StationCode": "2571A", "PositionName": "青龙寺", "Longitude": "102.3419"}, {"Latitude": "27.8408", "StationCode": "2572A", "PositionName": "邛海宾馆", "Longitude": "102.2714"}, {"Latitude": "27.8978", "StationCode": "2573A", "PositionName": "西昌市政府", "Longitude": "102.2625"}, {"Latitude": "27.8847", "StationCode": "2574A", "PositionName": "凉山州政府", "Longitude": "102.2689"}, {"Latitude": "27.8953", "StationCode": "2575A", "PositionName": "长安", "Longitude": "102.2311"}], "达州市": [{"Latitude": "31.2797", "StationCode": "2548A", "PositionName": "达州职业技术学院", "Longitude": "107.5272"}, {"Latitude": "31.215", "StationCode": "2549A", "PositionName": "市环境监测站", "Longitude": "107.525"}, {"Latitude": "31.2108", "StationCode": "2550A", "PositionName": "凤凰小区", "Longitude": "107.4967"}, {"Latitude": "31.1956", "StationCode": "2551A", "PositionName": "达县机关宾馆", "Longitude": "107.5069"}, {"Latitude": "31.2058", "StationCode": "2552A", "PositionName": "市政中心", "Longitude": "107.4611"}], "阿坝州": [{"Latitude": "31.9286", "StationCode": "2566A", "PositionName": "州农科所", "Longitude": "102.1755"}, {"Latitude": "31.9025", "StationCode": "2567A", "PositionName": "州监测站", "Longitude": "102.2218"}, {"Latitude": "31.8934", "StationCode": "2568A", "PositionName": "马师校", "Longitude": "102.2402"}], "内江市": [{"Latitude": "29.5953", "StationCode": "2531A", "PositionName": "市监测站", "Longitude": "105.0331"}, {"Latitude": "29.5947", "StationCode": "2532A", "PositionName": "东兴区政府", "Longitude": "105.0717"}, {"Latitude": "29.5817", "StationCode": "2533A", "PositionName": "内江二中", "Longitude": "105.0653"}, {"Latitude": "29.5822", "StationCode": "2534A", "PositionName": "内江日报社", "Longitude": "105.0406"}], "巴中市": [{"Latitude": "31.8711", "StationCode": "2558A", "PositionName": "市环保局", "Longitude": "106.7389"}, {"Latitude": "31.8531", "StationCode": "2559A", "PositionName": "巴中中学", "Longitude": "106.7594"}, {"Latitude": "31.87888889", "StationCode": "2914A", "PositionName": "苏山坪", "Longitude": "106.7513889"}, {"Latitude": "31.85805556", "StationCode": "2915A", "PositionName": "职业中学", "Longitude": "106.7619444"}], "德阳市": [{"Latitude": "31.1208", "StationCode": "1901A", "PositionName": "东山公园", "Longitude": "104.4219"}, {"Latitude": "31.1333", "StationCode": "1902A", "PositionName": "西小区", "Longitude": "104.3883"}, {"Latitude": "31.1167", "StationCode": "1903A", "PositionName": "市检察院", "Longitude": "104.4053"}, {"Latitude": "31.1108", "StationCode": "1904A", "PositionName": "耐火材料厂", "Longitude": "104.3539"}], "攀枝花市": [{"Latitude": "26.57098", "StationCode": "1888A", "PositionName": "弄弄坪", "Longitude": "101.68912"}, {"Latitude": "26.5928", "StationCode": "1889A", "PositionName": "河门口", "Longitude": "101.5769"}, {"Latitude": "26.5850", "StationCode": "1890A", "PositionName": "炳草岗", "Longitude": "101.7169"}, {"Latitude": "26.5017", "StationCode": "1891A", "PositionName": "仁和", "Longitude": "101.7453"}, {"Latitude": "26.5670", "StationCode": "2835A", "PositionName": "四十中小", "Longitude": "101.7227"}], "宜宾市": [{"Latitude": "28.8194", "StationCode": "1882A", "PositionName": "石马中学", "Longitude": "104.5969"}, {"Latitude": "28.76611", "StationCode": "1883A", "PositionName": "市委", "Longitude": "104.6225"}, {"Latitude": "28.7867", "StationCode": "1884A", "PositionName": "宜宾四中", "Longitude": "104.6061"}, {"Latitude": "28.76389", "StationCode": "1885A", "PositionName": "市政府", "Longitude": "104.6417"}, {"Latitude": "28.71583", "StationCode": "1886A", "PositionName": "黄金嘴", "Longitude": "104.5761"}, {"Latitude": "28.7989", "StationCode": "1887A", "PositionName": "沙坪中学", "Longitude": "104.6789"}], "遂宁市": [{"Latitude": "30.5797", "StationCode": "2527A", "PositionName": "石溪浩", "Longitude": "105.7519"}, {"Latitude": "30.6133", "StationCode": "2528A", "PositionName": "市监测站", "Longitude": "105.68"}, {"Latitude": "30.6347", "StationCode": "2529A", "PositionName": "行政中心", "Longitude": "105.8161"}, {"Latitude": "30.475", "StationCode": "2530A", "PositionName": "美宁食品公司", "Longitude": "105.5956"}], "广元市": [{"Latitude": "32.4535", "StationCode": "2523A", "PositionName": "黑石坡", "Longitude": "105.8945"}, {"Latitude": "32.4429", "StationCode": "2524A", "PositionName": "老城", "Longitude": "105.8242"}, {"Latitude": "32.4246", "StationCode": "2525A", "PositionName": "南坝", "Longitude": "105.8153"}, {"Latitude": "32.4285", "StationCode": "2526A", "PositionName": "监测站", "Longitude": "105.8624"}], "自贡市": [{"Latitude": "29.3628", "StationCode": "1897A", "PositionName": "大塘山", "Longitude": "104.7547"}, {"Latitude": "29.3564", "StationCode": "1899A", "PositionName": "檀木林街", "Longitude": "104.7747"}, {"Latitude": "29.3411", "StationCode": "1900A", "PositionName": "春华路", "Longitude": "104.7692"}, {"Latitude": "29.33972", "StationCode": "3027A", "PositionName": "青杠林路", "Longitude": "104.7228"}], "广安市": [{"Latitude": "30.518", "StationCode": "2543A", "PositionName": "小平旧居", "Longitude": "106.631"}, {"Latitude": "30.4576", "StationCode": "2544A", "PositionName": "市委", "Longitude": "106.6303"}, {"Latitude": "30.4663", "StationCode": "2545A", "PositionName": "友谊中学", "Longitude": "106.6271"}, {"Latitude": "30.4551", "StationCode": "2547A", "PositionName": "广电花园", "Longitude": "106.6388"}, {"Latitude": "30.4865", "StationCode": "2902A", "PositionName": "北辰小学", "Longitude": "106.6351"}], "眉山市": [{"Latitude": "30.0506", "StationCode": "2539A", "PositionName": "蟆颐观", "Longitude": "103.8986"}, {"Latitude": "30.0874", "StationCode": "2540A", "PositionName": "气象局", "Longitude": "103.8416"}, {"Latitude": "30.0691", "StationCode": "2541A", "PositionName": "旭光小区", "Longitude": "103.8495"}, {"Latitude": "30.062", "StationCode": "2542A", "PositionName": "市监测站", "Longitude": "103.8341"}]}, "28": {"甘南州": [{"Latitude": "35.0003", "StationCode": "2669A", "PositionName": "监测站", "Longitude": "102.905"}], "白银市": [{"Latitude": "36.5458", "StationCode": "2647A", "PositionName": "豫源饭店", "Longitude": "104.1731"}, {"Latitude": "36.5481", "StationCode": "2648A", "PositionName": "动力公司", "Longitude": "104.1731"}], "张掖市": [{"Latitude": "38.9467", "StationCode": "2654A", "PositionName": "监测站", "Longitude": "100.4686"}, {"Latitude": "38.9389", "StationCode": "2655A", "PositionName": "科委", "Longitude": "100.4497"}], "临夏州": [{"Latitude": "35.6039", "StationCode": "2667A", "PositionName": "环保局", "Longitude": "103.2139"}, {"Latitude": "35.5997", "StationCode": "2668A", "PositionName": "州委党校", "Longitude": "103.2064"}], "嘉峪关市": [{"Latitude": "39.7711", "StationCode": "1945A", "PositionName": "气象局", "Longitude": "98.2908"}, {"Latitude": "39.79777778", "StationCode": "2884A", "PositionName": "酒钢宾馆", "Longitude": "98.26722222"}], "陇南市": [{"Latitude": "33.3261", "StationCode": "2665A", "PositionName": "汉王镇固水子", "Longitude": "105.0822"}, {"Latitude": "33.38256667", "StationCode": "2885A", "PositionName": "滨江中学", "Longitude": "104.9338889"}], "酒泉市": [{"Latitude": "39.746", "StationCode": "2658A", "PositionName": "仓门街子站", "Longitude": "98.509"}, {"Latitude": "39.7294", "StationCode": "2659A", "PositionName": "富康家世界子站", "Longitude": "98.5023"}], "兰州市": [{"Latitude": "36.0756", "StationCode": "1475A", "PositionName": "职工医院", "Longitude": "103.712"}, {"Latitude": "36.1031", "StationCode": "1476A", "PositionName": "兰炼宾馆", "Longitude": "103.631"}, {"Latitude": "35.940", "StationCode": "1477A", "PositionName": "榆中兰大校区", "Longitude": "104.148"}, {"Latitude": "36.0725", "StationCode": "1478A", "PositionName": "生物制品所", "Longitude": "103.841"}, {"Latitude": "36.0464", "StationCode": "1479A", "PositionName": "铁路设计院", "Longitude": "103.831"}], "天水市": [{"Latitude": "34.3469", "StationCode": "2649A", "PositionName": "仙人崖", "Longitude": "106.005"}, {"Latitude": "34.5814", "StationCode": "2650A", "PositionName": "进步巷", "Longitude": "105.7281"}, {"Latitude": "34.5653", "StationCode": "2651A", "PositionName": "文化馆", "Longitude": "105.8614"}], "庆阳市": [{"Latitude": "35.7289", "StationCode": "2660A", "PositionName": "区环保局", "Longitude": "107.6831"}, {"Latitude": "35.5236", "StationCode": "2661A", "PositionName": "粮贸总公司", "Longitude": "107.6406"}, {"Latitude": "35.7067", "StationCode": "2662A", "PositionName": "市环保局", "Longitude": "107.6364"}], "平凉市": [{"Latitude": "35.5461", "StationCode": "2656A", "PositionName": "监测站", "Longitude": "106.6692"}, {"Latitude": "35.5294", "StationCode": "2657A", "PositionName": "博物馆", "Longitude": "106.7039"}], "定西市": [{"Latitude": "35.5714", "StationCode": "2663A", "PositionName": "监测站(原粮食局)", "Longitude": "104.6228"}, {"Latitude": "35.5975", "StationCode": "2664A", "PositionName": "南峰招待所(原起重机厂)", "Longitude": "104.6169"}], "武威市": [{"Latitude": "37.9311", "StationCode": "2652A", "PositionName": "监测站", "Longitude": "102.6219"}, {"Latitude": "37.9358", "StationCode": "2653A", "PositionName": "雷台", "Longitude": "102.6469"}], "金昌市": [{"Latitude": "38.5247", "StationCode": "1942A", "PositionName": "市科委", "Longitude": "102.1878"}, {"Latitude": "38.5339", "StationCode": "1943A", "PositionName": "新川苑", "Longitude": "102.1725"}, {"Latitude": "38.5061", "StationCode": "1944A", "PositionName": "公司二招", "Longitude": "102.1708"}]}, "29": {"海北州": [{"Latitude": "36.9639", "StationCode": "2671A", "PositionName": "海晏县西海镇", "Longitude": "100.9048"}], "海南州": [{"Latitude": "36.2866", "StationCode": "2673A", "PositionName": "共和县恰卜恰镇", "Longitude": "100.6188"}], "黄南州": [{"Latitude": "35.5102", "StationCode": "2672A", "PositionName": "同仁县隆务镇", "Longitude": "102.0199"}], "海东地区": [{"Latitude": "36.4997", "StationCode": "2670A", "PositionName": "平安县", "Longitude": "102.1086"}], "果洛州": [{"Latitude": "34.4714", "StationCode": "2674A", "PositionName": "玛沁县大武镇", "Longitude": "100.2561"}], "玉树州": [{"Latitude": "33.0014", "StationCode": "2675A", "PositionName": "玉树县结古镇", "Longitude": "97"}], "西宁市": [{"Latitude": "36.6428", "StationCode": "1480A", "PositionName": "市环境监测站", "Longitude": "101.748"}, {"Latitude": "36.6922", "StationCode": "1481A", "PositionName": "省医药仓库", "Longitude": "101.749"}, {"Latitude": "36.5819", "StationCode": "1482A", "PositionName": "四陆医院", "Longitude": "101.834"}, {"Latitude": "36.6867", "StationCode": "1483A", "PositionName": "第五水厂", "Longitude": "101.524"}], "海西州": [{"Latitude": "37.3753", "StationCode": "2676A", "PositionName": "德令哈市", "Longitude": "97.3731"}]}, "1": {"北京市": [{"Latitude": "39.8673", "StationCode": "1001A", "PositionName": "万寿西宫", "Longitude": "116.366"}, {"Latitude": "40.2865", "StationCode": "1002A", "PositionName": "定陵", "Longitude": "116.17"}, {"Latitude": "39.9522", "StationCode": "1003A", "PositionName": "东四", "Longitude": "116.434"}, {"Latitude": "39.8745", "StationCode": "1004A", "PositionName": "天坛", "Longitude": "116.434"}, {"Latitude": "39.9716", "StationCode": "1005A", "PositionName": "农展馆", "Longitude": "116.473"}, {"Latitude": "39.9425", "StationCode": "1006A", "PositionName": "官园", "Longitude": "116.361"}, {"Latitude": "39.9934", "StationCode": "1007A", "PositionName": "海淀区万柳", "Longitude": "116.315"}, {"Latitude": "40.1438", "StationCode": "1008A", "PositionName": "顺义新城", "Longitude": "116.72"}, {"Latitude": "40.3937", "StationCode": "1009A", "PositionName": "怀柔镇", "Longitude": "116.644"}, {"Latitude": "40.1952", "StationCode": "1010A", "PositionName": "昌平镇", "Longitude": "116.23"}, {"Latitude": "40.0031", "StationCode": "1011A", "PositionName": "奥体中心", "Longitude": "116.407"}, {"Latitude": "39.9279", "StationCode": "1012A", "PositionName": "古城", "Longitude": "116.225"}]}, "3": {"沧州市": [{"Latitude": "38.2991", "StationCode": "1071A", "PositionName": "沧县城建局", "Longitude": "116.8854"}, {"Latitude": "38.3254", "StationCode": "1072A", "PositionName": "电视转播站", "Longitude": "116.8584"}, {"Latitude": "38.3228", "StationCode": "1073A", "PositionName": "市环保局", "Longitude": "116.8709"}], "唐山市": [{"Latitude": "39.6308", "StationCode": "1036A", "PositionName": "供销社", "Longitude": "118.1662"}, {"Latitude": "39.6430", "StationCode": "1037A", "PositionName": "雷达站", "Longitude": "118.1440"}, {"Latitude": "39.6407", "StationCode": "1038A", "PositionName": "物资局", "Longitude": "118.1853"}, {"Latitude": "39.6679", "StationCode": "1039A", "PositionName": "陶瓷公司", "Longitude": "118.2185"}, {"Latitude": "39.65782", "StationCode": "1040A", "PositionName": "十二中", "Longitude": "118.1838"}, {"Latitude": "39.6295", "StationCode": "1041A", "PositionName": "小山", "Longitude": "118.1997"}], "邢台市": [{"Latitude": "37.0967", "StationCode": "1077A", "PositionName": "达活泉", "Longitude": "114.4821"}, {"Latitude": "37.0533", "StationCode": "1078A", "PositionName": "邢师高专", "Longitude": "114.5261"}, {"Latitude": "37.0964", "StationCode": "1079A", "PositionName": "路桥公司", "Longitude": "114.5331"}, {"Latitude": "37.0620", "StationCode": "1080A", "PositionName": "市环保局", "Longitude": "114.4854"}], "衡水市": [{"Latitude": "37.7575", "StationCode": "1074A", "PositionName": "电机北厂", "Longitude": "115.6951"}, {"Latitude": "37.7379", "StationCode": "1075A", "PositionName": "市监测站", "Longitude": "115.6426"}, {"Latitude": "37.7390", "StationCode": "1076A", "PositionName": "市环保局", "Longitude": "115.6906"}], "张家口市": [{"Latitude": "40.8367", "StationCode": "1057A", "PositionName": "人民公园", "Longitude": "114.8985"}, {"Latitude": "40.79481", "StationCode": "1058A", "PositionName": "探机厂", "Longitude": "114.892"}, {"Latitude": "40.8115", "StationCode": "1059A", "PositionName": "五金库", "Longitude": "114.8814"}, {"Latitude": "40.7688", "StationCode": "1060A", "PositionName": "世纪豪园", "Longitude": "114.9032"}, {"Latitude": "40.8725", "StationCode": "1061A", "PositionName": "北泵房", "Longitude": "114.9040"}], "保定市": [{"Latitude": "38.8632", "StationCode": "1051A", "PositionName": "游泳馆", "Longitude": "115.4930"}, {"Latitude": "38.8957", "StationCode": "1052A", "PositionName": "华电二区", "Longitude": "115.5223"}, {"Latitude": "38.9108", "StationCode": "1053A", "PositionName": "接待中心", "Longitude": "115.4713"}, {"Latitude": "38.8416", "StationCode": "1054A", "PositionName": "地表水厂", "Longitude": "115.4612"}, {"Latitude": "38.8756", "StationCode": "1055A", "PositionName": "胶片厂", "Longitude": "115.4420"}, {"Latitude": "38.8707", "StationCode": "1056A", "PositionName": "监测站", "Longitude": "115.5214"}], "秦皇岛市": [{"Latitude": "39.8283", "StationCode": "1042A", "PositionName": "北戴河环保局", "Longitude": "119.5259"}, {"Latitude": "40.0181", "StationCode": "1043A", "PositionName": "第一关", "Longitude": "119.7624"}, {"Latitude": "39.9567", "StationCode": "1044A", "PositionName": "监测站", "Longitude": "119.6023"}, {"Latitude": "39.9358", "StationCode": "1045A", "PositionName": "市政府", "Longitude": "119.6070"}, {"Latitude": "39.9419", "StationCode": "1046A", "PositionName": "建设大厦", "Longitude": "119.5369"}], "廊坊市": [{"Latitude": "39.5178", "StationCode": "1067A", "PositionName": "药材公司", "Longitude": "116.6838"}, {"Latitude": "39.5747", "StationCode": "1068A", "PositionName": "开发区", "Longitude": "116.7729"}, {"Latitude": "39.5343", "StationCode": "1070A", "PositionName": "北华航天学院", "Longitude": "116.7464"}, {"Latitude": "39.5453", "StationCode": "2919A", "PositionName": "河北工业大学", "Longitude": "116.7022"}], "石家庄市": [{"Latitude": "38.0513", "StationCode": "1029A", "PositionName": "职工医院", "Longitude": "114.4548"}, {"Latitude": "38.0398", "StationCode": "1030A", "PositionName": "高新区", "Longitude": "114.6046"}, {"Latitude": "38.1398", "StationCode": "1031A", "PositionName": "西北水源", "Longitude": "114.5019"}, {"Latitude": "38.00583333", "StationCode": "1032A", "PositionName": "西南高教", "Longitude": "114.4586111"}, {"Latitude": "38.01777778", "StationCode": "1033A", "PositionName": "世纪公园", "Longitude": "114.5330556"}, {"Latitude": "38.0524", "StationCode": "1034A", "PositionName": "人民会堂", "Longitude": "114.5214"}, {"Latitude": "37.9097", "StationCode": "1035A", "PositionName": "封龙山", "Longitude": "114.3541"}, {"Latitude": "38.03777778", "StationCode": "2862A", "PositionName": "22中南校区", "Longitude": "114.5480556"}], "邯郸市": [{"Latitude": "36.61763", "StationCode": "1047A", "PositionName": "环保局", "Longitude": "114.5129"}, {"Latitude": "36.6164", "StationCode": "1048A", "PositionName": "东污水处理厂", "Longitude": "114.5426"}, {"Latitude": "36.5776", "StationCode": "1049A", "PositionName": "矿院", "Longitude": "114.5035"}, {"Latitude": "36.61981", "StationCode": "1050A", "PositionName": "丛台公园", "Longitude": "114.4965"}], "承德市": [{"Latitude": "40.9161", "StationCode": "1062A", "PositionName": "铁路", "Longitude": "117.9664"}, {"Latitude": "40.9843", "StationCode": "1063A", "PositionName": "中国银行", "Longitude": "117.9525"}, {"Latitude": "40.9359", "StationCode": "1064A", "PositionName": "开发区", "Longitude": "117.9630"}, {"Latitude": "40.9733", "StationCode": "1065A", "PositionName": "文化中心", "Longitude": "117.8184"}, {"Latitude": "41.0112", "StationCode": "1066A", "PositionName": "离宫", "Longitude": "117.9384"}]}, "2": {"天津市": [{"Latitude": "39.1654", "StationCode": "1015A", "PositionName": "勤俭路", "Longitude": "117.145"}, {"Latitude": "39.1082", "StationCode": "1017A", "PositionName": "大直沽八号路", "Longitude": "117.237"}, {"Latitude": "39.0927", "StationCode": "1018A", "PositionName": "前进路", "Longitude": "117.202"}, {"Latitude": "39.2133", "StationCode": "1019A", "PositionName": "北辰科技园区", "Longitude": "117.1837"}, {"Latitude": "39.0877", "StationCode": "1021A", "PositionName": "跃进路", "Longitude": "117.307"}, {"Latitude": "39.0343", "StationCode": "1023A", "PositionName": "第四大街", "Longitude": "117.707"}, {"Latitude": "38.8394", "StationCode": "1024A", "PositionName": "永明路", "Longitude": "117.457"}, {"Latitude": "39.124", "StationCode": "1025A", "PositionName": "航天路", "Longitude": "117.401"}, {"Latitude": "39.1587", "StationCode": "1026A", "PositionName": "汉北路", "Longitude": "117.764"}, {"Latitude": "38.9194", "StationCode": "1027A", "PositionName": "团泊洼", "Longitude": "117.157"}, {"Latitude": "39.2474", "StationCode": "2858A", "PositionName": "河西一经路", "Longitude": "117.7918"}, {"Latitude": "38.9846", "StationCode": "2859A", "PositionName": "津沽路", "Longitude": "117.3747"}, {"Latitude": "39.0845", "StationCode": "2860A", "PositionName": "宾水西道", "Longitude": "117.1589"}, {"Latitude": "39.1067", "StationCode": "2922A", "PositionName": "大理道", "Longitude": "117.1941"}, {"Latitude": "39.16969", "StationCode": "3020A", "PositionName": "中山北路", "Longitude": "117.2099"}]}, "5": {"兴安盟": [{"Latitude": "46.0872", "StationCode": "2199A", "PositionName": "盟监测站", "Longitude": "122.062"}, {"Latitude": "46.0703", "StationCode": "2200A", "PositionName": "胜华新制药厂", "Longitude": "122.0506"}, {"Latitude": "46.0756", "StationCode": "2201A", "PositionName": "科右前旗环保局", "Longitude": "121.9462"}], "鄂尔多斯市": [{"Latitude": "39.8129", "StationCode": "1591A", "PositionName": "综合楼", "Longitude": "110.0023"}, {"Latitude": "39.8261", "StationCode": "1592A", "PositionName": "巴音孟克林场办事处", "Longitude": "109.9486"}, {"Latitude": "39.5986", "StationCode": "1593A", "PositionName": "康泽苑", "Longitude": "109.7736"}, {"Latitude": "39.5989", "StationCode": "1594A", "PositionName": "华泰汽车城", "Longitude": "109.8119"}, {"Latitude": "39.7884", "StationCode": "1595A", "PositionName": "奥林花园", "Longitude": "109.9734"}], "呼和浩特市": [{"Latitude": "40.7579", "StationCode": "1090A", "PositionName": "呼市一监", "Longitude": "111.651"}, {"Latitude": "40.8033", "StationCode": "1091A", "PositionName": "小召", "Longitude": "111.658"}, {"Latitude": "40.8452", "StationCode": "1092A", "PositionName": "兴松小区", "Longitude": "111.659"}, {"Latitude": "40.8144", "StationCode": "1093A", "PositionName": "糖厂", "Longitude": "111.608"}, {"Latitude": "40.8369", "StationCode": "1094A", "PositionName": "如意水处理厂", "Longitude": "111.751"}, {"Latitude": "40.8062", "StationCode": "1095A", "PositionName": "二十九中", "Longitude": "111.7277"}, {"Latitude": "40.7866", "StationCode": "1096A", "PositionName": "工大金川校区", "Longitude": "111.551"}, {"Latitude": "40.7612", "StationCode": "1097A", "PositionName": "化肥厂生活区", "Longitude": "111.717"}], "锡林郭勒盟": [{"Latitude": "43.9317", "StationCode": "2202A", "PositionName": "市环保监测站", "Longitude": "116.1042"}, {"Latitude": "43.9311", "StationCode": "2203A", "PositionName": "市政府", "Longitude": "116.0781"}], "包头市": [{"Latitude": "40.6532", "StationCode": "1585A", "PositionName": "市环境监测站", "Longitude": "109.8756"}, {"Latitude": "40.6575", "StationCode": "1586A", "PositionName": "包百大楼", "Longitude": "109.8104"}, {"Latitude": "40.5905", "StationCode": "1587A", "PositionName": "东河城环局", "Longitude": "110.0067"}, {"Latitude": "40.6821", "StationCode": "1588A", "PositionName": "青山宾馆", "Longitude": "109.8538"}, {"Latitude": "40.6288", "StationCode": "1589A", "PositionName": "惠龙物流", "Longitude": "109.8654"}, {"Latitude": "40.5546", "StationCode": "1590A", "PositionName": "东河鸿龙湾", "Longitude": "110.0377"}], "通辽市": [{"Latitude": "43.6267", "StationCode": "2189A", "PositionName": "通辽宾馆", "Longitude": "122.2603"}, {"Latitude": "43.6156", "StationCode": "2190A", "PositionName": "胶建铝业", "Longitude": "122.3039"}, {"Latitude": "43.6801", "StationCode": "2191A", "PositionName": "艺术职业学校", "Longitude": "122.2532"}], "巴彦淖尔市": [{"Latitude": "40.916", "StationCode": "2194A", "PositionName": "秋林养殖基地", "Longitude": "107.5936"}, {"Latitude": "40.7608", "StationCode": "2195A", "PositionName": "附中", "Longitude": "107.4211"}, {"Latitude": "40.7378", "StationCode": "2196A", "PositionName": "市环保大楼", "Longitude": "107.3715"}], "赤峰市": [{"Latitude": "42.2814", "StationCode": "1744A", "PositionName": "松山一中", "Longitude": "118.9233"}, {"Latitude": "42.2725", "StationCode": "1745A", "PositionName": "哈达街", "Longitude": "118.9572"}, {"Latitude": "42.2556", "StationCode": "1746A", "PositionName": "天义路", "Longitude": "118.8789"}, {"Latitude": "42.0317", "StationCode": "1747A", "PositionName": "松山路", "Longitude": "119.2719"}], "乌兰察布市": [{"Latitude": "40.9923", "StationCode": "2197A", "PositionName": "集宁新区", "Longitude": "113.1306"}, {"Latitude": "41.038", "StationCode": "2198A", "PositionName": "集宁旧区西", "Longitude": "113.0974"}], "乌海市": [{"Latitude": "39.6719", "StationCode": "2186A", "PositionName": "聚英学校", "Longitude": "106.8219"}, {"Latitude": "39.6969", "StationCode": "2187A", "PositionName": "市林业局", "Longitude": "106.8089"}, {"Latitude": "39.6572", "StationCode": "2188A", "PositionName": "中海勃湾学校", "Longitude": "106.7931"}], "呼伦贝尔市": [{"Latitude": "49.2261", "StationCode": "2192A", "PositionName": "区环保局", "Longitude": "119.7594"}, {"Latitude": "49.2014", "StationCode": "2193A", "PositionName": "市艺校", "Longitude": "119.7283"}], "阿拉善盟": [{"Latitude": "38.8343", "StationCode": "2204A", "PositionName": "体育场", "Longitude": "105.6775"}, {"Latitude": "38.843", "StationCode": "2205A", "PositionName": "盟环保楼", "Longitude": "105.6975"}, {"Latitude": "38.8516", "StationCode": "2206A", "PositionName": "环保局新楼", "Longitude": "105.724"}]}, "4": {"太原市": [{"Latitude": "37.8873", "StationCode": "1081A", "PositionName": "尖草坪", "Longitude": "112.522"}, {"Latitude": "37.9103", "StationCode": "1082A", "PositionName": "涧河", "Longitude": "112.573"}, {"Latitude": "38.0108", "StationCode": "1083A", "PositionName": "上兰", "Longitude": "112.434"}, {"Latitude": "37.7124", "StationCode": "1084A", "PositionName": "晋源", "Longitude": "112.469"}, {"Latitude": "37.7394", "StationCode": "1085A", "PositionName": "小店", "Longitude": "112.5583"}, {"Latitude": "37.8692", "StationCode": "1086A", "PositionName": "桃园", "Longitude": "112.5369"}, {"Latitude": "37.8195", "StationCode": "1087A", "PositionName": "坞城", "Longitude": "112.57"}, {"Latitude": "37.9854", "StationCode": "1088A", "PositionName": "南寨", "Longitude": "112.549"}, {"Latitude": "37.7805", "StationCode": "1089A", "PositionName": "金胜", "Longitude": "112.488"}], "吕梁市": [{"Latitude": "37.5211", "StationCode": "2183A", "PositionName": "环保局", "Longitude": "111.1406"}, {"Latitude": "37.5136", "StationCode": "2185A", "PositionName": "自来水公司", "Longitude": "111.1297"}, {"Latitude": "37.51", "StationCode": "2867A", "PositionName": "马茂庄小学", "Longitude": "111.1283333"}], "晋中市": [{"Latitude": "37.7019", "StationCode": "2171A", "PositionName": "锦纶小区", "Longitude": "112.7549"}, {"Latitude": "37.7111", "StationCode": "2173A", "PositionName": "南都小区", "Longitude": "112.7306"}, {"Latitude": "37.7087", "StationCode": "2174A", "PositionName": "榆次区政府", "Longitude": "112.7105"}, {"Latitude": "37.68277778", "StationCode": "2865A", "PositionName": "榆次三中", "Longitude": "112.7194444"}], "朔州市": [{"Latitude": "39.3514", "StationCode": "2166A", "PositionName": "平朔", "Longitude": "112.44"}, {"Latitude": "39.3606", "StationCode": "2167A", "PositionName": "朔唯", "Longitude": "112.4549"}, {"Latitude": "39.3179", "StationCode": "2168A", "PositionName": "区政府", "Longitude": "112.4254"}, {"Latitude": "39.3265", "StationCode": "2169A", "PositionName": "市环保局", "Longitude": "112.4078"}, {"Latitude": "39.3673", "StationCode": "2170A", "PositionName": "市二中", "Longitude": "112.4279"}], "忻州市": [{"Latitude": "38.4186", "StationCode": "2180A", "PositionName": "机引", "Longitude": "112.7356"}, {"Latitude": "38.4519", "StationCode": "2181A", "PositionName": "开发区", "Longitude": "112.7383"}, {"Latitude": "38.4928", "StationCode": "2182A", "PositionName": "会展中心", "Longitude": "112.7003"}], "大同市": [{"Latitude": "40.1097", "StationCode": "1721A", "PositionName": "果树场", "Longitude": "113.3819"}, {"Latitude": "40.0758", "StationCode": "1723A", "PositionName": "云冈宾馆", "Longitude": "113.2994"}, {"Latitude": "40.0917", "StationCode": "1724A", "PositionName": "大同大学", "Longitude": "113.3444"}, {"Latitude": "40.1269", "StationCode": "1725A", "PositionName": "安家小村", "Longitude": "113.2661"}, {"Latitude": "40.0844", "StationCode": "1726A", "PositionName": "教育学院", "Longitude": "113.2711"}, {"Latitude": "40.1114", "StationCode": "2923A", "PositionName": "供排水公司", "Longitude": "113.2803"}], "临汾市": [{"Latitude": "36.0783", "StationCode": "1733A", "PositionName": "临钢医院", "Longitude": "111.5531"}, {"Latitude": "36.0714", "StationCode": "1734A", "PositionName": "技工学校", "Longitude": "111.5028"}, {"Latitude": "36.0822", "StationCode": "1735A", "PositionName": "工商学校", "Longitude": "111.5169"}, {"Latitude": "36.0875", "StationCode": "1736A", "PositionName": "市委", "Longitude": "111.5025"}, {"Latitude": "36.0417", "StationCode": "1737A", "PositionName": "南机场", "Longitude": "111.4917"}, {"Latitude": "36.10139", "StationCode": "3018A", "PositionName": "唐尧大酒店", "Longitude": "111.505"}], "晋城市": [{"Latitude": "35.5051", "StationCode": "2160A", "PositionName": "自来水公司", "Longitude": "112.85"}, {"Latitude": "35.4934", "StationCode": "2161A", "PositionName": "白云商贸", "Longitude": "112.835"}, {"Latitude": "35.4883", "StationCode": "2162A", "PositionName": "市环保局", "Longitude": "112.8564"}, {"Latitude": "35.4894", "StationCode": "2163A", "PositionName": "技术学院", "Longitude": "112.8664"}, {"Latitude": "35.4813", "StationCode": "2164A", "PositionName": "泽州一中", "Longitude": "112.8252"}, {"Latitude": "35.546", "StationCode": "2165A", "PositionName": "白马寺", "Longitude": "112.8453"}], "阳泉市": [{"Latitude": "37.8564", "StationCode": "1738A", "PositionName": "市中心", "Longitude": "113.5753"}, {"Latitude": "37.8792", "StationCode": "1739A", "PositionName": "赛鱼", "Longitude": "113.4922"}, {"Latitude": "37.8561", "StationCode": "1740A", "PositionName": "南庄", "Longitude": "113.5922"}, {"Latitude": "37.8531", "StationCode": "1741A", "PositionName": "白羊墅", "Longitude": "113.6292"}, {"Latitude": "37.8694", "StationCode": "1742A", "PositionName": "平坦", "Longitude": "113.5689"}, {"Latitude": "37.8500", "StationCode": "1743A", "PositionName": "大阳泉", "Longitude": "113.5158"}], "长治市": [{"Latitude": "36.1542", "StationCode": "1727A", "PositionName": "清华站", "Longitude": "113.1097"}, {"Latitude": "36.1939", "StationCode": "1728A", "PositionName": "监测站", "Longitude": "113.0972"}, {"Latitude": "36.2126", "StationCode": "1730A", "PositionName": "审计局", "Longitude": "113.0886"}, {"Latitude": "36.1855", "StationCode": "1731A", "PositionName": "长治八中", "Longitude": "113.0844444"}, {"Latitude": "36.1912", "StationCode": "2845A", "PositionName": "德盛苑", "Longitude": "113.1569"}], "运城市": [{"Latitude": "35.0147", "StationCode": "2175A", "PositionName": "运城中学", "Longitude": "110.9956"}, {"Latitude": "35.0611", "StationCode": "2176A", "PositionName": "禹都开发区", "Longitude": "111.0233"}, {"Latitude": "35.0308", "StationCode": "2178A", "PositionName": "地区技校", "Longitude": "110.9678"}, {"Latitude": "35.1147", "StationCode": "2179A", "PositionName": "空港新区", "Longitude": "111.0414"}, {"Latitude": "35.04388889", "StationCode": "2866A", "PositionName": "外滩首府", "Longitude": "111.0522222"}]}, "7": {"吉林市": [{"Latitude": "43.8875", "StationCode": "1772A", "PositionName": "哈达湾", "Longitude": "126.5550"}, {"Latitude": "43.8358", "StationCode": "1773A", "PositionName": "东局子", "Longitude": "126.5844"}, {"Latitude": "43.8228", "StationCode": "1774A", "PositionName": "电力学院", "Longitude": "126.4978"}, {"Latitude": "43.8947", "StationCode": "1775A", "PositionName": "江北", "Longitude": "126.5786"}, {"Latitude": "43.8256", "StationCode": "1776A", "PositionName": "江南公园", "Longitude": "126.5500"}, {"Latitude": "43.7256", "StationCode": "1778A", "PositionName": "丰满", "Longitude": "126.6772"}, {"Latitude": "43.95305556", "StationCode": "2868A", "PositionName": "九站", "Longitude": "126.4738889"}], "四平市": [{"Latitude": "43.1747", "StationCode": "2224A", "PositionName": "监测站", "Longitude": "124.3419"}, {"Latitude": "43.1594", "StationCode": "2225A", "PositionName": "一商场", "Longitude": "124.3711"}, {"Latitude": "43.1847", "StationCode": "2226A", "PositionName": "境园", "Longitude": "124.3897"}], "通化市": [{"Latitude": "41.7156", "StationCode": "2229A", "PositionName": "光明", "Longitude": "125.9361"}, {"Latitude": "41.7381", "StationCode": "2230A", "PositionName": "铁路", "Longitude": "125.9486"}], "白城市": [{"Latitude": "45.6289", "StationCode": "2235A", "PositionName": "洮北区环保局", "Longitude": "122.8444"}, {"Latitude": "45.6175", "StationCode": "2236A", "PositionName": "市环保局", "Longitude": "122.8211"}], "延边州": [{"Latitude": "42.8939", "StationCode": "2237A", "PositionName": "妇幼医院", "Longitude": "129.4892"}, {"Latitude": "42.9061", "StationCode": "2238A", "PositionName": "延边医院", "Longitude": "129.5042"}, {"Latitude": "42.8775", "StationCode": "2239A", "PositionName": "朝阳川镇医院", "Longitude": "129.3675"}], "松原市": [{"Latitude": "45.0878", "StationCode": "2233A", "PositionName": "江南", "Longitude": "124.8292"}, {"Latitude": "45.1642", "StationCode": "2234A", "PositionName": "江北", "Longitude": "124.8528"}], "白山市": [{"Latitude": "41.9206", "StationCode": "2231A", "PositionName": "喜丰", "Longitude": "126.4047"}, {"Latitude": "41.9419", "StationCode": "2232A", "PositionName": "环保局", "Longitude": "126.4078"}], "辽源市": [{"Latitude": "42.8947", "StationCode": "2227A", "PositionName": "环保局", "Longitude": "125.1358"}, {"Latitude": "42.8953", "StationCode": "2228A", "PositionName": "污水处理厂", "Longitude": "125.1567"}], "长春市": [{"Latitude": "43.9167", "StationCode": "1119A", "PositionName": "食品厂", "Longitude": "125.323"}, {"Latitude": "43.91", "StationCode": "1120A", "PositionName": "客车厂", "Longitude": "125.287"}, {"Latitude": "43.8400", "StationCode": "1121A", "PositionName": "邮电学院", "Longitude": "125.2786"}, {"Latitude": "43.8748", "StationCode": "1122A", "PositionName": "劳动公园", "Longitude": "125.3649"}, {"Latitude": "43.8694", "StationCode": "1123A", "PositionName": "园林处", "Longitude": "125.325"}, {"Latitude": "43.7878", "StationCode": "1124A", "PositionName": "净月潭", "Longitude": "125.454"}, {"Latitude": "43.55", "StationCode": "1125A", "PositionName": "甩湾子", "Longitude": "125.633"}, {"Latitude": "43.8667", "StationCode": "1126A", "PositionName": "经开区环卫处", "Longitude": "125.417"}, {"Latitude": "43.8167", "StationCode": "1127A", "PositionName": "高新区管委会", "Longitude": "125.25"}, {"Latitude": "43.85", "StationCode": "1128A", "PositionName": "岱山公园", "Longitude": "125.217"}]}, "6": {"沈阳市": [{"Latitude": "41.9339", "StationCode": "1098A", "PositionName": "森林路", "Longitude": "123.6836"}, {"Latitude": "41.7561", "StationCode": "1099A", "PositionName": "浑南东路", "Longitude": "123.535"}, {"Latitude": "41.7089", "StationCode": "1100A", "PositionName": "新秀街", "Longitude": "123.439"}, {"Latitude": "41.8336", "StationCode": "1102A", "PositionName": "东陵路", "Longitude": "123.542"}, {"Latitude": "41.8472", "StationCode": "1103A", "PositionName": "陵东街", "Longitude": "123.428"}, {"Latitude": "41.765", "StationCode": "1104A", "PositionName": "文化路", "Longitude": "123.41"}, {"Latitude": "41.7775", "StationCode": "1105A", "PositionName": "小河沿", "Longitude": "123.478"}, {"Latitude": "41.7972", "StationCode": "1106A", "PositionName": "太原街", "Longitude": "123.3997"}, {"Latitude": "41.9228", "StationCode": "1108A", "PositionName": "京沈街", "Longitude": "123.3783"}, {"Latitude": "41.7347", "StationCode": "2897A", "PositionName": "沈辽西路", "Longitude": "123.2444"}, {"Latitude": "41.9086", "StationCode": "2900A", "PositionName": "裕农路", "Longitude": "123.5953"}], "大连市": [{"Latitude": "38.973888889", "StationCode": "1109A", "PositionName": "甘井子", "Longitude": "121.61194444"}, {"Latitude": "38.951111111", "StationCode": "1110A", "PositionName": "周水子", "Longitude": "121.565"}, {"Latitude": "38.885", "StationCode": "1111A", "PositionName": "星海三站", "Longitude": "121.56388889"}, {"Latitude": "38.911944444", "StationCode": "1112A", "PositionName": "青泥洼桥", "Longitude": "121.63305556"}, {"Latitude": "38.863888889", "StationCode": "1113A", "PositionName": "傅家庄", "Longitude": "121.625"}, {"Latitude": "38.856111111", "StationCode": "1114A", "PositionName": "七贤岭", "Longitude": "121.51805556"}, {"Latitude": "38.808055556", "StationCode": "1115A", "PositionName": "旅顺", "Longitude": "121.25888889"}, {"Latitude": "39.1311", "StationCode": "1116A", "PositionName": "金州", "Longitude": "121.7481"}, {"Latitude": "39.0511", "StationCode": "1117A", "PositionName": "开发区", "Longitude": "121.7769"}, {"Latitude": "39.0631", "StationCode": "1118A", "PositionName": "双D港", "Longitude": "121.9769"}], "鞍山市": [{"Latitude": "41.1196", "StationCode": "1748A", "PositionName": "深沟寺", "Longitude": "123.0440"}, {"Latitude": "41.0931", "StationCode": "1749A", "PositionName": "太阳城", "Longitude": "123.0110"}, {"Latitude": "41.1442", "StationCode": "1750A", "PositionName": "太平", "Longitude": "123.0485"}, {"Latitude": "41.0971", "StationCode": "1751A", "PositionName": "铁西三道街", "Longitude": "122.9642"}, {"Latitude": "41.0833", "StationCode": "1752A", "PositionName": "铁西工业园区", "Longitude": "122.9481"}, {"Latitude": "41.0831", "StationCode": "1753A", "PositionName": "明达新区", "Longitude": "123.0156"}, {"Latitude": "41.0228", "StationCode": "1754A", "PositionName": "千山", "Longitude": "123.1289"}], "丹东市": [{"Latitude": "40.0625", "StationCode": "1600A", "PositionName": "江湾东路", "Longitude": "124.3303"}, {"Latitude": "40.1503", "StationCode": "1601A", "PositionName": "临江后街", "Longitude": "124.4256"}, {"Latitude": "40.1461", "StationCode": "1602A", "PositionName": "元宝山", "Longitude": "124.3933"}, {"Latitude": "40.1194", "StationCode": "1603A", "PositionName": "民主桥", "Longitude": "124.3678"}], "锦州市": [{"Latitude": "41.0781", "StationCode": "1767A", "PositionName": "南山", "Longitude": "121.0986"}, {"Latitude": "40.8333", "StationCode": "1768A", "PositionName": "开发区", "Longitude": "121.0450"}, {"Latitude": "41.1219", "StationCode": "1769A", "PositionName": "百股街道", "Longitude": "121.2008"}, {"Latitude": "41.1222", "StationCode": "1770A", "PositionName": "天安街道", "Longitude": "121.1178"}, {"Latitude": "41.1386", "StationCode": "1771A", "PositionName": "北湖公园", "Longitude": "121.1303"}], "本溪市": [{"Latitude": "41.3283", "StationCode": "1761A", "PositionName": "大峪", "Longitude": "123.8436"}, {"Latitude": "41.3369", "StationCode": "1762A", "PositionName": "溪湖", "Longitude": "123.7528"}, {"Latitude": "41.3047", "StationCode": "1763A", "PositionName": "彩屯", "Longitude": "123.7308"}, {"Latitude": "41.2864", "StationCode": "1764A", "PositionName": "东明", "Longitude": "123.7669"}, {"Latitude": "41.2692", "StationCode": "1765A", "PositionName": "新立屯", "Longitude": "123.7989"}, {"Latitude": "41.3472", "StationCode": "1766A", "PositionName": "威宁", "Longitude": "123.8142"}], "葫芦岛市": [{"Latitude": "40.7136", "StationCode": "1607A", "PositionName": "龙港区", "Longitude": "120.9092"}, {"Latitude": "40.7514", "StationCode": "1608A", "PositionName": "化工街", "Longitude": "120.8392"}, {"Latitude": "40.7150", "StationCode": "1609A", "PositionName": "新区", "Longitude": "120.8478"}, {"Latitude": "40.7736", "StationCode": "1610A", "PositionName": "东城区", "Longitude": "120.8631"}], "阜新市": [{"Latitude": "41.9967", "StationCode": "2207A", "PositionName": "工业园区", "Longitude": "121.6178"}, {"Latitude": "42.0186", "StationCode": "2208A", "PositionName": "长青街", "Longitude": "121.6561"}, {"Latitude": "42.0503", "StationCode": "2209A", "PositionName": "农业园区", "Longitude": "121.6972"}, {"Latitude": "42.0228", "StationCode": "2210A", "PositionName": "东苑", "Longitude": "121.6722"}, {"Latitude": "42.0486", "StationCode": "2211A", "PositionName": "玉龙新城", "Longitude": "121.6592"}], "辽阳市": [{"Latitude": "41.1953", "StationCode": "2212A", "PositionName": "宏伟区", "Longitude": "123.2"}, {"Latitude": "41.2553", "StationCode": "2213A", "PositionName": "新华园", "Longitude": "123.15"}, {"Latitude": "41.2736", "StationCode": "2214A", "PositionName": "滨河路", "Longitude": "123.1761"}, {"Latitude": "41.2894", "StationCode": "2215A", "PositionName": "铁西工业园", "Longitude": "123.1417"}], "盘锦市": [{"Latitude": "41.1556", "StationCode": "1604A", "PositionName": "开发区", "Longitude": "122.0247"}, {"Latitude": "41.0903", "StationCode": "1605A", "PositionName": "兴隆台", "Longitude": "122.0539"}, {"Latitude": "41.1042", "StationCode": "1606A", "PositionName": "新生街道", "Longitude": "121.8350"}], "朝阳市": [{"Latitude": "41.5931", "StationCode": "2220A", "PositionName": "西梁", "Longitude": "120.4439"}, {"Latitude": "41.5672", "StationCode": "2221A", "PositionName": "河畔小区", "Longitude": "120.4486"}, {"Latitude": "41.5647", "StationCode": "2222A", "PositionName": "八里堡", "Longitude": "120.4247"}, {"Latitude": "41.615", "StationCode": "2223A", "PositionName": "农业园区", "Longitude": "120.3939"}], "铁岭市": [{"Latitude": "42.3022", "StationCode": "2216A", "PositionName": "汇工街西", "Longitude": "123.8139"}, {"Latitude": "42.2953", "StationCode": "2217A", "PositionName": "水上乐园", "Longitude": "123.8831"}, {"Latitude": "42.2864", "StationCode": "2218A", "PositionName": "银州路东段", "Longitude": "123.8489"}, {"Latitude": "42.2217", "StationCode": "2219A", "PositionName": "金沙江路北", "Longitude": "123.7153"}], "抚顺市": [{"Latitude": "41.8469", "StationCode": "1755A", "PositionName": "望花区", "Longitude": "123.8100"}, {"Latitude": "41.8828", "StationCode": "1756A", "PositionName": "顺城区", "Longitude": "123.9169"}, {"Latitude": "41.8625", "StationCode": "1757A", "PositionName": "东洲区", "Longitude": "124.0383"}, {"Latitude": "41.8594", "StationCode": "1758A", "PositionName": "新抚区", "Longitude": "123.9000"}, {"Latitude": "41.8864", "StationCode": "1759A", "PositionName": "大伙房水库", "Longitude": "124.0878"}, {"Latitude": "41.8417", "StationCode": "1760A", "PositionName": "沈抚新城", "Longitude": "123.7117"}], "营口市": [{"Latitude": "40.6592", "StationCode": "1596A", "PositionName": "学府南路", "Longitude": "122.2414"}, {"Latitude": "40.7094", "StationCode": "1597A", "PositionName": "大庆路", "Longitude": "122.2703"}, {"Latitude": "40.6511", "StationCode": "1598A", "PositionName": "镜湖西路", "Longitude": "122.2150"}, {"Latitude": "40.6789", "StationCode": "1599A", "PositionName": "西炮台", "Longitude": "122.1658"}]}, "9": {"上海市": [{"Latitude": "31.238", "StationCode": "1141A", "PositionName": "普陀", "Longitude": "121.4"}, {"Latitude": "31.2036", "StationCode": "1142A", "PositionName": "十五厂", "Longitude": "121.478"}, {"Latitude": "31.3008", "StationCode": "1143A", "PositionName": "虹口", "Longitude": "121.467"}, {"Latitude": "31.1654", "StationCode": "1144A", "PositionName": "徐汇上师大", "Longitude": "121.412"}, {"Latitude": "31.2659", "StationCode": "1145A", "PositionName": "杨浦四漂", "Longitude": "121.536"}, {"Latitude": "31.0935", "StationCode": "1146A", "PositionName": "青浦淀山湖", "Longitude": "120.978"}, {"Latitude": "31.2261", "StationCode": "1147A", "PositionName": "静安监测站", "Longitude": "121.425"}, {"Latitude": "31.1907", "StationCode": "1148A", "PositionName": "浦东川沙", "Longitude": "121.703"}, {"Latitude": "31.2284", "StationCode": "1149A", "PositionName": "浦东新区监测站", "Longitude": "121.533"}, {"Latitude": "31.2071", "StationCode": "1150A", "PositionName": "浦东张江", "Longitude": "121.577"}]}, "8": {"伊春市": [{"Latitude": "47.7222", "StationCode": "2252A", "PositionName": "中心医院", "Longitude": "128.8736"}, {"Latitude": "47.7317", "StationCode": "2253A", "PositionName": "林管局", "Longitude": "128.9094"}, {"Latitude": "48.4658", "StationCode": "2254A", "PositionName": "汤旺河国家公园", "Longitude": "129.4942"}], "哈尔滨市": [{"Latitude": "45.755", "StationCode": "1129A", "PositionName": "岭北", "Longitude": "126.542"}, {"Latitude": "45.8167", "StationCode": "1130A", "PositionName": "松北商大", "Longitude": "126.561"}, {"Latitude": "45.5422", "StationCode": "1131A", "PositionName": "阿城会宁", "Longitude": "126.979"}, {"Latitude": "45.7222", "StationCode": "1132A", "PositionName": "南岗学府路", "Longitude": "126.599"}, {"Latitude": "45.7733", "StationCode": "1133A", "PositionName": "太平宏伟公园", "Longitude": "126.689"}, {"Latitude": "45.7667", "StationCode": "1134A", "PositionName": "道外承德广场", "Longitude": "126.635"}, {"Latitude": "45.7319", "StationCode": "1135A", "PositionName": "香坊红旗大街", "Longitude": "126.685"}, {"Latitude": "45.7258", "StationCode": "1136A", "PositionName": "动力和平路", "Longitude": "126.646"}, {"Latitude": "45.7478", "StationCode": "1137A", "PositionName": "道里建国路", "Longitude": "126.593"}, {"Latitude": "45.61", "StationCode": "1138A", "PositionName": "平房东轻厂", "Longitude": "126.615"}, {"Latitude": "45.9819", "StationCode": "1139A", "PositionName": "呼兰师专", "Longitude": "126.6106"}, {"Latitude": "45.6842", "StationCode": "1140A", "PositionName": "省农科院", "Longitude": "126.6206"}], "齐齐哈尔市": [{"Latitude": "47.3636", "StationCode": "1779A", "PositionName": "安居小区", "Longitude": "123.9305"}, {"Latitude": "47.3386", "StationCode": "1780A", "PositionName": "中心广场", "Longitude": "123.9305"}, {"Latitude": "47.3227", "StationCode": "1781A", "PositionName": "农牧车辆厂", "Longitude": "123.9483"}, {"Latitude": "47.2030", "StationCode": "1782A", "PositionName": "富区环保局", "Longitude": "123.6261"}, {"Latitude": "47.2988", "StationCode": "1783A", "PositionName": "市环境监测站", "Longitude": "123.9450"}], "黑河市": [{"Latitude": "50.2486", "StationCode": "2263A", "PositionName": "交通局", "Longitude": "127.4961"}, {"Latitude": "50.2391", "StationCode": "2264A", "PositionName": "党校", "Longitude": "127.5044"}, {"Latitude": "50.2538", "StationCode": "2265A", "PositionName": "地震局", "Longitude": "127.4143"}], "绥化市": [{"Latitude": "46.6384", "StationCode": "2266A", "PositionName": "人和东街", "Longitude": "126.9934"}, {"Latitude": "46.6527", "StationCode": "2267A", "PositionName": "党政办公中心", "Longitude": "126.9636"}], "七台河市": [{"Latitude": "45.7677", "StationCode": "2260A", "PositionName": "环保局", "Longitude": "131.0032"}, {"Latitude": "45.8194", "StationCode": "2261A", "PositionName": "新建", "Longitude": "130.8625"}, {"Latitude": "45.8309", "StationCode": "2262A", "PositionName": "葫头沟", "Longitude": "130.9467"}], "鹤岗市": [{"Latitude": "47.3349", "StationCode": "2244A", "PositionName": "哈啤分公司", "Longitude": "130.2659"}, {"Latitude": "47.2753", "StationCode": "2245A", "PositionName": "斯达机电", "Longitude": "130.261"}, {"Latitude": "47.3489", "StationCode": "2246A", "PositionName": "东山纸板厂", "Longitude": "130.3172"}, {"Latitude": "47.3382", "StationCode": "2247A", "PositionName": "五号水库", "Longitude": "130.1097"}], "大庆市": [{"Latitude": "46.0347", "StationCode": "1789A", "PositionName": "大同区", "Longitude": "124.8354"}, {"Latitude": "46.5280", "StationCode": "1790A", "PositionName": "龙凤区", "Longitude": "125.1120"}, {"Latitude": "46.3991", "StationCode": "1791A", "PositionName": "红岗区", "Longitude": "124.8847"}, {"Latitude": "46.5776", "StationCode": "1792A", "PositionName": "萨尔图区", "Longitude": "125.1386"}, {"Latitude": "46.6219", "StationCode": "1793A", "PositionName": "让胡路区", "Longitude": "124.8648"}], "佳木斯市": [{"Latitude": "46.8025", "StationCode": "2255A", "PositionName": "佳纺", "Longitude": "130.2719"}, {"Latitude": "46.8267", "StationCode": "2256A", "PositionName": "发电厂", "Longitude": "130.3961"}, {"Latitude": "46.7975", "StationCode": "2257A", "PositionName": "环保局", "Longitude": "130.3258"}, {"Latitude": "46.8032", "StationCode": "2258A", "PositionName": "十一中", "Longitude": "130.3648"}, {"Latitude": "46.7588", "StationCode": "2259A", "PositionName": "四丰", "Longitude": "130.3794"}], "鸡西市": [{"Latitude": "45.2924", "StationCode": "2240A", "PositionName": "环保局", "Longitude": "130.962"}, {"Latitude": "45.305", "StationCode": "2241A", "PositionName": "自来水公司", "Longitude": "130.9817"}, {"Latitude": "45.2948", "StationCode": "2242A", "PositionName": "白酒厂", "Longitude": "131.0103"}, {"Latitude": "45.2978", "StationCode": "2243A", "PositionName": "气象局", "Longitude": "130.9298"}], "双鸭山市": [{"Latitude": "46.6572", "StationCode": "2248A", "PositionName": "双合村", "Longitude": "131.1638"}, {"Latitude": "46.619", "StationCode": "2249A", "PositionName": "南小市", "Longitude": "131.1651"}, {"Latitude": "46.6462", "StationCode": "2250A", "PositionName": "环保局", "Longitude": "131.1516"}, {"Latitude": "46.5888", "StationCode": "2251A", "PositionName": "苗圃", "Longitude": "131.1572"}], "牡丹江市": [{"Latitude": "44.5610", "StationCode": "1784A", "PositionName": "环保大楼", "Longitude": "129.6100"}, {"Latitude": "44.5782", "StationCode": "1785A", "PositionName": "文化广场", "Longitude": "129.6115"}, {"Latitude": "44.5952", "StationCode": "1786A", "PositionName": "第一医院", "Longitude": "129.5902"}, {"Latitude": "44.6104", "StationCode": "1787A", "PositionName": "机车工厂", "Longitude": "129.6459"}, {"Latitude": "44.5462", "StationCode": "1788A", "PositionName": "第一中学", "Longitude": "129.6386"}]}, "11": {"宁波市": [{"Latitude": "29.9108", "StationCode": "1234A", "PositionName": "区环保大楼", "Longitude": "121.836"}, {"Latitude": "29.8208", "StationCode": "1235A", "PositionName": "万里学院", "Longitude": "121.56"}, {"Latitude": "29.9572", "StationCode": "1236A", "PositionName": "龙赛医院", "Longitude": "121.713"}, {"Latitude": "29.8906", "StationCode": "1237A", "PositionName": "三江中学", "Longitude": "121.554"}, {"Latitude": "29.7736", "StationCode": "1239A", "PositionName": "钱湖水厂", "Longitude": "121.633"}, {"Latitude": "29.8633", "StationCode": "1240A", "PositionName": "太古小学", "Longitude": "121.586"}, {"Latitude": "29.8506", "StationCode": "1241A", "PositionName": "市环境监测中心", "Longitude": "121.524"}, {"Latitude": "29.90166667", "StationCode": "2871A", "PositionName": "万里国际学校", "Longitude": "121.6147222"}], "舟山市": [{"Latitude": "30.0203", "StationCode": "1258A", "PositionName": "定海檀枫", "Longitude": "122.122"}, {"Latitude": "29.9558", "StationCode": "1259A", "PositionName": "普陀东港", "Longitude": "122.3094"}, {"Latitude": "29.9944", "StationCode": "1260A", "PositionName": "临城新区", "Longitude": "122.19"}], "丽水市": [{"Latitude": "28.4514", "StationCode": "1267A", "PositionName": "监测站大楼", "Longitude": "119.914"}, {"Latitude": "28.4586", "StationCode": "1268A", "PositionName": "莲都小学", "Longitude": "119.93"}, {"Latitude": "28.4231", "StationCode": "1269A", "PositionName": "余庄前", "Longitude": "119.879"}], "衢州市": [{"Latitude": "28.9404", "StationCode": "1264A", "PositionName": "环保大楼", "Longitude": "118.871"}, {"Latitude": "28.9664", "StationCode": "1265A", "PositionName": "实验学校", "Longitude": "118.871"}, {"Latitude": "28.9745", "StationCode": "1266A", "PositionName": "衢州学院", "Longitude": "118.855"}], "杭州市": [{"Latitude": "30.21", "StationCode": "1223A", "PositionName": "滨江", "Longitude": "120.211"}, {"Latitude": "30.2747", "StationCode": "1224A", "PositionName": "西溪", "Longitude": "120.063"}, {"Latitude": "29.635", "StationCode": "1225A", "PositionName": "千岛湖", "Longitude": "119.026"}, {"Latitude": "30.3058", "StationCode": "1226A", "PositionName": "下沙", "Longitude": "120.348"}, {"Latitude": "30.2456", "StationCode": "1227A", "PositionName": "卧龙桥", "Longitude": "120.127"}, {"Latitude": "30.2692", "StationCode": "1228A", "PositionName": "浙江农大", "Longitude": "120.19"}, {"Latitude": "30.2897", "StationCode": "1229A", "PositionName": "朝晖五区", "Longitude": "120.157"}, {"Latitude": "30.3119", "StationCode": "1230A", "PositionName": "和睦小学", "Longitude": "120.12"}, {"Latitude": "30.4183", "StationCode": "1231A", "PositionName": "临平镇", "Longitude": "120.301"}, {"Latitude": "30.1819", "StationCode": "1232A", "PositionName": "城厢镇", "Longitude": "120.27"}, {"Latitude": "30.1808", "StationCode": "1233A", "PositionName": "云栖", "Longitude": "120.088"}], "台州市": [{"Latitude": "28.6459", "StationCode": "1255A", "PositionName": "黄岩环保大楼", "Longitude": "121.273"}, {"Latitude": "28.6542", "StationCode": "1256A", "PositionName": "台州环保大楼", "Longitude": "121.419"}, {"Latitude": "28.5773", "StationCode": "1257A", "PositionName": "路桥田洋王", "Longitude": "121.377"}], "嘉兴市": [{"Latitude": "30.7946", "StationCode": "1252A", "PositionName": "清河小学", "Longitude": "120.744"}, {"Latitude": "30.7478", "StationCode": "1253A", "PositionName": "嘉兴学院", "Longitude": "120.726"}, {"Latitude": "30.7525", "StationCode": "2872A", "PositionName": "南湖区残联", "Longitude": "120.7844444"}], "温州市": [{"Latitude": "28.0089", "StationCode": "1242A", "PositionName": "瓯海", "Longitude": "120.634"}, {"Latitude": "27.9939", "StationCode": "1243A", "PositionName": "南浦", "Longitude": "120.677"}, {"Latitude": "27.9747", "StationCode": "1244A", "PositionName": "龙湾", "Longitude": "120.76"}, {"Latitude": "28.0167", "StationCode": "1245A", "PositionName": "市站", "Longitude": "120.671"}], "湖州市": [{"Latitude": "30.8244", "StationCode": "1250A", "PositionName": "城西水厂", "Longitude": "120.07"}, {"Latitude": "30.89556", "StationCode": "2873A", "PositionName": "仁皇山新区", "Longitude": "120.0875"}, {"Latitude": "30.8596", "StationCode": "2907A", "PositionName": "吴兴区站", "Longitude": "120.1844"}], "金华市": [{"Latitude": "29.077", "StationCode": "1262A", "PositionName": "十五中", "Longitude": "119.647"}, {"Latitude": "29.1029", "StationCode": "1263A", "PositionName": "监测站", "Longitude": "119.686"}, {"Latitude": "29.1128", "StationCode": "2994A", "PositionName": "武警支队", "Longitude": "119.6533"}], "绍兴市": [{"Latitude": "30.0911", "StationCode": "1246A", "PositionName": "袍江站", "Longitude": "120.598"}, {"Latitude": "29.9919", "StationCode": "1247A", "PositionName": "城东开发委", "Longitude": "120.605"}, {"Latitude": "30.0033", "StationCode": "2921A", "PositionName": "树下王站", "Longitude": "120.7789"}]}, "10": {"无锡市": [{"Latitude": "31.4867", "StationCode": "1188A", "PositionName": "雪浪", "Longitude": "120.269"}, {"Latitude": "31.6219", "StationCode": "1189A", "PositionName": "黄巷", "Longitude": "120.275"}, {"Latitude": "31.56", "StationCode": "1190A", "PositionName": "曹张", "Longitude": "120.294"}, {"Latitude": "31.5031", "StationCode": "1191A", "PositionName": "漆塘", "Longitude": "120.242"}, {"Latitude": "31.5848", "StationCode": "1192A", "PositionName": "东亭", "Longitude": "120.354"}, {"Latitude": "31.5475", "StationCode": "1193A", "PositionName": "旺庄", "Longitude": "120.354"}, {"Latitude": "31.5631", "StationCode": "1194A", "PositionName": "荣巷", "Longitude": "120.245"}, {"Latitude": "31.6842", "StationCode": "1195A", "PositionName": "堰桥", "Longitude": "120.288"}], "常州市": [{"Latitude": "31.7586", "StationCode": "1196A", "PositionName": "市监测站", "Longitude": "119.996"}, {"Latitude": "31.7039", "StationCode": "1200A", "PositionName": "武进监测站", "Longitude": "119.935"}, {"Latitude": "31.9108", "StationCode": "1201A", "PositionName": "安家", "Longitude": "119.905"}, {"Latitude": "31.8108", "StationCode": "3002A", "PositionName": "行政中心", "Longitude": "119.9736"}, {"Latitude": "31.7694", "StationCode": "3003A", "PositionName": "经开区", "Longitude": "120.0469"}, {"Latitude": "31.7897", "StationCode": "3010A", "PositionName": "钟楼", "Longitude": "119.8914"}], "泰州市": [{"Latitude": "32.4867", "StationCode": "1206A", "PositionName": "公园路", "Longitude": "119.9"}, {"Latitude": "32.4611", "StationCode": "1207A", "PositionName": "莲花", "Longitude": "119.9219"}, {"Latitude": "32.4639", "StationCode": "1209A", "PositionName": "留学生创业园", "Longitude": "119.888"}, {"Latitude": "32.3292", "StationCode": "2997A", "PositionName": "王营", "Longitude": "119.8767"}], "淮安市": [{"Latitude": "33.5981", "StationCode": "1210A", "PositionName": "钵池山", "Longitude": "119.036"}, {"Latitude": "33.575", "StationCode": "1211A", "PositionName": "北京南路", "Longitude": "119.007"}, {"Latitude": "33.6067", "StationCode": "1212A", "PositionName": "市监测站", "Longitude": "118.989"}, {"Latitude": "33.5039", "StationCode": "1213A", "PositionName": "楚州区监测站", "Longitude": "119.135"}, {"Latitude": "33.6270", "StationCode": "1214A", "PositionName": "淮阴区监测站", "Longitude": "119.0122"}], "徐州市": [{"Latitude": "34.2761", "StationCode": "1177A", "PositionName": "黄河新村", "Longitude": "117.167"}, {"Latitude": "34.2417", "StationCode": "1178A", "PositionName": "淮塔", "Longitude": "117.192"}, {"Latitude": "34.2153", "StationCode": "1180A", "PositionName": "新城区", "Longitude": "117.256"}, {"Latitude": "34.2911", "StationCode": "1181A", "PositionName": "桃园路", "Longitude": "117.244"}, {"Latitude": "34.2778", "StationCode": "1182A", "PositionName": "农科院", "Longitude": "117.2933"}, {"Latitude": "34.29", "StationCode": "3005A", "PositionName": "鼓楼区政府", "Longitude": "117.1814"}, {"Latitude": "34.1781", "StationCode": "3006A", "PositionName": "铜山区招生办", "Longitude": "117.1694"}], "连云港市": [{"Latitude": "34.5885", "StationCode": "1173A", "PositionName": "市环境监测站", "Longitude": "119.176"}, {"Latitude": "34.6972", "StationCode": "3000A", "PositionName": "德源药业(直管站)", "Longitude": "119.3581"}, {"Latitude": "34.7519", "StationCode": "3008A", "PositionName": "胡沟管理处", "Longitude": "119.3608"}, {"Latitude": "34.5911", "StationCode": "3009A", "PositionName": "矿山设计院", "Longitude": "119.1478"}], "扬州市": [{"Latitude": "32.3878", "StationCode": "1184A", "PositionName": "城东财政所", "Longitude": "119.46"}, {"Latitude": "32.41", "StationCode": "1185A", "PositionName": "市监测站", "Longitude": "119.404"}, {"Latitude": "32.3761", "StationCode": "1186A", "PositionName": "邗江监测站", "Longitude": "119.389"}, {"Latitude": "32.41361", "StationCode": "2869A", "PositionName": "五台山医院", "Longitude": "119.4580"}], "宿迁市": [{"Latitude": "33.9528", "StationCode": "1220A", "PositionName": "宿迁学院", "Longitude": "118.293"}, {"Latitude": "33.9592", "StationCode": "1221A", "PositionName": "宿迁中学", "Longitude": "118.2442"}, {"Latitude": "33.9506", "StationCode": "1222A", "PositionName": "宿豫区环保局", "Longitude": "118.3214"}, {"Latitude": "33.9650", "StationCode": "2996A", "PositionName": "市供电局", "Longitude": "118.2830"}], "苏州市": [{"Latitude": "31.2472", "StationCode": "1160A", "PositionName": "上方山", "Longitude": "120.561"}, {"Latitude": "31.2864", "StationCode": "1161A", "PositionName": "南门", "Longitude": "120.628"}, {"Latitude": "31.3019", "StationCode": "1162A", "PositionName": "彩香", "Longitude": "120.591"}, {"Latitude": "31.3264", "StationCode": "1163A", "PositionName": "轧钢厂", "Longitude": "120.596"}, {"Latitude": "31.2703", "StationCode": "1164A", "PositionName": "吴中区", "Longitude": "120.613"}, {"Latitude": "31.2994", "StationCode": "1165A", "PositionName": "苏州新区", "Longitude": "120.543"}, {"Latitude": "31.3097", "StationCode": "1166A", "PositionName": "苏州工业园区", "Longitude": "120.669"}, {"Latitude": "31.3708", "StationCode": "1167A", "PositionName": "相城区", "Longitude": "120.641"}], "南京市": [{"Latitude": "32.1083", "StationCode": "1151A", "PositionName": "迈皋桥", "Longitude": "118.803"}, {"Latitude": "32.0572", "StationCode": "1152A", "PositionName": "草场门", "Longitude": "118.749"}, {"Latitude": "32.0723", "StationCode": "1153A", "PositionName": "山西路", "Longitude": "118.7780"}, {"Latitude": "32.0144", "StationCode": "1154A", "PositionName": "中华门", "Longitude": "118.777"}, {"Latitude": "32.0314", "StationCode": "1155A", "PositionName": "瑞金路", "Longitude": "118.803"}, {"Latitude": "32.0775", "StationCode": "1156A", "PositionName": "玄武湖", "Longitude": "118.795"}, {"Latitude": "32.0878", "StationCode": "1157A", "PositionName": "浦口", "Longitude": "118.626"}, {"Latitude": "32.0092", "StationCode": "1158A", "PositionName": "奥体中心", "Longitude": "118.737"}, {"Latitude": "32.105", "StationCode": "1159A", "PositionName": "仙林大学城", "Longitude": "118.907"}], "盐城市": [{"Latitude": "33.4022", "StationCode": "1215A", "PositionName": "盐城电厂", "Longitude": "120.118"}, {"Latitude": "33.3942", "StationCode": "1216A", "PositionName": "市监测站", "Longitude": "120.156"}, {"Latitude": "33.3947", "StationCode": "1218A", "PositionName": "开发区管委会", "Longitude": "120.225"}, {"Latitude": "33.3681", "StationCode": "3004A", "PositionName": "宝龙广场", "Longitude": "120.1631"}], "南通市": [{"Latitude": "31.96", "StationCode": "1168A", "PositionName": "南郊", "Longitude": "120.913"}, {"Latitude": "32.0005", "StationCode": "1169A", "PositionName": "虹桥", "Longitude": "120.86"}, {"Latitude": "32.02", "StationCode": "1170A", "PositionName": "城中", "Longitude": "120.87"}, {"Latitude": "31.93", "StationCode": "1171A", "PositionName": "星湖花园", "Longitude": "120.94"}, {"Latitude": "32.0417", "StationCode": "1172A", "PositionName": "紫琅学院", "Longitude": "120.81"}], "镇江市": [{"Latitude": "32.1883", "StationCode": "1203A", "PositionName": "新区办事处", "Longitude": "119.68"}, {"Latitude": "32.215", "StationCode": "1204A", "PositionName": "职教中心", "Longitude": "119.491"}, {"Latitude": "32.1319", "StationCode": "1205A", "PositionName": "丹徒区监测站", "Longitude": "119.43"}, {"Latitude": "32.18888889", "StationCode": "2870A", "PositionName": "市疾控中心", "Longitude": "119.4369444"}]}, "13": {"南平市": [{"Latitude": "26.6761", "StationCode": "2331A", "PositionName": "茫荡山", "Longitude": "118.0966"}, {"Latitude": "26.6383", "StationCode": "2332A", "PositionName": "南平市监测站", "Longitude": "118.1694"}, {"Latitude": "26.6514", "StationCode": "2333A", "PositionName": "南平铝业有限公司", "Longitude": "118.1819"}, {"Latitude": "26.6272", "StationCode": "2334A", "PositionName": "南平七中", "Longitude": "118.1756"}], "莆田市": [{"Latitude": "25.442", "StationCode": "2319A", "PositionName": "荔城区仓后路", "Longitude": "119.0156"}, {"Latitude": "25.4552", "StationCode": "2320A", "PositionName": "莆田市监测站", "Longitude": "119.0018"}, {"Latitude": "25.4556", "StationCode": "2321A", "PositionName": "涵江区六中", "Longitude": "119.1117"}, {"Latitude": "25.3214", "StationCode": "2322A", "PositionName": "秀屿区政府", "Longitude": "119.1015"}, {"Latitude": "25.4792", "StationCode": "2323A", "PositionName": "东圳水库", "Longitude": "118.981"}], "龙岩市": [{"Latitude": "25.1174", "StationCode": "2335A", "PositionName": "龙岩师专", "Longitude": "117.0181"}, {"Latitude": "25.1035", "StationCode": "2336A", "PositionName": "龙岩市监测站", "Longitude": "117.0216"}, {"Latitude": "25.0661", "StationCode": "2337A", "PositionName": "闽西职业技术学院", "Longitude": "117.0256"}, {"Latitude": "25.0311", "StationCode": "2338A", "PositionName": "龙岩学院", "Longitude": "117.0151"}], "泉州市": [{"Latitude": "24.9117", "StationCode": "1611A", "PositionName": "涂山街", "Longitude": "118.5819"}, {"Latitude": "24.8978", "StationCode": "1612A", "PositionName": "津头埔", "Longitude": "118.5972"}, {"Latitude": "24.9424", "StationCode": "1613A", "PositionName": "万安", "Longitude": "118.6663"}, {"Latitude": "24.9617", "StationCode": "1614A", "PositionName": "清源山", "Longitude": "118.6108"}], "厦门市": [{"Latitude": "24.818055556", "StationCode": "1286A", "PositionName": "溪东", "Longitude": "118.15694444"}, {"Latitude": "24.476666667", "StationCode": "1287A", "PositionName": "洪文", "Longitude": "118.15138889"}, {"Latitude": "24.445833333", "StationCode": "1288A", "PositionName": "鼓浪屿", "Longitude": "118.06361111"}, {"Latitude": "24.5058", "StationCode": "2842A", "PositionName": "湖里中学", "Longitude": "118.0936"}], "漳州市": [{"Latitude": "24.5157", "StationCode": "2074A", "PositionName": "漳州三中", "Longitude": "117.6569"}, {"Latitude": "24.4674", "StationCode": "2075A", "PositionName": "九湖", "Longitude": "117.6336"}, {"Latitude": "24.5060", "StationCode": "2920A", "PositionName": "蓝田镇", "Longitude": "117.7116"}], "福州市": [{"Latitude": "26.0542", "StationCode": "1280A", "PositionName": "鼓山", "Longitude": "119.389"}, {"Latitude": "26.0258", "StationCode": "1281A", "PositionName": "快安", "Longitude": "119.414"}, {"Latitude": "26.0392", "StationCode": "1282A", "PositionName": "师大", "Longitude": "119.303"}, {"Latitude": "26.1092", "StationCode": "1283A", "PositionName": "五四北路", "Longitude": "119.299"}, {"Latitude": "26.0797", "StationCode": "1284A", "PositionName": "杨桥西路", "Longitude": "119.268"}, {"Latitude": "26.0753", "StationCode": "1285A", "PositionName": "紫阳", "Longitude": "119.315"}], "宁德市": [{"Latitude": "26.6946", "StationCode": "2339A", "PositionName": "金涵水库", "Longitude": "119.5001"}, {"Latitude": "26.6607", "StationCode": "2340A", "PositionName": "蕉城区农机局", "Longitude": "119.5202"}, {"Latitude": "26.6611", "StationCode": "2341A", "PositionName": "宁德市监测站", "Longitude": "119.5392"}], "三明市": [{"Latitude": "26.2625", "StationCode": "2324A", "PositionName": "三钢", "Longitude": "117.6211"}, {"Latitude": "26.2708", "StationCode": "2325A", "PositionName": "三明二中", "Longitude": "117.6353"}, {"Latitude": "26.2378", "StationCode": "2326A", "PositionName": "三元区政府", "Longitude": "117.6028"}, {"Latitude": "26.3108", "StationCode": "2327A", "PositionName": "洋溪", "Longitude": "117.7275"}]}, "12": {"滁州市": [{"Latitude": "32.3153", "StationCode": "2298A", "PositionName": "老年大学", "Longitude": "118.3094"}, {"Latitude": "32.2786", "StationCode": "2299A", "PositionName": "人大宾馆", "Longitude": "118.3244"}, {"Latitude": "32.3061", "StationCode": "2300A", "PositionName": "监测站", "Longitude": "118.3158"}], "黄山市": [{"Latitude": "29.7128", "StationCode": "2295A", "PositionName": "延安路89号", "Longitude": "118.3057"}, {"Latitude": "29.7207", "StationCode": "2296A", "PositionName": "黄山东路89号", "Longitude": "118.3236"}, {"Latitude": "30.2756", "StationCode": "2297A", "PositionName": "黄山区政府5号楼", "Longitude": "118.1371"}], "铜陵市": [{"Latitude": "30.9414", "StationCode": "2285A", "PositionName": "市第四中学", "Longitude": "117.8178"}, {"Latitude": "30.9222", "StationCode": "2286A", "PositionName": "市公路局", "Longitude": "117.8078"}, {"Latitude": "30.9414", "StationCode": "2287A", "PositionName": "市新民污水厂", "Longitude": "117.7806"}, {"Latitude": "30.8811", "StationCode": "2288A", "PositionName": "市第九中学", "Longitude": "117.7442"}, {"Latitude": "30.9219", "StationCode": "2289A", "PositionName": "车站新区", "Longitude": "117.8561"}, {"Latitude": "30.9697", "StationCode": "2290A", "PositionName": "市职教基地", "Longitude": "117.8472"}], "淮北市": [{"Latitude": "33.975", "StationCode": "2282A", "PositionName": "监测站", "Longitude": "116.8008"}, {"Latitude": "33.8997", "StationCode": "2283A", "PositionName": "烈山区政府", "Longitude": "116.8067"}, {"Latitude": "33.9461", "StationCode": "2284A", "PositionName": "职业技术学院", "Longitude": "116.7844"}], "芜湖市": [{"Latitude": "31.3508", "StationCode": "1794A", "PositionName": "监测站", "Longitude": "118.3528"}, {"Latitude": "31.4189", "StationCode": "1795A", "PositionName": "科创中心", "Longitude": "118.3700"}, {"Latitude": "31.3178", "StationCode": "1796A", "PositionName": "四水厂", "Longitude": "118.3708"}, {"Latitude": "31.3839", "StationCode": "1797A", "PositionName": "五七二零厂", "Longitude": "118.4022"}], "安庆市": [{"Latitude": "30.5103", "StationCode": "2291A", "PositionName": "环科院", "Longitude": "117.0549"}, {"Latitude": "30.51197222", "StationCode": "2292A", "PositionName": "马山宾馆", "Longitude": "117.0331111"}, {"Latitude": "30.5489", "StationCode": "2293A", "PositionName": "联富花园", "Longitude": "117.0486"}, {"Latitude": "30.6145", "StationCode": "2294A", "PositionName": "安庆大学", "Longitude": "116.9894"}], "宣城市": [{"Latitude": "30.9447", "StationCode": "2316A", "PositionName": "鳌峰子站", "Longitude": "118.7581"}, {"Latitude": "30.9742", "StationCode": "2317A", "PositionName": "敬亭山子站", "Longitude": "118.7386"}, {"Latitude": "30.9431", "StationCode": "2318A", "PositionName": "开发区子站", "Longitude": "118.7175"}], "六安市": [{"Latitude": "31.7371", "StationCode": "2307A", "PositionName": "监测大楼", "Longitude": "116.508"}, {"Latitude": "31.7618", "StationCode": "2308A", "PositionName": "皖西学院", "Longitude": "116.478"}, {"Latitude": "31.7797", "StationCode": "2309A", "PositionName": "朝阳厂", "Longitude": "116.5068"}, {"Latitude": "31.7712", "StationCode": "2310A", "PositionName": "开发区", "Longitude": "116.5661"}], "蚌埠市": [{"Latitude": "32.939", "StationCode": "2270A", "PositionName": "工人疗养院", "Longitude": "117.3961"}, {"Latitude": "32.9444", "StationCode": "2271A", "PositionName": "百货大楼", "Longitude": "117.3575"}, {"Latitude": "32.935", "StationCode": "2272A", "PositionName": "二水厂", "Longitude": "117.3086"}, {"Latitude": "32.8913", "StationCode": "2273A", "PositionName": "蚌埠学院", "Longitude": "117.4186"}, {"Latitude": "32.9673", "StationCode": "2274A", "PositionName": "淮上区政府", "Longitude": "117.3536"}, {"Latitude": "32.8985", "StationCode": "2275A", "PositionName": "高新区", "Longitude": "117.3065"}], "宿州市": [{"Latitude": "33.6481", "StationCode": "2304A", "PositionName": "监测楼", "Longitude": "116.9765"}, {"Latitude": "33.6284", "StationCode": "2305A", "PositionName": "一中", "Longitude": "116.9677"}, {"Latitude": "33.63063889", "StationCode": "2306A", "PositionName": "火车站", "Longitude": "116.989"}], "阜阳市": [{"Latitude": "32.8928", "StationCode": "2301A", "PositionName": "市监测站", "Longitude": "115.8275"}, {"Latitude": "32.8603", "StationCode": "2303A", "PositionName": "开发区", "Longitude": "115.8556"}, {"Latitude": "32.88922222", "StationCode": "2875A", "PositionName": "阜阳职业技术学院", "Longitude": "115.7838889"}], "合肥市": [{"Latitude": "31.7848", "StationCode": "1270A", "PositionName": "明珠广场", "Longitude": "117.196"}, {"Latitude": "31.8766", "StationCode": "1271A", "PositionName": "三里街", "Longitude": "117.307"}, {"Latitude": "31.8706", "StationCode": "1272A", "PositionName": "琥珀山庄", "Longitude": "117.259"}, {"Latitude": "31.9051", "StationCode": "1273A", "PositionName": "董铺水库", "Longitude": "117.16"}, {"Latitude": "31.8572", "StationCode": "1274A", "PositionName": "长江中路", "Longitude": "117.25"}, {"Latitude": "31.9438", "StationCode": "1275A", "PositionName": "庐阳区", "Longitude": "117.266"}, {"Latitude": "31.8585", "StationCode": "1276A", "PositionName": "瑶海区", "Longitude": "117.336"}, {"Latitude": "31.7956", "StationCode": "1277A", "PositionName": "包河区", "Longitude": "117.302"}, {"Latitude": "31.7386", "StationCode": "1278A", "PositionName": "滨湖新区", "Longitude": "117.278"}, {"Latitude": "31.8516", "StationCode": "1279A", "PositionName": "高新区", "Longitude": "117.124"}], "淮南市": [{"Latitude": "32.7639", "StationCode": "2277A", "PositionName": "潘集区政府", "Longitude": "116.8028"}, {"Latitude": "32.645", "StationCode": "2278A", "PositionName": "师范学院", "Longitude": "117.0083"}, {"Latitude": "32.6028", "StationCode": "2279A", "PositionName": "谢家集区政府", "Longitude": "116.8556"}, {"Latitude": "32.6319", "StationCode": "2280A", "PositionName": "八公山区政府", "Longitude": "116.8306"}, {"Latitude": "32.625", "StationCode": "2281A", "PositionName": "焦岗湖风景区管理处", "Longitude": "116.7039"}, {"Latitude": "32.64600333", "StationCode": "2874A", "PositionName": "益益乳业工业园", "Longitude": "117.0411667"}], "马鞍山市": [{"Latitude": "31.6861", "StationCode": "1798A", "PositionName": "湖东路四小", "Longitude": "118.5058"}, {"Latitude": "31.6411", "StationCode": "1799A", "PositionName": "天平服装", "Longitude": "118.4828"}, {"Latitude": "31.7506", "StationCode": "1800A", "PositionName": "慈湖二小", "Longitude": "118.5106"}, {"Latitude": "31.6928", "StationCode": "1801A", "PositionName": "马钢动力厂", "Longitude": "118.4800"}, {"Latitude": "31.7133", "StationCode": "1802A", "PositionName": "市教育基地", "Longitude": "118.6439"}], "亳州市": [{"Latitude": "33.8399", "StationCode": "2311A", "PositionName": "污水处理厂", "Longitude": "115.8067"}, {"Latitude": "33.8561", "StationCode": "2312A", "PositionName": "三国揽胜宫", "Longitude": "115.7831"}], "池州市": [{"Latitude": "30.6617", "StationCode": "2314A", "PositionName": "池州学院", "Longitude": "117.4697"}, {"Latitude": "30.6539", "StationCode": "2315A", "PositionName": "平天湖", "Longitude": "117.4974"}, {"Latitude": "30.66", "StationCode": "2916A", "PositionName": "老干部局", "Longitude": "117.49"}]}, "15": {"济宁市": [{"Latitude": "35.4280", "StationCode": "1653A", "PositionName": "火炬城", "Longitude": "116.6305"}, {"Latitude": "35.4144", "StationCode": "1654A", "PositionName": "监测站", "Longitude": "116.5856"}, {"Latitude": "35.4039", "StationCode": "1655A", "PositionName": "电化厂", "Longitude": "116.5546"}], "青岛市": [{"Latitude": "36.2403", "StationCode": "1307A", "PositionName": "仰口", "Longitude": "120.6659"}, {"Latitude": "36.1851", "StationCode": "1308A", "PositionName": "李沧区子站", "Longitude": "120.3905"}, {"Latitude": "36.0699", "StationCode": "1309A", "PositionName": "市北区子站", "Longitude": "120.3471"}, {"Latitude": "36.0654", "StationCode": "1310A", "PositionName": "市南区东部子站", "Longitude": "120.4134"}, {"Latitude": "36.1032", "StationCode": "1311A", "PositionName": "四方区子站", "Longitude": "120.3664"}, {"Latitude": "36.0543", "StationCode": "1312A", "PositionName": "市南区西部子站", "Longitude": "120.2992"}, {"Latitude": "36.0851", "StationCode": "1313A", "PositionName": "崂山区子站", "Longitude": "120.4587"}, {"Latitude": "36.3083", "StationCode": "1314A", "PositionName": "黄岛区子站", "Longitude": "120.1964"}, {"Latitude": "36.2403", "StationCode": "1315A", "PositionName": "城阳区子站", "Longitude": "120.4001"}], "淄博市": [{"Latitude": "36.8088", "StationCode": "1631A", "PositionName": "人民公园", "Longitude": "118.0482"}, {"Latitude": "36.8380", "StationCode": "1632A", "PositionName": "东风化工厂", "Longitude": "118.0448"}, {"Latitude": "36.4970", "StationCode": "1633A", "PositionName": "双山", "Longitude": "117.8477"}, {"Latitude": "36.6377", "StationCode": "1634A", "PositionName": "气象站", "Longitude": "117.9544"}, {"Latitude": "36.8198", "StationCode": "1635A", "PositionName": "莆田园", "Longitude": "118.3092"}, {"Latitude": "36.8041", "StationCode": "1636A", "PositionName": "三金集团", "Longitude": "117.8512"}], "枣庄市": [{"Latitude": "34.8640", "StationCode": "1637A", "PositionName": "市中区政府", "Longitude": "117.5564"}, {"Latitude": "34.7837", "StationCode": "1638A", "PositionName": "薛城环保局", "Longitude": "117.2852"}, {"Latitude": "34.7745", "StationCode": "1639A", "PositionName": "峄城区政府", "Longitude": "117.5852"}, {"Latitude": "34.5667", "StationCode": "1640A", "PositionName": "台儿庄区环保局", "Longitude": "117.7320"}, {"Latitude": "35.0992", "StationCode": "1641A", "PositionName": "山亭区环保局", "Longitude": "117.4518"}], "烟台市": [{"Latitude": "37.5639", "StationCode": "1642A", "PositionName": "开发区", "Longitude": "121.2514"}, {"Latitude": "37.5433", "StationCode": "1643A", "PositionName": "轴承厂", "Longitude": "121.3719"}, {"Latitude": "37.5436", "StationCode": "1644A", "PositionName": "西郊化工站", "Longitude": "121.3181"}, {"Latitude": "37.4822", "StationCode": "1645A", "PositionName": "莱山环保局", "Longitude": "121.4478"}, {"Latitude": "37.4967", "StationCode": "1646A", "PositionName": "福山环保局", "Longitude": "121.2611"}, {"Latitude": "37.3872", "StationCode": "1647A", "PositionName": "牟平环保局", "Longitude": "121.5953"}], "菏泽市": [{"Latitude": "35.248889", "StationCode": "1718A", "PositionName": "市气象局", "Longitude": "115.42277"}, {"Latitude": "35.2375", "StationCode": "1719A", "PositionName": "市政协", "Longitude": "115.474722"}, {"Latitude": "35.27", "StationCode": "1720A", "PositionName": "菏泽学院", "Longitude": "115.455"}], "潍坊市": [{"Latitude": "36.7019", "StationCode": "1648A", "PositionName": "仲裁委", "Longitude": "119.1200"}, {"Latitude": "36.7008", "StationCode": "1650A", "PositionName": "环保局", "Longitude": "119.1425"}, {"Latitude": "36.7731", "StationCode": "1652A", "PositionName": "寒亭监测站", "Longitude": "119.1939"}, {"Latitude": "36.7339", "StationCode": "2876A", "PositionName": "幼特教师范", "Longitude": "119.0841"}, {"Latitude": "36.6525", "StationCode": "2877A", "PositionName": "坊子邮政", "Longitude": "119.1638"}], "莱芜市": [{"Latitude": "36.2050", "StationCode": "1615A", "PositionName": "植物油厂", "Longitude": "117.6850"}, {"Latitude": "36.2289", "StationCode": "1616A", "PositionName": "技术学院", "Longitude": "117.6789"}, {"Latitude": "36.2081", "StationCode": "1617A", "PositionName": "日升国际", "Longitude": "117.7150"}], "威海市": [{"Latitude": "37.4294", "StationCode": "1662A", "PositionName": "华夏技校", "Longitude": "122.1206"}, {"Latitude": "37.5325", "StationCode": "1663A", "PositionName": "山大分校", "Longitude": "122.0508"}, {"Latitude": "37.5072", "StationCode": "1664A", "PositionName": "市监测站", "Longitude": "122.1067"}], "德州市": [{"Latitude": "37.4664", "StationCode": "1622A", "PositionName": "儿童乐园", "Longitude": "116.3061"}, {"Latitude": "37.4504", "StationCode": "1623A", "PositionName": "黑马集团", "Longitude": "116.2729"}, {"Latitude": "37.4489", "StationCode": "1624A", "PositionName": "监理站", "Longitude": "116.3189"}], "聊城市": [{"Latitude": "36.4372", "StationCode": "1625A", "PositionName": "区政府", "Longitude": "115.9848"}, {"Latitude": "36.4796", "StationCode": "1627A", "PositionName": "党校", "Longitude": "115.9835"}, {"Latitude": "36.4343", "StationCode": "2878A", "PositionName": "聊大东校", "Longitude": "116.0072"}], "东营市": [{"Latitude": "37.4658", "StationCode": "1665A", "PositionName": "西城阳光环保公司", "Longitude": "118.5019"}, {"Latitude": "37.4314", "StationCode": "1666A", "PositionName": "市环保局", "Longitude": "118.6672"}, {"Latitude": "37.4442", "StationCode": "1667A", "PositionName": "耿井村", "Longitude": "118.5857"}, {"Latitude": "37.3781", "StationCode": "1668A", "PositionName": "广南水库", "Longitude": "118.8192"}], "滨州市": [{"Latitude": "37.3803", "StationCode": "1628A", "PositionName": "市环保局", "Longitude": "118.0062"}, {"Latitude": "37.3617", "StationCode": "1629A", "PositionName": "第二水厂", "Longitude": "118.0018"}, {"Latitude": "37.3930", "StationCode": "1630A", "PositionName": "北中新校", "Longitude": "117.9776"}], "济南市": [{"Latitude": "36.6114", "StationCode": "1299A", "PositionName": "科干所", "Longitude": "116.988"}, {"Latitude": "36.67", "StationCode": "1300A", "PositionName": "农科所", "Longitude": "116.93"}, {"Latitude": "36.6739", "StationCode": "1301A", "PositionName": "开发区", "Longitude": "117.114"}, {"Latitude": "36.6872", "StationCode": "1302A", "PositionName": "济南化工厂", "Longitude": "116.989"}, {"Latitude": "36.6868", "StationCode": "1303A", "PositionName": "省种子仓库", "Longitude": "117.0684"}, {"Latitude": "36.6489", "StationCode": "1304A", "PositionName": "机床二厂", "Longitude": "116.943"}, {"Latitude": "36.6622", "StationCode": "1305A", "PositionName": "市监测站", "Longitude": "117.049"}, {"Latitude": "36.5336", "StationCode": "1306A", "PositionName": "长清党校", "Longitude": "116.734"}], "日照市": [{"Latitude": "35.4178", "StationCode": "1659A", "PositionName": "监测站", "Longitude": "119.4641"}, {"Latitude": "35.4234", "StationCode": "1660A", "PositionName": "市政府广场", "Longitude": "119.5198"}, {"Latitude": "35.3962", "StationCode": "1661A", "PositionName": "港务局", "Longitude": "119.5400"}], "临沂市": [{"Latitude": "35.0573", "StationCode": "1618A", "PositionName": "沂河小区", "Longitude": "118.3418"}, {"Latitude": "35.0622", "StationCode": "1619A", "PositionName": "鲁南制药厂", "Longitude": "118.2939"}, {"Latitude": "34.9817", "StationCode": "1620A", "PositionName": "新光毛纺厂", "Longitude": "118.2764"}, {"Latitude": "35.0896", "StationCode": "1621A", "PositionName": "河东保险公司", "Longitude": "118.4023"}], "泰安市": [{"Latitude": "36.1942", "StationCode": "1656A", "PositionName": "监测站", "Longitude": "117.1436"}, {"Latitude": "36.1942", "StationCode": "1657A", "PositionName": "人口学校", "Longitude": "117.0881"}, {"Latitude": "36.1758", "StationCode": "1658A", "PositionName": "电力学校", "Longitude": "117.1081"}]}, "14": {"赣州市": [{"Latitude": "25.9118", "StationCode": "2362A", "PositionName": "通天岩", "Longitude": "114.9064"}, {"Latitude": "25.8664", "StationCode": "2363A", "PositionName": "地委", "Longitude": "114.9367"}, {"Latitude": "25.8481", "StationCode": "2364A", "PositionName": "气象台", "Longitude": "114.9461"}, {"Latitude": "25.8333", "StationCode": "2365A", "PositionName": "市图书馆", "Longitude": "114.9322"}, {"Latitude": "25.8471", "StationCode": "2366A", "PositionName": "华坚鞋城", "Longitude": "114.8905"}], "上饶市": [{"Latitude": "28.4569", "StationCode": "2381A", "PositionName": "百草园", "Longitude": "118.0058"}, {"Latitude": "28.4459", "StationCode": "2382A", "PositionName": "市监测站", "Longitude": "117.973"}, {"Latitude": "28.4622", "StationCode": "2383A", "PositionName": "凤凰光学", "Longitude": "117.9511"}, {"Latitude": "28.4303", "StationCode": "2384A", "PositionName": "开发区管委会", "Longitude": "117.9033"}], "新余市": [{"Latitude": "27.7758", "StationCode": "2352A", "PositionName": "北岗", "Longitude": "115.0586"}, {"Latitude": "27.8344", "StationCode": "2353A", "PositionName": "飞宇", "Longitude": "114.9831"}, {"Latitude": "27.8328", "StationCode": "2354A", "PositionName": "第二水厂", "Longitude": "114.9289"}, {"Latitude": "27.8036", "StationCode": "2355A", "PositionName": "市气象局", "Longitude": "114.9314"}, {"Latitude": "27.8042", "StationCode": "2356A", "PositionName": "新钢氧气厂", "Longitude": "114.9119"}], "抚州市": [{"Latitude": "28.0797", "StationCode": "2376A", "PositionName": "桐源党溪", "Longitude": "116.2239"}, {"Latitude": "27.9883", "StationCode": "2377A", "PositionName": "市站", "Longitude": "116.3553"}, {"Latitude": "27.9639", "StationCode": "2378A", "PositionName": "血防站", "Longitude": "116.3598"}, {"Latitude": "28.0005", "StationCode": "2379A", "PositionName": "采茶剧团", "Longitude": "116.3574"}, {"Latitude": "27.9647", "StationCode": "2380A", "PositionName": "医学分院", "Longitude": "116.385"}], "宜春市": [{"Latitude": "27.8036", "StationCode": "2371A", "PositionName": "槟榔水业", "Longitude": "114.3442"}, {"Latitude": "27.8014", "StationCode": "2372A", "PositionName": "市中国银行", "Longitude": "114.3806"}, {"Latitude": "27.7842", "StationCode": "2373A", "PositionName": "市石油公司", "Longitude": "114.3953"}, {"Latitude": "27.7914", "StationCode": "2374A", "PositionName": "市气象局", "Longitude": "114.3703"}, {"Latitude": "27.8072", "StationCode": "2375A", "PositionName": "市广电局", "Longitude": "114.4011"}], "萍乡市": [{"Latitude": "27.4948", "StationCode": "2347A", "PositionName": "武功山气象站", "Longitude": "114.0944"}, {"Latitude": "27.6428", "StationCode": "2348A", "PositionName": "中医院", "Longitude": "113.8381"}, {"Latitude": "27.6231", "StationCode": "2349A", "PositionName": "市政府车库", "Longitude": "113.8447"}, {"Latitude": "27.6442", "StationCode": "2350A", "PositionName": "市环保局", "Longitude": "113.8686"}, {"Latitude": "27.6178", "StationCode": "2351A", "PositionName": "安源区政府", "Longitude": "113.865"}], "鹰潭市": [{"Latitude": "28.095", "StationCode": "2357A", "PositionName": "龙虎山", "Longitude": "116.9622"}, {"Latitude": "28.2642", "StationCode": "2358A", "PositionName": "新监测站", "Longitude": "117.0564"}, {"Latitude": "28.2403", "StationCode": "2359A", "PositionName": "财苑宾馆", "Longitude": "117.0281"}, {"Latitude": "28.2264", "StationCode": "2360A", "PositionName": "体育馆", "Longitude": "117.0222"}, {"Latitude": "28.2169", "StationCode": "2361A", "PositionName": "三川水表", "Longitude": "116.9983"}], "吉安市": [{"Latitude": "27.0658", "StationCode": "2367A", "PositionName": "红声器材厂", "Longitude": "114.9817"}, {"Latitude": "27.11", "StationCode": "2368A", "PositionName": "市森林工业局", "Longitude": "114.9739"}, {"Latitude": "27.1311", "StationCode": "2369A", "PositionName": "市环境监测站", "Longitude": "114.99"}, {"Latitude": "27.0983", "StationCode": "2370A", "PositionName": "青原区法院", "Longitude": "115.0075"}], "九江市": [{"Latitude": "29.6816", "StationCode": "1803A", "PositionName": "十里", "Longitude": "115.9872"}, {"Latitude": "29.7048", "StationCode": "1804A", "PositionName": "茅山头", "Longitude": "115.9581"}, {"Latitude": "29.7292", "StationCode": "1805A", "PositionName": "西园", "Longitude": "115.9880"}, {"Latitude": "29.6535", "StationCode": "1806A", "PositionName": "五七二七厂", "Longitude": "116.0174"}, {"Latitude": "29.6926", "StationCode": "1807A", "PositionName": "水科所", "Longitude": "116.0628"}, {"Latitude": "29.6039", "StationCode": "1808A", "PositionName": "综合工业园", "Longitude": "115.9114"}, {"Latitude": "29.7534", "StationCode": "1809A", "PositionName": "石化总厂", "Longitude": "116.0726"}, {"Latitude": "29.5867", "StationCode": "1810A", "PositionName": "庐山气象台", "Longitude": "115.9936"}], "南昌市": [{"Latitude": "28.6844", "StationCode": "1290A", "PositionName": "省外办", "Longitude": "115.893"}, {"Latitude": "28.6839", "StationCode": "1291A", "PositionName": "省林业公司", "Longitude": "115.8886"}, {"Latitude": "28.7442", "StationCode": "1292A", "PositionName": "林科所", "Longitude": "115.813"}, {"Latitude": "28.6969", "StationCode": "1293A", "PositionName": "京东镇政府", "Longitude": "115.973"}, {"Latitude": "28.6869", "StationCode": "1294A", "PositionName": "建工学校", "Longitude": "115.852"}, {"Latitude": "28.6425", "StationCode": "1295A", "PositionName": "象湖", "Longitude": "115.892"}, {"Latitude": "28.7994", "StationCode": "1296A", "PositionName": "武术学校", "Longitude": "115.742"}, {"Latitude": "28.6131", "StationCode": "1297A", "PositionName": "石化", "Longitude": "115.912"}, {"Latitude": "28.6844", "StationCode": "1298A", "PositionName": "省站", "Longitude": "115.931"}], "景德镇市": [{"Latitude": "29.3864", "StationCode": "2342A", "PositionName": "王岗中学", "Longitude": "117.3097"}, {"Latitude": "29.2958", "StationCode": "2343A", "PositionName": "老干部活动中心", "Longitude": "117.2111"}, {"Latitude": "29.2786", "StationCode": "2344A", "PositionName": "兽医站", "Longitude": "117.1983"}, {"Latitude": "29.2647", "StationCode": "2345A", "PositionName": "台达陶瓷", "Longitude": "117.1558"}, {"Latitude": "29.2956", "StationCode": "2346A", "PositionName": "陶研所", "Longitude": "117.2461"}]}, "17": {"宜昌市": [{"Latitude": "30.7157", "StationCode": "1839A", "PositionName": "四零三", "Longitude": "111.3009"}, {"Latitude": "30.6980", "StationCode": "1840A", "PositionName": "白龙岗", "Longitude": "111.2992"}, {"Latitude": "30.6463", "StationCode": "1841A", "PositionName": "伍家岗", "Longitude": "111.3549"}, {"Latitude": "30.6960", "StationCode": "1842A", "PositionName": "点军区", "Longitude": "111.2680"}, {"Latitude": "30.7819", "StationCode": "1843A", "PositionName": "夷陵区", "Longitude": "111.3296"}], "荆州市": [{"Latitude": "30.3175", "StationCode": "1844A", "PositionName": "市图书馆", "Longitude": "112.2551"}, {"Latitude": "30.3515", "StationCode": "1845A", "PositionName": "市委党校", "Longitude": "112.2068"}, {"Latitude": "30.3055", "StationCode": "1846A", "PositionName": "科融环保", "Longitude": "112.2887"}], "黄石市": [{"Latitude": "30.2352", "StationCode": "2423A", "PositionName": "沈家营", "Longitude": "115.0625"}, {"Latitude": "30.2028", "StationCode": "2424A", "PositionName": "陈家湾", "Longitude": "115.0767"}, {"Latitude": "30.1765", "StationCode": "2425A", "PositionName": "新下陆", "Longitude": "114.9551"}, {"Latitude": "30.2043", "StationCode": "2426A", "PositionName": "铁山", "Longitude": "114.8949"}, {"Latitude": "30.2099", "StationCode": "2427A", "PositionName": "经济开发区", "Longitude": "115.0264"}], "黄冈市": [{"Latitude": "30.4742", "StationCode": "2446A", "PositionName": "职工中心", "Longitude": "114.9028"}, {"Latitude": "30.4519", "StationCode": "2929A", "PositionName": "红卫路", "Longitude": "114.8858"}], "荆门市": [{"Latitude": "31.0483", "StationCode": "2439A", "PositionName": "竹园小学", "Longitude": "112.2014"}, {"Latitude": "30.9892", "StationCode": "2440A", "PositionName": "掇刀", "Longitude": "112.1969"}, {"Latitude": "31.0386", "StationCode": "2441A", "PositionName": "石化一小", "Longitude": "112.2211"}, {"Latitude": "31.03389", "StationCode": "3012A", "PositionName": "西山林语", "Longitude": "112.1908"}], "武汉市": [{"Latitude": "30.5719", "StationCode": "1325A", "PositionName": "东湖梨园", "Longitude": "114.3672"}, {"Latitude": "30.5514", "StationCode": "1326A", "PositionName": "汉阳月湖", "Longitude": "114.2511"}, {"Latitude": "30.6197", "StationCode": "1327A", "PositionName": "汉口花桥", "Longitude": "114.2836"}, {"Latitude": "30.5494", "StationCode": "1328A", "PositionName": "武昌紫阳", "Longitude": "114.3006"}, {"Latitude": "30.6103", "StationCode": "1329A", "PositionName": "青山钢花", "Longitude": "114.4272"}, {"Latitude": "30.4753", "StationCode": "1330A", "PositionName": "沌口新区", "Longitude": "114.1525"}, {"Latitude": "30.5947", "StationCode": "1331A", "PositionName": "汉口江滩", "Longitude": "114.3008"}, {"Latitude": "30.4822", "StationCode": "1332A", "PositionName": "东湖高新", "Longitude": "114.3894"}, {"Latitude": "30.6414", "StationCode": "1333A", "PositionName": "吴家山", "Longitude": "114.2131"}, {"Latitude": "30.2997", "StationCode": "1334A", "PositionName": "沉湖七壕", "Longitude": "113.8531"}], "随州市": [{"Latitude": "31.7275", "StationCode": "2451A", "PositionName": "市委党校", "Longitude": "113.3583"}, {"Latitude": "31.6908", "StationCode": "2452A", "PositionName": "市林业局", "Longitude": "113.3833"}, {"Latitude": "31.7308", "StationCode": "2453A", "PositionName": "市立交桥水厂", "Longitude": "113.3983"}], "鄂州市": [{"Latitude": "30.3944", "StationCode": "2436A", "PositionName": "市政府", "Longitude": "114.8878"}, {"Latitude": "30.3714", "StationCode": "2437A", "PositionName": "赵家坝", "Longitude": "114.8989"}, {"Latitude": "30.4133", "StationCode": "2438A", "PositionName": "凡口开发区", "Longitude": "114.8131"}], "十堰市": [{"Latitude": "32.395", "StationCode": "2428A", "PositionName": "武当山", "Longitude": "111.0419"}, {"Latitude": "32.6494", "StationCode": "2429A", "PositionName": "滨河新村", "Longitude": "110.78"}, {"Latitude": "32.6389", "StationCode": "2430A", "PositionName": "刘家沟", "Longitude": "110.7258"}, {"Latitude": "32.5714", "StationCode": "2431A", "PositionName": "铁二处", "Longitude": "110.8839"}], "孝感市": [{"Latitude": "30.9285", "StationCode": "2443A", "PositionName": "文化路", "Longitude": "113.9153"}, {"Latitude": "30.9075", "StationCode": "2444A", "PositionName": "东城区", "Longitude": "113.942"}], "咸宁市": [{"Latitude": "29.8181", "StationCode": "2447A", "PositionName": "森林公园", "Longitude": "114.3036"}, {"Latitude": "29.8211", "StationCode": "2448A", "PositionName": "市发改委", "Longitude": "114.3231"}, {"Latitude": "29.8539", "StationCode": "2449A", "PositionName": "咸安区政府", "Longitude": "114.2894"}, {"Latitude": "29.8686", "StationCode": "2450A", "PositionName": "长江产业园", "Longitude": "114.3372"}], "恩施州": [{"Latitude": "30.2989", "StationCode": "2454A", "PositionName": "湖北民院", "Longitude": "109.5039"}, {"Latitude": "30.2819", "StationCode": "2455A", "PositionName": "州电力总公司", "Longitude": "109.4689"}], "襄阳市": [{"Latitude": "32.0197", "StationCode": "2432A", "PositionName": "襄城运动路", "Longitude": "112.155"}, {"Latitude": "32.0564", "StationCode": "2433A", "PositionName": "樊城新华路", "Longitude": "112.1392"}, {"Latitude": "32.1142", "StationCode": "2434A", "PositionName": "高新管委会", "Longitude": "112.1825"}, {"Latitude": "32.0903", "StationCode": "2435A", "PositionName": "襄州航空路", "Longitude": "112.2106"}]}, "16": {"驻马店市": [{"Latitude": "32.965", "StationCode": "2420A", "PositionName": "市一纸厂", "Longitude": "114.018"}, {"Latitude": "33.0069", "StationCode": "2421A", "PositionName": "市彩印厂", "Longitude": "114.0131"}, {"Latitude": "32.996", "StationCode": "2422A", "PositionName": "天方二分厂", "Longitude": "113.996"}], "开封市": [{"Latitude": "34.8022", "StationCode": "1823A", "PositionName": "河大一附院", "Longitude": "114.3406"}, {"Latitude": "34.7781", "StationCode": "1824A", "PositionName": "肿瘤医院", "Longitude": "114.3389"}, {"Latitude": "34.7975", "StationCode": "1825A", "PositionName": "妇幼保健院", "Longitude": "114.3733"}, {"Latitude": "34.7967", "StationCode": "1826A", "PositionName": "世纪星幼儿园", "Longitude": "114.2886"}], "南阳市": [{"Latitude": "32.9917", "StationCode": "2403A", "PositionName": "环保局", "Longitude": "112.5192"}, {"Latitude": "33.0122", "StationCode": "2404A", "PositionName": "瓦房庄", "Longitude": "112.5224"}, {"Latitude": "32.9735", "StationCode": "2405A", "PositionName": "汉画馆", "Longitude": "112.5003"}, {"Latitude": "33.027", "StationCode": "2406A", "PositionName": "气象站", "Longitude": "112.5573"}, {"Latitude": "32.9683", "StationCode": "2407A", "PositionName": "理工学院", "Longitude": "112.55"}], "郑州市": [{"Latitude": "34.7545", "StationCode": "1316A", "PositionName": "烟厂", "Longitude": "113.681"}, {"Latitude": "34.7745", "StationCode": "1317A", "PositionName": "郑纺机", "Longitude": "113.641"}, {"Latitude": "34.8019", "StationCode": "1318A", "PositionName": "银行学校", "Longitude": "113.675"}, {"Latitude": "34.8020", "StationCode": "1319A", "PositionName": "供水公司", "Longitude": "113.5640"}, {"Latitude": "34.7187", "StationCode": "1320A", "PositionName": "经开区管委", "Longitude": "113.727"}, {"Latitude": "34.7190", "StationCode": "1321A", "PositionName": "四十七中", "Longitude": "113.7340"}, {"Latitude": "34.7496", "StationCode": "1322A", "PositionName": "市监测站", "Longitude": "113.5991"}, {"Latitude": "34.7538", "StationCode": "1323A", "PositionName": "河医大", "Longitude": "113.6356"}, {"Latitude": "34.9162", "StationCode": "1324A", "PositionName": "岗李水库", "Longitude": "113.6113"}], "鹤壁市": [{"Latitude": "35.9019", "StationCode": "2385A", "PositionName": "市监测站", "Longitude": "114.17"}, {"Latitude": "35.7511", "StationCode": "2386A", "PositionName": "市交警支队", "Longitude": "114.2956"}, {"Latitude": "35.7306", "StationCode": "2387A", "PositionName": "迎宾馆", "Longitude": "114.2878"}], "洛阳市": [{"Latitude": "34.6692", "StationCode": "1811A", "PositionName": "中信二小", "Longitude": "112.3628"}, {"Latitude": "34.6511", "StationCode": "1812A", "PositionName": "市委党校", "Longitude": "112.3939"}, {"Latitude": "34.6869", "StationCode": "1814A", "PositionName": "豫西宾馆", "Longitude": "112.4664"}, {"Latitude": "34.6869", "StationCode": "1815A", "PositionName": "河南林校", "Longitude": "112.4831"}, {"Latitude": "34.6231", "StationCode": "1816A", "PositionName": "开发区管委会", "Longitude": "112.3844"}, {"Latitude": "34.6258", "StationCode": "1817A", "PositionName": "市委新办公区", "Longitude": "112.4275"}, {"Latitude": "34.6686", "StationCode": "3022A", "PositionName": "凯旋路小学", "Longitude": "112.4433"}], "濮阳市": [{"Latitude": "35.763", "StationCode": "2392A", "PositionName": "环保局", "Longitude": "115.031"}, {"Latitude": "35.7672", "StationCode": "2394A", "PositionName": "油田运输公司", "Longitude": "115.0628"}, {"Latitude": "35.767", "StationCode": "2395A", "PositionName": "油田物探公司", "Longitude": "115.0772"}, {"Latitude": "35.76806", "StationCode": "3021A", "PositionName": "濮水河管理处", "Longitude": "115.0061"}], "焦作市": [{"Latitude": "35.235", "StationCode": "1827A", "PositionName": "市监测站", "Longitude": "113.261"}, {"Latitude": "35.213", "StationCode": "1828A", "PositionName": "市环保局", "Longitude": "113.227"}, {"Latitude": "35.1764", "StationCode": "1829A", "PositionName": "高新区政府", "Longitude": "113.2464"}, {"Latitude": "35.2590", "StationCode": "1830A", "PositionName": "影视城", "Longitude": "113.1992"}], "新乡市": [{"Latitude": "35.279", "StationCode": "2388A", "PositionName": "科技学院", "Longitude": "113.926"}, {"Latitude": "35.31", "StationCode": "2389A", "PositionName": "环保西院", "Longitude": "113.836"}, {"Latitude": "35.272", "StationCode": "2390A", "PositionName": "开发区", "Longitude": "113.884"}, {"Latitude": "35.303", "StationCode": "2391A", "PositionName": "环保东院", "Longitude": "113.883"}], "三门峡市": [{"Latitude": "34.7772", "StationCode": "1835A", "PositionName": "市政府", "Longitude": "111.1928"}, {"Latitude": "34.7940", "StationCode": "1836A", "PositionName": "开发区", "Longitude": "111.1580"}, {"Latitude": "34.7917", "StationCode": "1837A", "PositionName": "二 印", "Longitude": "111.1858"}, {"Latitude": "34.7997", "StationCode": "1838A", "PositionName": "风景区", "Longitude": "111.1489"}], "许昌市": [{"Latitude": "34.0117", "StationCode": "2396A", "PositionName": "监测站", "Longitude": "113.8331"}, {"Latitude": "34.0314", "StationCode": "2397A", "PositionName": "环保局", "Longitude": "113.8208"}, {"Latitude": "33.9953", "StationCode": "2398A", "PositionName": "开发区", "Longitude": "113.7906"}], "周口市": [{"Latitude": "33.6128", "StationCode": "2067A", "PositionName": "市环境监测站", "Longitude": "114.6613"}, {"Latitude": "33.6347", "StationCode": "2068A", "PositionName": "周口师范", "Longitude": "114.6758"}, {"Latitude": "33.5979", "StationCode": "2069A", "PositionName": "市运管处", "Longitude": "114.6546"}, {"Latitude": "33.6406", "StationCode": "2070A", "PositionName": "川汇区环保局", "Longitude": "114.6369"}], "信阳市": [{"Latitude": "32.1078", "StationCode": "2054A", "PositionName": "平桥分局", "Longitude": "114.1044"}, {"Latitude": "32.1403", "StationCode": "2064A", "PositionName": "南湾水厂", "Longitude": "114.0122"}, {"Latitude": "32.1342", "StationCode": "2065A", "PositionName": "市酿酒公司", "Longitude": "114.0681"}, {"Latitude": "32.1383", "StationCode": "2066A", "PositionName": "审计局", "Longitude": "114.0614"}], "平顶山市": [{"Latitude": "33.7214", "StationCode": "1831A", "PositionName": "高压开关厂", "Longitude": "113.3064"}, {"Latitude": "33.721", "StationCode": "1832A", "PositionName": "新华旅馆", "Longitude": "113.322"}, {"Latitude": "33.739", "StationCode": "1833A", "PositionName": "规划设计院", "Longitude": "113.292"}, {"Latitude": "33.737", "StationCode": "1834A", "PositionName": "平顶山工学院", "Longitude": "113.182"}], "安阳市": [{"Latitude": "36.061", "StationCode": "1818A", "PositionName": "棉研所", "Longitude": "114.483"}, {"Latitude": "36.086", "StationCode": "1819A", "PositionName": "红庙街", "Longitude": "114.3200"}, {"Latitude": "36.087", "StationCode": "1820A", "PositionName": "银杏小区", "Longitude": "114.358"}, {"Latitude": "36.0883", "StationCode": "1821A", "PositionName": "环保局", "Longitude": "114.3931"}, {"Latitude": "36.1100", "StationCode": "1822A", "PositionName": "铁佛寺", "Longitude": "114.2860"}], "漯河市": [{"Latitude": "33.567", "StationCode": "2399A", "PositionName": "三五一五工厂", "Longitude": "114.056"}, {"Latitude": "33.568", "StationCode": "2400A", "PositionName": "漯河大学", "Longitude": "114.005"}, {"Latitude": "33.581", "StationCode": "2401A", "PositionName": "水利局", "Longitude": "114.014"}, {"Latitude": "33.5653", "StationCode": "2402A", "PositionName": "广电局", "Longitude": "114.0322"}], "商丘市": [{"Latitude": "34.4286", "StationCode": "2408A", "PositionName": "环境监测站", "Longitude": "115.6697"}, {"Latitude": "34.429", "StationCode": "2409A", "PositionName": "粮食局", "Longitude": "115.6558"}, {"Latitude": "34.407", "StationCode": "2410A", "PositionName": "睢阳区环保局", "Longitude": "115.6386"}, {"Latitude": "34.402", "StationCode": "2411A", "PositionName": "第三人民医院", "Longitude": "115.6578"}]}, "19": {"汕头市": [{"Latitude": "23.3667", "StationCode": "1674A", "PositionName": "金平子站", "Longitude": "116.6794"}, {"Latitude": "23.3633", "StationCode": "1675A", "PositionName": "龙湖子站", "Longitude": "116.7244"}, {"Latitude": "23.2775", "StationCode": "1676A", "PositionName": "濠江子站", "Longitude": "116.7258"}, {"Latitude": "23.4714", "StationCode": "1677A", "PositionName": "澄海子站", "Longitude": "116.7519"}, {"Latitude": "23.2539", "StationCode": "1678A", "PositionName": "潮阳子站", "Longitude": "116.6092"}, {"Latitude": "23.2536", "StationCode": "1679A", "PositionName": "潮南子站", "Longitude": "116.4019"}], "深圳市": [{"Latitude": "22.55", "StationCode": "1356A", "PositionName": "荔园", "Longitude": "114.096"}, {"Latitude": "22.5625", "StationCode": "1357A", "PositionName": "洪湖", "Longitude": "114.117"}, {"Latitude": "22.5417", "StationCode": "1358A", "PositionName": "华侨城", "Longitude": "113.987"}, {"Latitude": "22.5167", "StationCode": "1359A", "PositionName": "南油", "Longitude": "113.923"}, {"Latitude": "22.5908", "StationCode": "1360A", "PositionName": "盐田", "Longitude": "114.263"}, {"Latitude": "22.7267", "StationCode": "1361A", "PositionName": "龙岗", "Longitude": "114.24"}, {"Latitude": "22.5794", "StationCode": "1362A", "PositionName": "西乡", "Longitude": "113.891"}, {"Latitude": "22.5422", "StationCode": "1363A", "PositionName": "南澳", "Longitude": "114.494"}, {"Latitude": "22.6342", "StationCode": "1364A", "PositionName": "葵涌", "Longitude": "114.41"}, {"Latitude": "22.5978", "StationCode": "1365A", "PositionName": "梅沙", "Longitude": "114.297"}, {"Latitude": "22.75", "StationCode": "1366A", "PositionName": "观澜", "Longitude": "114.085"}], "汕尾市": [{"Latitude": "22.775", "StationCode": "1693A", "PositionName": "市环保局", "Longitude": "115.3653"}, {"Latitude": "22.7898", "StationCode": "1694A", "PositionName": "市政府", "Longitude": "115.3706"}, {"Latitude": "22.7925", "StationCode": "1695A", "PositionName": "新城中学", "Longitude": "115.3622"}], "中山市": [{"Latitude": "22.5211", "StationCode": "1379A", "PositionName": "华柏园", "Longitude": "113.3769"}, {"Latitude": "22.5497", "StationCode": "1380A", "PositionName": "张溪", "Longitude": "113.3881"}, {"Latitude": "22.5111", "StationCode": "1381A", "PositionName": "紫马岭", "Longitude": "113.4075"}, {"Latitude": "22.4853", "StationCode": "1382A", "PositionName": "长江旅游区", "Longitude": "113.4411"}], "珠海市": [{"Latitude": "22.2611", "StationCode": "1367A", "PositionName": "吉大", "Longitude": "113.574"}, {"Latitude": "22.2294", "StationCode": "1368A", "PositionName": "前山", "Longitude": "113.495"}, {"Latitude": "22.4251", "StationCode": "1369A", "PositionName": "唐家", "Longitude": "113.628"}, {"Latitude": "22.2281", "StationCode": "1370A", "PositionName": "斗门", "Longitude": "113.299"}], "佛山市": [{"Latitude": "23.0048", "StationCode": "1371A", "PositionName": "湾梁", "Longitude": "113.134"}, {"Latitude": "23.0395", "StationCode": "1372A", "PositionName": "华材职中", "Longitude": "113.105"}, {"Latitude": "23.0467", "StationCode": "1373A", "PositionName": "南海气象局", "Longitude": "113.144"}, {"Latitude": "22.8054", "StationCode": "1374A", "PositionName": "顺德苏岗", "Longitude": "113.292"}, {"Latitude": "22.7629", "StationCode": "1375A", "PositionName": "容桂街道办", "Longitude": "113.257"}, {"Latitude": "22.8693", "StationCode": "1376A", "PositionName": "高明孔堂", "Longitude": "112.844"}, {"Latitude": "23.1572", "StationCode": "1377A", "PositionName": "三水监测站", "Longitude": "112.885"}, {"Latitude": "23.1886", "StationCode": "1378A", "PositionName": "三水云东海", "Longitude": "112.863"}], "广州市": [{"Latitude": "23.1422", "StationCode": "1345A", "PositionName": "广雅中学", "Longitude": "113.235"}, {"Latitude": "23.105", "StationCode": "1346A", "PositionName": "市五中", "Longitude": "113.261"}, {"Latitude": "23.0916", "StationCode": "1348A", "PositionName": "广东商学院", "Longitude": "113.348"}, {"Latitude": "23.105", "StationCode": "1349A", "PositionName": "市八十六中", "Longitude": "113.433"}, {"Latitude": "22.9477", "StationCode": "1350A", "PositionName": "番禺中学", "Longitude": "113.352"}, {"Latitude": "23.3917", "StationCode": "1351A", "PositionName": "花都师范", "Longitude": "113.215"}, {"Latitude": "23.1331", "StationCode": "1352A", "PositionName": "市监测站", "Longitude": "113.26"}, {"Latitude": "23.2783", "StationCode": "1353A", "PositionName": "九龙镇镇龙", "Longitude": "113.568"}, {"Latitude": "23.1569", "StationCode": "1354A", "PositionName": "麓湖", "Longitude": "113.281"}, {"Latitude": "23.5538", "StationCode": "1355A", "PositionName": "帽峰山森林公园", "Longitude": "113.589"}, {"Latitude": "23.1323", "StationCode": "2846A", "PositionName": "体育西", "Longitude": "113.3208"}], "茂名市": [{"Latitude": "21.4689", "StationCode": "1686A", "PositionName": "市环保局茂港分局", "Longitude": "111.0286"}, {"Latitude": "21.6533", "StationCode": "1687A", "PositionName": "茂石化七小", "Longitude": "110.9294"}, {"Latitude": "21.6669", "StationCode": "1688A", "PositionName": "健康路", "Longitude": "110.9067"}, {"Latitude": "21.6828", "StationCode": "1689A", "PositionName": "高岭", "Longitude": "110.8592"}], "湛江市": [{"Latitude": "21.2706", "StationCode": "1680A", "PositionName": "湛江影剧院", "Longitude": "110.3539"}, {"Latitude": "21.2228", "StationCode": "1681A", "PositionName": "市环境监测站", "Longitude": "110.3928"}, {"Latitude": "21.1997", "StationCode": "1682A", "PositionName": "环保局宿舍", "Longitude": "110.4019"}, {"Latitude": "21.2028", "StationCode": "1683A", "PositionName": "霞山游泳场", "Longitude": "110.4111"}, {"Latitude": "21.2679", "StationCode": "1684A", "PositionName": "麻章区环保局", "Longitude": "110.3316"}, {"Latitude": "21.2567", "StationCode": "1685A", "PositionName": "坡头区环保局", "Longitude": "110.4558"}], "梅州市": [{"Latitude": "24.3289", "StationCode": "1690A", "PositionName": "嘉应大学", "Longitude": "116.1278"}, {"Latitude": "24.2719", "StationCode": "1691A", "PositionName": "梅县新城", "Longitude": "116.0797"}, {"Latitude": "24.2654", "StationCode": "1692A", "PositionName": "环境监控中心", "Longitude": "116.1248"}], "揭阳市": [{"Latitude": "23.5353", "StationCode": "1708A", "PositionName": "新兴", "Longitude": "116.3697"}, {"Latitude": "23.5486", "StationCode": "1709A", "PositionName": "西马", "Longitude": "116.3242"}, {"Latitude": "23.5739", "StationCode": "1710A", "PositionName": "东兴", "Longitude": "116.3594"}, {"Latitude": "23.5292", "StationCode": "1711A", "PositionName": "渔湖", "Longitude": "116.4094"}], "清远市": [{"Latitude": "23.6936", "StationCode": "1702A", "PositionName": "环保大楼", "Longitude": "113.0425"}, {"Latitude": "23.7106", "StationCode": "1703A", "PositionName": "凤城街办", "Longitude": "113.0208"}, {"Latitude": "23.63444", "StationCode": "3025A", "PositionName": "技师学院", "Longitude": "113.0472"}], "韶关市": [{"Latitude": "24.769519", "StationCode": "1669A", "PositionName": "市八中", "Longitude": "113.586606"}, {"Latitude": "24.81119444", "StationCode": "1670A", "PositionName": "碧湖山庄", "Longitude": "113.5593889"}, {"Latitude": "24.795928", "StationCode": "1671A", "PositionName": "园林处", "Longitude": "113.598061"}, {"Latitude": "24.77908333", "StationCode": "1672A", "PositionName": "韶关学院", "Longitude": "113.6734722"}, {"Latitude": "24.68636111", "StationCode": "1673A", "PositionName": "曲江监测站", "Longitude": "113.5970833"}], "阳江市": [{"Latitude": "21.8586", "StationCode": "1699A", "PositionName": "鸳鸯湖", "Longitude": "111.9786"}, {"Latitude": "21.8536", "StationCode": "1700A", "PositionName": "南恩路", "Longitude": "111.9508"}, {"Latitude": "21.8650", "StationCode": "1701A", "PositionName": "马南垌", "Longitude": "111.9494"}], "云浮市": [{"Latitude": "22.9169", "StationCode": "1712A", "PositionName": "新市府", "Longitude": "112.0392"}, {"Latitude": "22.9394", "StationCode": "1713A", "PositionName": "市监测站", "Longitude": "112.0369"}, {"Latitude": "22.9539", "StationCode": "1714A", "PositionName": "牧羊", "Longitude": "112.0539"}], "肇庆市": [{"Latitude": "23.0706", "StationCode": "1397A", "PositionName": "睦岗子站", "Longitude": "112.427"}, {"Latitude": "23.0528", "StationCode": "1398A", "PositionName": "城中子站", "Longitude": "112.471"}, {"Latitude": "23.1617", "StationCode": "1399A", "PositionName": "坑口子站", "Longitude": "112.565"}, {"Latitude": "23.0786", "StationCode": "1400A", "PositionName": "七星岩子站", "Longitude": "112.4722"}], "河源市": [{"Latitude": "23.7569", "StationCode": "1696A", "PositionName": "源西", "Longitude": "114.6778"}, {"Latitude": "23.7586", "StationCode": "1697A", "PositionName": "东埔", "Longitude": "114.6944"}, {"Latitude": "23.7233", "StationCode": "1698A", "PositionName": "老城", "Longitude": "114.6892"}], "惠州市": [{"Latitude": "23.0528", "StationCode": "1392A", "PositionName": "河南岸金山湖子站", "Longitude": "114.4183"}, {"Latitude": "23.0800", "StationCode": "1393A", "PositionName": "下埔横江三路子站", "Longitude": "114.4053"}, {"Latitude": "23.1142", "StationCode": "1394A", "PositionName": "江北云山西路子站", "Longitude": "114.4103"}, {"Latitude": "22.8172", "StationCode": "1395A", "PositionName": "惠阳区承修路船湖子站", "Longitude": "114.3244"}, {"Latitude": "22.7422", "StationCode": "1396A", "PositionName": "大亚湾管委会子站", "Longitude": "114.5317"}], "潮州市": [{"Latitude": "23.6714", "StationCode": "1705A", "PositionName": "西园路", "Longitude": "116.6339"}, {"Latitude": "23.6706", "StationCode": "1706A", "PositionName": "档案局", "Longitude": "116.6447"}, {"Latitude": "23.65889", "StationCode": "3026A", "PositionName": "市政府", "Longitude": "116.6183"}], "江门市": [{"Latitude": "22.6069", "StationCode": "1383A", "PositionName": "北街", "Longitude": "113.104"}, {"Latitude": "22.5811", "StationCode": "1384A", "PositionName": "西区", "Longitude": "113.074"}, {"Latitude": "22.5328", "StationCode": "1385A", "PositionName": "圭峰西", "Longitude": "113.024"}, {"Latitude": "22.5931", "StationCode": "1386A", "PositionName": "东湖", "Longitude": "113.0819"}], "东莞市": [{"Latitude": "23.05361111", "StationCode": "1387A", "PositionName": "东城主山", "Longitude": "113.7819444"}, {"Latitude": "23.02777778", "StationCode": "1388A", "PositionName": "南城元岭", "Longitude": "113.7461111"}, {"Latitude": "23.06", "StationCode": "1389A", "PositionName": "莞城梨川", "Longitude": "113.7480556"}, {"Latitude": "23.01277778", "StationCode": "1390A", "PositionName": "东城石井", "Longitude": "113.7944444"}, {"Latitude": "22.96583333", "StationCode": "1391A", "PositionName": "南城西平", "Longitude": "113.7383333"}]}, "18": {"永州市": [{"Latitude": "26.2081", "StationCode": "2477A", "PositionName": "零陵南津渡", "Longitude": "111.6217"}, {"Latitude": "26.4214", "StationCode": "2478A", "PositionName": "市环境监测站", "Longitude": "111.6156"}, {"Latitude": "26.2331", "StationCode": "2479A", "PositionName": "零陵区环保局", "Longitude": "111.6236"}, {"Latitude": "26.4364", "StationCode": "2480A", "PositionName": "永州市环保局", "Longitude": "111.5992"}, {"Latitude": "26.4519", "StationCode": "2481A", "PositionName": "冷水滩区环保局", "Longitude": "111.5989"}], "邵阳市": [{"Latitude": "27.3033", "StationCode": "2462A", "PositionName": "市水土所", "Longitude": "111.5239"}, {"Latitude": "27.2317", "StationCode": "2463A", "PositionName": "市一中", "Longitude": "111.4733"}, {"Latitude": "27.2582", "StationCode": "2464A", "PositionName": "市化工厂", "Longitude": "111.4908"}, {"Latitude": "27.2537", "StationCode": "2465A", "PositionName": "市罐头厂", "Longitude": "111.4503"}, {"Latitude": "27.2272", "StationCode": "2466A", "PositionName": "市环保局", "Longitude": "111.4328"}], "益阳市": [{"Latitude": "28.6428", "StationCode": "2467A", "PositionName": "甘溪港", "Longitude": "112.4067"}, {"Latitude": "28.5808", "StationCode": "2468A", "PositionName": "市环保局", "Longitude": "112.3458"}, {"Latitude": "28.56", "StationCode": "2469A", "PositionName": "市特殊教育学校", "Longitude": "112.3439"}, {"Latitude": "28.6047", "StationCode": "2470A", "PositionName": "资阳区政务中心", "Longitude": "112.3347"}, {"Latitude": "28.5819", "StationCode": "2471A", "PositionName": "赫山环保分局", "Longitude": "112.3744"}], "株洲市": [{"Latitude": "27.8244", "StationCode": "1515A", "PositionName": "天台山庄", "Longitude": "113.135"}, {"Latitude": "27.8867", "StationCode": "1518A", "PositionName": "株冶医院", "Longitude": "113.095"}, {"Latitude": "27.8667", "StationCode": "1519A", "PositionName": "市四中", "Longitude": "113.167"}, {"Latitude": "27.8381", "StationCode": "1520A", "PositionName": "火车站", "Longitude": "113.143"}, {"Latitude": "27.8528", "StationCode": "1524A", "PositionName": "市监测站", "Longitude": "113.1300"}, {"Latitude": "27.8336", "StationCode": "1559A", "PositionName": "大京风景区", "Longitude": "113.251"}, {"Latitude": "27.9958", "StationCode": "2031A", "PositionName": "云田中学", "Longitude": "113.1817"}], "娄底市": [{"Latitude": "27.725", "StationCode": "2487A", "PositionName": "电视发射台", "Longitude": "111.9975"}, {"Latitude": "27.725", "StationCode": "2488A", "PositionName": "市监测站", "Longitude": "111.9975"}, {"Latitude": "27.7314", "StationCode": "2489A", "PositionName": "市委党校", "Longitude": "112.0194"}, {"Latitude": "27.7569", "StationCode": "2490A", "PositionName": "涟钢", "Longitude": "111.9561"}, {"Latitude": "27.7044", "StationCode": "2491A", "PositionName": "市政府", "Longitude": "111.9892"}], "郴州市": [{"Latitude": "25.9061", "StationCode": "2472A", "PositionName": "马头岭", "Longitude": "113.0073"}, {"Latitude": "25.8226", "StationCode": "2473A", "PositionName": "市职中", "Longitude": "113.0116"}, {"Latitude": "25.8179", "StationCode": "2474A", "PositionName": "兴隆步行街", "Longitude": "113.0119"}, {"Latitude": "25.8071", "StationCode": "2475A", "PositionName": "市审计局", "Longitude": "113.0383"}, {"Latitude": "25.7759", "StationCode": "2476A", "PositionName": "市环保局", "Longitude": "113.0348"}], "张家界市": [{"Latitude": "29.1389", "StationCode": "1858A", "PositionName": "永定新区", "Longitude": "110.4800"}, {"Latitude": "29.1242", "StationCode": "1859A", "PositionName": "电业局", "Longitude": "110.4697"}, {"Latitude": "29.3547", "StationCode": "1860A", "PositionName": "未央路", "Longitude": "110.5594"}, {"Latitude": "29.3150", "StationCode": "1861A", "PositionName": "袁家界", "Longitude": "110.4417"}], "长沙市": [{"Latitude": "28.2325", "StationCode": "1335A", "PositionName": "经开区环保局", "Longitude": "113.0833"}, {"Latitude": "28.2189", "StationCode": "1336A", "PositionName": "高开区环保局", "Longitude": "112.8872"}, {"Latitude": "28.2053", "StationCode": "1337A", "PositionName": "马坡岭", "Longitude": "113.0792"}, {"Latitude": "28.1900", "StationCode": "1338A", "PositionName": "湖南师范大学", "Longitude": "112.9394"}, {"Latitude": "28.1442", "StationCode": "1339A", "PositionName": "雨花区环保局", "Longitude": "112.9956"}, {"Latitude": "28.2597", "StationCode": "1340A", "PositionName": "伍家岭", "Longitude": "112.9792"}, {"Latitude": "28.1944", "StationCode": "1341A", "PositionName": "火车新站", "Longitude": "113.0014"}, {"Latitude": "28.1178", "StationCode": "1342A", "PositionName": "天心区环保局", "Longitude": "112.9844"}, {"Latitude": "28.1308", "StationCode": "1343A", "PositionName": "湖南中医药大学", "Longitude": "112.8908"}, {"Latitude": "28.3586", "StationCode": "1344A", "PositionName": "沙坪", "Longitude": "112.9958"}], "湘潭市": [{"Latitude": "27.8614", "StationCode": "1508A", "PositionName": "板塘", "Longitude": "112.9433"}, {"Latitude": "27.8403", "StationCode": "1511A", "PositionName": "市监测站", "Longitude": "112.9118"}, {"Latitude": "27.8728", "StationCode": "1512A", "PositionName": "江麓", "Longitude": "112.8937"}, {"Latitude": "27.8159", "StationCode": "1513A", "PositionName": "岳塘", "Longitude": "112.9227"}, {"Latitude": "27.9119", "StationCode": "1514A", "PositionName": "科大", "Longitude": "112.9074"}, {"Latitude": "27.9153", "StationCode": "1562A", "PositionName": "昭山", "Longitude": "113.0048"}, {"Latitude": "27.9164", "StationCode": "1564A", "PositionName": "韶山", "Longitude": "112.4876"}], "衡阳市": [{"Latitude": "26.9089", "StationCode": "2456A", "PositionName": "原169医院", "Longitude": "112.5328"}, {"Latitude": "26.9258", "StationCode": "2457A", "PositionName": "衡阳化工总厂", "Longitude": "112.6194"}, {"Latitude": "26.8956", "StationCode": "2458A", "PositionName": "珠晖区环保局", "Longitude": "112.6211"}, {"Latitude": "26.8733", "StationCode": "2459A", "PositionName": "市委党校", "Longitude": "112.6197"}, {"Latitude": "26.8919", "StationCode": "2460A", "PositionName": "市监测站", "Longitude": "112.6006"}, {"Latitude": "26.9056", "StationCode": "2461A", "PositionName": "真空机电公司", "Longitude": "112.5664"}], "怀化市": [{"Latitude": "27.5733", "StationCode": "2482A", "PositionName": "林科所", "Longitude": "109.9333"}, {"Latitude": "27.5444", "StationCode": "2483A", "PositionName": "河西地税局", "Longitude": "109.9453"}, {"Latitude": "27.5342", "StationCode": "2484A", "PositionName": "市四医院", "Longitude": "109.9792"}, {"Latitude": "27.5578", "StationCode": "2485A", "PositionName": "监测楼", "Longitude": "109.9972"}, {"Latitude": "27.583", "StationCode": "2486A", "PositionName": "市委党校", "Longitude": "110.0394"}], "湘西州": [{"Latitude": "28.2558", "StationCode": "2492A", "PositionName": "跃进水库", "Longitude": "109.6414"}, {"Latitude": "28.3169", "StationCode": "2493A", "PositionName": "州政府", "Longitude": "109.7325"}, {"Latitude": "28.2675", "StationCode": "2494A", "PositionName": "吉首市计生局", "Longitude": "109.6958"}], "常德市": [{"Latitude": "29.0244", "StationCode": "1853A", "PositionName": "市监测站", "Longitude": "111.7044"}, {"Latitude": "28.9703", "StationCode": "1854A", "PositionName": "市二中", "Longitude": "111.6975"}, {"Latitude": "29.0239", "StationCode": "1855A", "PositionName": "鼎城区环保局", "Longitude": "111.6753"}, {"Latitude": "29.0381", "StationCode": "1856A", "PositionName": "市技术监督局", "Longitude": "111.6794"}, {"Latitude": "29.1456", "StationCode": "1857A", "PositionName": "白鹤山", "Longitude": "111.7158"}], "岳阳市": [{"Latitude": "29.3578", "StationCode": "1847A", "PositionName": "南湖风景区", "Longitude": "113.1094"}, {"Latitude": "29.4251", "StationCode": "1848A", "PositionName": "城陵矶", "Longitude": "113.1493"}, {"Latitude": "29.3678", "StationCode": "1849A", "PositionName": "开发区", "Longitude": "113.1772"}, {"Latitude": "29.4758", "StationCode": "1850A", "PositionName": "云溪区", "Longitude": "113.2621"}, {"Latitude": "29.4402", "StationCode": "1851A", "PositionName": "君山区", "Longitude": "112.9943"}, {"Latitude": "29.3550", "StationCode": "1852A", "PositionName": "金凤水库", "Longitude": "113.2117"}]}, "31": {"哈密地区": [{"Latitude": "42.8172", "StationCode": "2688A", "PositionName": "地区监测站", "Longitude": "93.5128"}, {"Latitude": "42.8328", "StationCode": "2689A", "PositionName": "哈密师范学校", "Longitude": "93.4961"}], "乌鲁木齐市": [{"Latitude": "43.8303", "StationCode": "1490A", "PositionName": "监测站", "Longitude": "87.5801"}, {"Latitude": "43.768", "StationCode": "1491A", "PositionName": "收费所", "Longitude": "87.6046"}, {"Latitude": "43.9469", "StationCode": "1492A", "PositionName": "新疆农科院农场", "Longitude": "87.4754"}, {"Latitude": "43.8711", "StationCode": "1493A", "PositionName": "铁路局", "Longitude": "87.5525"}, {"Latitude": "43.831", "StationCode": "1494A", "PositionName": "三十一中学", "Longitude": "87.6432"}, {"Latitude": "43.8729", "StationCode": "1495A", "PositionName": "七十四中学", "Longitude": "87.4171"}, {"Latitude": "43.962", "StationCode": "1496A", "PositionName": "米东区环保局", "Longitude": "87.6444"}], "石河子市": [{"Latitude": "44.2967", "StationCode": "2709A", "PositionName": "艾青诗歌馆", "Longitude": "86.0497"}, {"Latitude": "44.3075", "StationCode": "2710A", "PositionName": "阳光学校", "Longitude": "86.0697"}], "阿勒泰地区": [{"Latitude": "47.9047", "StationCode": "2707A", "PositionName": "小东沟", "Longitude": "88.1214"}, {"Latitude": "47.8515", "StationCode": "2708A", "PositionName": "市站", "Longitude": "88.1267"}], "塔城地区": [{"Latitude": "46.7432", "StationCode": "2706A", "PositionName": "东门外小游园", "Longitude": "82.9994"}], "吐鲁番地区": [{"Latitude": "42.9409", "StationCode": "2686A", "PositionName": "市环保局", "Longitude": "89.191"}, {"Latitude": "42.9559", "StationCode": "2687A", "PositionName": "地区环保局", "Longitude": "89.1673"}], "克州": [{"Latitude": "39.7153", "StationCode": "2697A", "PositionName": "市人民政府", "Longitude": "76.1861"}], "和田地区": [{"Latitude": "37.1152", "StationCode": "2701A", "PositionName": "地区站", "Longitude": "79.9485"}, {"Latitude": "37.1013", "StationCode": "2702A", "PositionName": "古江巴格乡院内", "Longitude": "79.9117"}], "博州": [{"Latitude": "44.9079", "StationCode": "2693A", "PositionName": "博乐市西郊区", "Longitude": "82.0485"}, {"Latitude": "44.8969", "StationCode": "2694A", "PositionName": "市环保局", "Longitude": "82.0806"}], "喀什地区": [{"Latitude": "39.5371", "StationCode": "2698A", "PositionName": "巡警大队", "Longitude": "75.9828"}, {"Latitude": "39.4699", "StationCode": "2699A", "PositionName": "吾办", "Longitude": "75.9771"}, {"Latitude": "39.4365", "StationCode": "2700A", "PositionName": "市环境监测站", "Longitude": "75.9435"}], "库尔勒市": [{"Latitude": "41.7511", "StationCode": "1956A", "PositionName": "孔雀公园", "Longitude": "86.1461"}, {"Latitude": "41.7192", "StationCode": "1957A", "PositionName": "棉纺厂", "Longitude": "86.2022"}, {"Latitude": "41.7128", "StationCode": "1958A", "PositionName": "经济开发区", "Longitude": "86.2381"}], "昌吉州": [{"Latitude": "44.1564", "StationCode": "2690A", "PositionName": "天山天池", "Longitude": "87.9897"}, {"Latitude": "44.0114", "StationCode": "2691A", "PositionName": "州监测站", "Longitude": "87.2997"}, {"Latitude": "44.0297", "StationCode": "2692A", "PositionName": "新区政务中心", "Longitude": "87.2717"}], "克拉玛依市": [{"Latitude": "45.6033", "StationCode": "1951A", "PositionName": "长征新村", "Longitude": "84.8861"}, {"Latitude": "45.5828", "StationCode": "1952A", "PositionName": "南林小区", "Longitude": "84.8897"}, {"Latitude": "45.6886", "StationCode": "1953A", "PositionName": "白碱滩区", "Longitude": "85.1186"}, {"Latitude": "44.3336", "StationCode": "1954A", "PositionName": "独山子区", "Longitude": "84.8983"}, {"Latitude": "46.0872", "StationCode": "1955A", "PositionName": "乌尔禾区商贸楼", "Longitude": "85.6931"}], "五家渠市": [{"Latitude": "44.1756", "StationCode": "2711A", "PositionName": "农水大厦", "Longitude": "87.5475"}], "阿克苏地区": [{"Latitude": "41.1636", "StationCode": "2695A", "PositionName": "电视台", "Longitude": "80.2828"}, {"Latitude": "41.1933", "StationCode": "2696A", "PositionName": "艺术中心", "Longitude": "80.2956"}]}, "30": {"石嘴山市": [{"Latitude": "38.8170", "StationCode": "1947A", "PositionName": "沙湖旅游区", "Longitude": "106.3394"}, {"Latitude": "39.0153", "StationCode": "1948A", "PositionName": "大武口黄河东街", "Longitude": "106.3717"}, {"Latitude": "39.2282", "StationCode": "1949A", "PositionName": "惠农南大街", "Longitude": "106.7704"}, {"Latitude": "39.1292", "StationCode": "1950A", "PositionName": "红果子镇惠新街", "Longitude": "106.7096"}], "固原市": [{"Latitude": "36.1417", "StationCode": "2683A", "PositionName": "马园", "Longitude": "106.2319"}, {"Latitude": "36.0022", "StationCode": "2684A", "PositionName": "监测站", "Longitude": "106.2792"}, {"Latitude": "36.0211", "StationCode": "2685A", "PositionName": "新区", "Longitude": "106.2375"}], "银川市": [{"Latitude": "38.6016", "StationCode": "1484A", "PositionName": "贺兰山马莲口", "Longitude": "105.9512"}, {"Latitude": "38.4975", "StationCode": "1488A", "PositionName": "贺兰山东路", "Longitude": "106.2328"}, {"Latitude": "38.5036", "StationCode": "1489A", "PositionName": "学院路", "Longitude": "106.1358"}, {"Latitude": "38.44139", "StationCode": "2924A", "PositionName": "水乡路(直管站)", "Longitude": "106.2275"}, {"Latitude": "38.4841", "StationCode": "2925A", "PositionName": "上海东路", "Longitude": "106.2739"}, {"Latitude": "38.49494", "StationCode": "2926A", "PositionName": "文昌北街", "Longitude": "106.1024"}], "吴忠市": [{"Latitude": "37.9648", "StationCode": "2677A", "PositionName": "教育园区", "Longitude": "106.1532"}, {"Latitude": "37.9844", "StationCode": "2678A", "PositionName": "高级中学", "Longitude": "106.2025"}, {"Latitude": "37.9723", "StationCode": "2679A", "PositionName": "新区二泵站", "Longitude": "106.196"}], "中卫市": [{"Latitude": "37.4514", "StationCode": "2680A", "PositionName": "沙坡头消防站", "Longitude": "105.0197"}, {"Latitude": "37.0172", "StationCode": "2681A", "PositionName": "官桥站", "Longitude": "105.18"}, {"Latitude": "37.5002", "StationCode": "2682A", "PositionName": "环保局站", "Longitude": "105.1971"}]}}'
cityList_json = {"659001": "石河子市", "610400": "咸阳市", "511500": "宜宾市", "632600": "果洛州", "110000": "北京市", "320300": "徐州市", "230200": "齐齐哈尔市", "620400": "白银市", "632100": "海东地区", "130500": "邢台市", "370400": "枣庄市", "653100": "喀什地区", "341600": "亳州市", "441600": "河源市", "330100": "杭州市", "632200": "海北州", "621100": "定西市", "410900": "濮阳市", "440200": "韶关市", "542100": "昌都地区", "512000": "资阳市", "533321": "怒江州", "370800": "济宁市", "360800": "吉安市", "211100": "盘锦市", "410700": "新乡市", "659004": "五家渠市", "511100": "乐山市", "340200": "芜湖市", "510700": "绵阳市", "210500": "本溪市", "522700": "黔南州", "130100": "石家庄市", "371400": "德州市", "632700": "玉树州", "652300": "昌吉州", "430400": "衡阳市", "632800": "海西州", "341200": "阜阳市", "130900": "沧州市", "140300": "阳泉市", "150700": "呼伦贝尔市", "441800": "清远市", "652200": "哈密地区", "431000": "郴州市", "430200": "株洲市", "620500": "天水市", "511800": "雅安市", "341800": "宣城市", "640200": "石嘴山市", "130800": "承德市", "532801": "西双版纳州", "152500": "锡林郭勒盟", "340100": "合肥市", "350100": "福州市", "421300": "随州市", "640100": "银川市", "511600": "广安市", "652900": "阿克苏地区", "411700": "驻马店市", "230700": "伊春市", "360400": "九江市", "513300": "甘孜州", "620100": "兰州市", "533421": "迪庆州", "320700": "连云港市", "210200": "大连市", "652700": "博州", "150900": "乌兰察布市", "420900": "孝感市", "440400": "珠海市", "620900": "酒泉市", "450200": "柳州市", "310000": "上海市", "131200": "张家口市", "420100": "武汉市", "451300": "来宾市", "211300": "朝阳市", "340500": "马鞍山市", "430600": "岳阳市", "520400": "安顺市", "542500": "阿里地区", "630100": "西宁市", "420500": "宜昌市", "632500": "海南州", "640400": "固原市", "130400": "邯郸市", "350900": "宁德市", "640300": "吴忠市", "654300": "阿勒泰地区", "370700": "潍坊市", "330400": "嘉兴市", "140800": "运城市", "451000": "百色市", "440900": "茂名市", "360100": "南昌市", "652800": "库尔勒市", "610300": "宝鸡市", "440100": "广州市", "610500": "渭南市", "620200": "嘉峪关市", "350600": "漳州市", "460200": "三亚市", "621200": "陇南市", "340300": "蚌埠市", "445200": "揭阳市", "220400": "辽源市", "371100": "日照市", "210600": "丹东市", "231000": "牡丹江市", "230100": "哈尔滨市", "620700": "张掖市", "341100": "滁州市", "130300": "秦皇岛市", "441900": "东莞市", "140400": "长治市", "360900": "宜春市", "320400": "常州市", "211000": "辽阳市", "150300": "乌海市", "321300": "宿迁市", "410400": "平顶山市", "440700": "江门市", "340800": "安庆市", "230300": "鸡西市", "433100": "湘西州", "232700": "大兴安岭地区", "522600": "黔东南州", "331300": "绍兴市", "520300": "遵义市", "422800": "恩施州", "533103": "德宏州", "511700": "达州市", "411600": "周口市", "522200": "铜仁地区", "360500": "新余市", "460100": "海口市", "150600": "鄂尔多斯市", "441200": "肇庆市", "371600": "滨州市", "370200": "青岛市", "532522": "红河州", "420800": "荆门市", "430800": "张家界市", "340600": "淮北市", "450300": "桂林市", "440300": "深圳市", "450700": "钦州市", "410200": "开封市", "530900": "临沧市", "450500": "北海市", "421000": "荆州市", "371700": "菏泽市", "513400": "凉山州", "440500": "汕头市", "540100": "拉萨市", "140700": "晋中市", "411200": "三门峡市", "330500": "湖州市", "542300": "日喀则地区", "210300": "鞍山市", "411300": "南阳市", "530500": "保山市", "640500": "中卫市", "211400": "葫芦岛市", "510500": "泸州市", "140900": "忻州市", "441400": "梅州市", "330700": "金华市", "440800": "湛江市", "654200": "塔城地区", "150100": "呼和浩特市", "230400": "鹤岗市", "450800": "贵港市", "430300": "湘潭市", "520200": "六盘水市", "431200": "怀化市", "442000": "中山市", "410100": "郑州市", "610600": "延安市", "511300": "南充市", "231200": "绥化市", "350500": "泉州市", "371000": "威海市", "320900": "盐城市", "371200": "莱芜市", "370600": "烟台市", "610700": "汉中市", "411400": "商丘市", "420700": "鄂州市", "341000": "黄山市", "230600": "大庆市", "623000": "甘南州", "140100": "太原市", "510900": "遂宁市", "220800": "白城市", "230800": "佳木斯市", "330900": "舟山市", "530400": "玉溪市", "320500": "苏州市", "510100": "成都市", "150200": "包头市", "321200": "泰州市", "420600": "襄阳市", "371500": "聊城市", "220300": "四平市", "361100": "上饶市", "220600": "白山市", "430500": "邵阳市", "450900": "玉林市", "210700": "锦州市", "350300": "莆田市", "331000": "台州市", "152200": "兴安盟", "410500": "安阳市", "330300": "温州市", "451400": "崇左市", "210800": "营口市", "360200": "景德镇市", "653000": "克州", "620300": "金昌市", "321100": "镇江市", "130600": "保定市", "652100": "吐鲁番地区", "370500": "东营市", "440600": "佛山市", "450400": "梧州市", "610100": "西安市", "131000": "廊坊市", "231100": "黑河市", "410300": "洛阳市", "530800": "普洱市", "141100": "吕梁市", "340700": "铜陵市", "350700": "南平市", "421100": "黄冈市", "622900": "临夏州", "532621": "文山州", "522300": "黔西南州", "152900": "阿拉善盟", "140500": "晋城市", "411100": "漯河市", "441300": "惠州市", "360600": "鹰潭市", "320100": "南京市", "210400": "抚顺市", "542400": "那曲地区", "650100": "乌鲁木齐市", "430900": "益阳市", "371300": "临沂市", "341700": "池州市", "654000": "伊犁哈萨克州", "530600": "昭通市", "430700": "常德市", "620600": "武威市", "361000": "抚州市", "410800": "焦作市", "610800": "榆林市", "451100": "贺州市", "511400": "眉山市", "510400": "攀枝花市", "621000": "庆阳市", "320200": "无锡市", "222400": "延边州", "445300": "云浮市", "370300": "淄博市", "130200": "唐山市", "431300": "娄底市", "441500": "汕尾市", "500000": "重庆市", "420200": "黄石市", "230500": "双鸭山市", "542600": "林芝地区", "510800": "广元市", "220200": "吉林市", "230900": "七台河市", "140200": "大同市", "330800": "衢州市", "532301": "楚雄州", "150800": "巴彦淖尔市", "370900": "泰安市", "451200": "河池市", "220100": "长春市", "410600": "鹤壁市", "350400": "三明市", "511000": "内江市", "611000": "商洛市", "370100": "济南市", "450600": "防城港市", "610900": "安康市", "510600": "德阳市", "120000": "天津市", "542200": "山南地区", "341300": "宿州市", "210900": "阜新市", "220700": "松原市", "360300": "萍乡市", "510300": "自贡市", "150400": "赤峰市", "522400": "毕节市", "321000": "扬州市", "513200": "阿坝州", "431100": "永州市", "511900": "巴中市", "150500": "通辽市", "520100": "贵阳市", "530100": "昆明市", "131100": "衡水市", "632300": "黄南州", "610200": "铜川市", "350200": "厦门市", "653200": "和田地区", "331100": "丽水市", "220500": "通化市", "421200": "咸宁市", "330200": "宁波市", "530300": "曲靖市", "445100": "潮州市", "430100": "长沙市", "350800": "龙岩市", "411000": "许昌市", "320800": "淮安市", "360700": "赣州市", "140600": "朔州市", "210100": "沈阳市", "341500": "六安市", "320600": "南通市", "530700": "丽江市", "420300": "十堰市", "211200": "铁岭市", "650200": "克拉玛依市", "620800": "平凉市", "450100": "南宁市", "411500": "信阳市", "532901": "大理州", "141000": "临汾市", "441700": "阳江市", "340400": "淮南市"}
|
# -*- coding: utf-8 -*-
import collections
from lexical_analyzer_helpers import *
def get_top_words_in_path(path, name_type, speech_part, top_size=10):
if name_type not in ["variable", "function_definition"]:
raise ValueError(name_type + " not supported. Available types: [variable, function_definition]")
if speech_part not in ["noun", "verb"]:
raise ValueError(speech_part + " not supported. Available types: [noun, verb]")
if name_type == "variable":
names = get_all_words_in_path(path, get_all_variables_names)
else:
names = get_all_words_in_path(path, get_all_function_names)
if speech_part == "noun":
words = flat([split_snake_case_name_to_words(name, is_noun) for name in names])
else:
words = flat([split_snake_case_name_to_words(name, is_verb) for name in names])
return collections.Counter(words).most_common(top_size)
def get_top_verbs_in_function_names(path, top_size=10):
return get_top_words_in_path(path, name_type="function_definition", speech_part="verb", top_size=top_size)
def get_top_nouns_in_function_names(path, top_size=10):
return get_top_words_in_path(path, name_type="function_definition", speech_part="noun", top_size=top_size)
def get_top_verbs_in_variable_names(path, top_size=10):
return get_top_words_in_path(path, name_type="variable", speech_part="verb", top_size=top_size)
def get_top_nouns_in_variable_names(path, top_size=10):
return get_top_words_in_path(path, name_type="variable", speech_part="noun", top_size=top_size)
def get_top_for_projects_in_path(projects_path, projects, top_function, top_size=10):
top_words = {}
for project in projects:
full_path = os.path.join(projects_path, project)
top = top_function(full_path, top_size=top_size)
top_words = sum_occurrence(top_words, top)
top_words_list = []
for word in top_words:
top_words_list.append((word, top_words[word]))
return top_words_list
def speech_part_is_supported(speech_part):
return speech_part in ["verb", "noun"]
def name_type_is_supported(names_type):
return names_type in ["function_definition", "variable"]
|
import decimal
D = decimal.Decimal
decimal.getcontext().prec = 16
dq = D(".00000001")
df = D(".1")
du = D(".001")
currencies = ['ltc', 'usd', 'lsd']
def priceConv(price, typ):
if typ == 1:
return D(str(price)) * D('100000000')
else:
return D(str(price)) / D('100000000')
#
#
# Current string format:
# price : quantity : price_w_fee : market_name : time : ( for usd) inverted price : inverted quantity
#
#
# takes an array of strings and packs them into the
# format "sargs1:sargs2:sargs3:..."
def stringPack(sargs):
return ":".join(map(str,sargs))
###################################################################
###################################################################
# fee structurce:
# we take in the decimal price, decimal quantity
# we check our fee variable from the market,
# then we compute the total after fee's and return that amount
# in the btc-e case as an example it takes .2% of the transaction
# so we will instead return a quantity?
# eg buying ltc from btc, btc-e takes an amount off the ltc you buy.
# These give the changed QUANTITY back and is actually what markets
# will do. The common way we will look at these is expecting
# the exchange to take a cut in the primary currency only
# so for ltc/btc it will only take cut out of the BTC side
# so going btc -> ltc we pay higher btc price but get full ltc amount
# going ltc -> btc again we lose out on BTC quantity not ltc.
# some exchanges do this differently though so they need their
# own functions to convert to this standard.
#
# This is what it costs to FILL a bid quote for us.
def BuyFee(array, fee):
price = array[0]
quantity = array[1]
btc_flat = price * quantity
btc_fee = btc_flat * fee
return btc_fee
# The loss that goes from selling for example LTC -> BTC
# how much btc we actually get
def SellFee(array, fee):
price = array[0]
quantity = array[1]
btc_flat = price * quantity
btc_fee = btc_flat / fee
return btc_fee
# The Bid/Ask-FeePrice is the actual price that it would cost
# us to fill. This is just looking at cost. Different markets
# actually subtract the fee's differently from the quantity and
# do not actually effect the price at all.
# This should return the price after fee
def BidFeePrice(array, fee):
price = array[0]
quantity = array[1]
idx = array[2]
newq = price / fee
return [newq , quantity, idx]
# for ask
def AskFeePrice(array, fee):
price = array[0]
quantity = array[1]
idx = array[2]
return [(price * fee), quantity, idx]
# in case we do not use the particular pair, or we error
def NullPrice():
return [D('999999'),D('0'), 0], [D('0'),D('0'), 0]
#
# Inverting section
#
# for example, the btc/usd is not the format that we normally
# use as we have written this in a 'base' btc format, eg: ltc/btc
# using btc/usd with usd as the base confuses our algos. so
# in the case where btc is not the base we must adjust.
# changes from btc/usd to usd/btc assuming this:
# price * btc = usd
# --> btc = usd / price
# will return the new 'quantity' which is
# the amount which is the 'usd' portion
# while the price is now 1/price
def invertBase(price, quantity):
# first we calculate usd, our new quantity
usd = price * quantity
# now we get the new price
p2 = 1 / price
return [p2, usd]
# reverses the above transform
# this is to go back for actually placing orders and interacting
# with exchanges API's
def revertBase(price, quantity):
# this is the original price
p1 = 1 / price
# this is the original quantity
btc = quantity / p1
return [p1, btc]
|
# for i in range(4):
# if i == 3:
# print('有3')
# break
# else:
# print('111')
# class Person:
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def say(self):
# print('我是{},今年{}岁'.format(self.name, self.age))
# class Student(Person):
# def __init__(self, name, age, grade):
# self.grade = grade
# super().__init__(name, age)
# def say(self):
# super().say()
# print('我正在上{}年级'.format(self.grade))
# s = Student('harry', 20, 5)
# s.say()
# 单例模式
class A:
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
return cls.__instance
def __init__(self, name):
self.name = name
@classmethod
def show(cls):
print(cls.__instance)
a = A('hello')
print(dir(a))
a.show()
b = A('world')
b.show()
|
# -*- coding: utf-8 -*-
'''
File name: code\silver_dollar_game\sol_344.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #344 :: Silver dollar game
#
# For more information see:
# https://projecteuler.net/problem=344
# Problem Statement
'''
One variant of N.G. de Bruijn's silver dollar game can be described as follows:
On a strip of squares a number of coins are placed, at most one coin per square. Only one coin, called the silver dollar, has any value. Two players take turns making moves. At each turn a player must make either a regular or a special move.
A regular move consists of selecting one coin and moving it one or more squares to the left. The coin cannot move out of the strip or jump on or over another coin.
Alternatively, the player can choose to make the special move of pocketing the leftmost coin rather than making a regular move. If no regular moves are possible, the player is forced to pocket the leftmost coin.
The winner is the player who pockets the silver dollar.
A winning configuration is an arrangement of coins on the strip where the first player can force a win no matter what the second player does.
Let W(n,c) be the number of winning configurations for a strip of n squares, c worthless coins and one silver dollar.
You are given that W(10,2) = 324 and W(100,10) = 1514704946113500.
Find W(1 000 000, 100) modulo the semiprime 1000 036 000 099 (= 1 000 003 · 1 000 033).
'''
# Solution
# Solution Approach
'''
'''
|
# coding=utf-8
"""
remind.py - Sopel Reminder Module
Copyright 2011, Sean B. Palmer, inamidst.com
Licensed under the Eiffel Forum License 2.
https://sopel.chat
"""
from __future__ import unicode_literals, absolute_import, print_function, division
import os
import re
import time
import threading
import collections
import codecs
from datetime import datetime
from sopel.module import commands, example, NOLIMIT
import sopel.tools
from sopel.tools.time import get_timezone, format_time
try:
import pytz
except ImportError:
pytz = None
def filename(self):
name = self.nick + '-' + self.config.core.host + '.reminders.db'
return os.path.join(self.config.core.homedir, name)
def load_database(name):
data = {}
if os.path.isfile(name):
f = codecs.open(name, 'r', encoding='utf-8')
for line in f:
unixtime, channel, nick, message = line.split('\t')
message = message.rstrip('\n')
t = int(float(unixtime)) # WTFs going on here?
reminder = (channel, nick, message)
try:
data[t].append(reminder)
except KeyError:
data[t] = [reminder]
f.close()
return data
def dump_database(name, data):
f = codecs.open(name, 'w', encoding='utf-8')
for unixtime, reminders in sopel.tools.iteritems(data):
for channel, nick, message in reminders:
f.write('%s\t%s\t%s\t%s\n' % (unixtime, channel, nick, message))
f.close()
def setup(bot):
bot.rfn = filename(bot)
bot.rdb = load_database(bot.rfn)
def monitor(bot):
time.sleep(5)
while True:
now = int(time.time())
unixtimes = [int(key) for key in bot.rdb]
oldtimes = [t for t in unixtimes if t <= now]
if oldtimes:
for oldtime in oldtimes:
for (channel, nick, message) in bot.rdb[oldtime]:
if message:
bot.msg(channel, nick + ': ' + message)
else:
bot.msg(channel, nick + '!')
del bot.rdb[oldtime]
dump_database(bot.rfn, bot.rdb)
time.sleep(2.5)
targs = (bot,)
t = threading.Thread(target=monitor, args=targs)
t.start()
scaling = collections.OrderedDict([
('years', 365.25 * 24 * 3600),
('year', 365.25 * 24 * 3600),
('yrs', 365.25 * 24 * 3600),
('y', 365.25 * 24 * 3600),
('months', 29.53059 * 24 * 3600),
('month', 29.53059 * 24 * 3600),
('mo', 29.53059 * 24 * 3600),
('weeks', 7 * 24 * 3600),
('week', 7 * 24 * 3600),
('wks', 7 * 24 * 3600),
('wk', 7 * 24 * 3600),
('w', 7 * 24 * 3600),
('days', 24 * 3600),
('day', 24 * 3600),
('d', 24 * 3600),
('hours', 3600),
('hour', 3600),
('hrs', 3600),
('hr', 3600),
('h', 3600),
('minutes', 60),
('minute', 60),
('mins', 60),
('min', 60),
('m', 60),
('seconds', 1),
('second', 1),
('secs', 1),
('sec', 1),
('s', 1),
])
periods = '|'.join(scaling.keys())
@commands('in')
@example('.in 3h45m Go to class')
def remind(bot, trigger):
"""Gives you a reminder in the given amount of time."""
if not trigger.group(2):
bot.say("Missing arguments for reminder command.")
return NOLIMIT
if trigger.group(3) and not trigger.group(4):
bot.say("No message given for reminder.")
return NOLIMIT
duration = 0
message = filter(None, re.split(r'(\d+(?:\.\d+)? ?(?:(?i)' + periods + ')) ?',
trigger.group(2))[1:])
reminder = ''
stop = False
for piece in message:
grp = re.match(r'(\d+(?:\.\d+)?) ?(.*) ?', piece)
if grp and not stop:
length = float(grp.group(1))
factor = scaling.get(grp.group(2).lower(), 60)
duration += length * factor
else:
reminder = reminder + piece
stop = True
if duration == 0:
return bot.reply("Sorry, didn't understand the input.")
if duration % 1:
duration = int(duration) + 1
else:
duration = int(duration)
timezone = get_timezone(
bot.db, bot.config, None, trigger.nick, trigger.sender)
create_reminder(bot, trigger, duration, reminder, timezone)
@commands('at')
@example('.at 13:47 Do your homework!')
def at(bot, trigger):
"""
Gives you a reminder at the given time. Takes hh:mm:ssTimezone
message. Timezone is any timezone Sopel takes elsewhere; the best choices
are those from the tzdb; a list of valid options is available at
https://sopel.chat/tz . The seconds and timezone are optional.
"""
if not trigger.group(2):
bot.say("No arguments given for reminder command.")
return NOLIMIT
if trigger.group(3) and not trigger.group(4):
bot.say("No message given for reminder.")
return NOLIMIT
regex = re.compile(r'(\d+):(\d+)(?::(\d+))?([^\s\d]+)? (.*)')
match = regex.match(trigger.group(2))
if not match:
bot.reply("Sorry, but I didn't understand your input.")
return NOLIMIT
hour, minute, second, tz, message = match.groups()
if not second:
second = '0'
if pytz:
timezone = get_timezone(bot.db, bot.config, tz,
trigger.nick, trigger.sender)
if not timezone:
timezone = 'UTC'
now = datetime.now(pytz.timezone(timezone))
at_time = datetime(now.year, now.month, now.day,
int(hour), int(minute), int(second),
tzinfo=now.tzinfo)
timediff = at_time - now
else:
if tz and tz.upper() != 'UTC':
bot.reply("I don't have timezone support installed.")
return NOLIMIT
now = datetime.now()
at_time = datetime(now.year, now.month, now.day,
int(hour), int(minute), int(second))
timediff = at_time - now
duration = timediff.seconds
if duration < 0:
duration += 86400
create_reminder(bot, trigger, duration, message, timezone)
def create_reminder(bot, trigger, duration, message, tz):
t = int(time.time()) + duration
reminder = (trigger.sender, trigger.nick, message)
try:
bot.rdb[t].append(reminder)
except KeyError:
bot.rdb[t] = [reminder]
dump_database(bot.rfn, bot.rdb)
if duration >= 60:
remind_at = datetime.utcfromtimestamp(t)
timef = format_time(bot.db, bot.config, tz, trigger.nick,
trigger.sender, remind_at)
bot.reply('Okay, will remind at %s' % timef)
else:
bot.reply('Okay, will remind in %s secs' % duration)
|
import pandas as pd
import numpy as np
import sys
from sklearn.metrics import roc_auc_score, precision_recall_fscore_support
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import RandomForestClassifier
from time import time
import pickle
import os
from sys import argv
import EncoderFactory
import BucketFactory
import ClassifierFactory
from DatasetManager import DatasetManager
datasets = ["production", "sepsis_cases_1", "sepsis_cases_2", "sepsis_cases_4", "traffic_fines_1", "bpic2012_accepted",
"bpic2012_cancelled", "bpic2012_declined", "bpic2017_accepted", "bpic2017_refused", "bpic2017_cancelled",
"hospital_billing_3"]
outfile = "prefix_lengths_with_classes.csv"
train_ratio = 0.8
val_ratio = 0.2
random_state = 22
##### MAIN PART ######
with open(outfile, 'w') as fout:
fout.write("%s;%s;%s;%s;%s\n"%("dataset", "data_type", "label", "nr_events", "case_count"))
for dataset_name in datasets:
print(dataset_name)
dataset_manager = DatasetManager(dataset_name)
# read the data
data = dataset_manager.read_dataset()
# split data into train and test
train, test = dataset_manager.split_data_strict(data, train_ratio)
train, val = dataset_manager.split_val(train, val_ratio)
# consider prefix lengths until 90% of positive cases have finished
min_prefix_length = 1
max_prefix_length = dataset_manager.get_max_case_length(data)
del data
prefix_lengths_train = train.groupby(dataset_manager.case_id_col).size()
prefix_lengths_val = val.groupby(dataset_manager.case_id_col).size()
prefix_lengths_test = test.groupby(dataset_manager.case_id_col).size()
for nr_events in range(min_prefix_length, max_prefix_length+1):
print(nr_events)
# all counts
count_train = sum(prefix_lengths_train >= nr_events)
count_val = sum(prefix_lengths_val >= nr_events)
count_test = sum(prefix_lengths_test >= nr_events)
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "train", "all", nr_events, count_train))
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "val", "all", nr_events, count_val))
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "test", "all", nr_events, count_test))
# class counts
relevant_cases = prefix_lengths_train[prefix_lengths_train >= nr_events].index
class_counts_train = train[train[dataset_manager.case_id_col].isin(relevant_cases)].groupby(dataset_manager.case_id_col).first()[dataset_manager.label_col].value_counts()
relevant_cases = prefix_lengths_val[prefix_lengths_val >= nr_events].index
class_counts_val = val[val[dataset_manager.case_id_col].isin(relevant_cases)].groupby(dataset_manager.case_id_col).first()[dataset_manager.label_col].value_counts()
relevant_cases = prefix_lengths_test[prefix_lengths_test >= nr_events].index
class_counts_test = test[test[dataset_manager.case_id_col].isin(relevant_cases)].groupby(dataset_manager.case_id_col).first()[dataset_manager.label_col].value_counts()
# pos counts
count_train = 0 if dataset_manager.pos_label not in class_counts_train else class_counts_train[dataset_manager.pos_label]
count_val = 0 if dataset_manager.pos_label not in class_counts_val else class_counts_val[dataset_manager.pos_label]
count_test = 0 if dataset_manager.pos_label not in class_counts_test else class_counts_test[dataset_manager.pos_label]
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "train", "pos", nr_events, count_train))
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "val", "pos", nr_events, count_val))
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "test", "pos", nr_events, count_test))
# neg counts
count_train = 0 if dataset_manager.neg_label not in class_counts_train else class_counts_train[dataset_manager.neg_label]
count_val = 0 if dataset_manager.neg_label not in class_counts_val else class_counts_val[dataset_manager.neg_label]
count_test = 0 if dataset_manager.neg_label not in class_counts_test else class_counts_test[dataset_manager.neg_label]
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "train", "neg", nr_events, count_train))
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "val", "neg", nr_events, count_val))
fout.write("%s;%s;%s;%s;%s\n"%(dataset_name, "test", "neg", nr_events, count_test))
print("\n")
|
"""
Module containing all the actual console scripts of the project.
"""
import sys
import os
import json
from multiprocessing import Process
from pprint import pprint
import click
import matplotlib
import numpy as np
import shutil
from ufotest.config import PATH, get_config_path, Config
from ufotest.exceptions import IncompleteBuildError, BuildError, PciError, FrameDecodingError
from ufotest.util import (update_install,
run_command,
setup_environment,
init_install,
check_install,
execute_script,
get_version,
get_path,
check_vivado,
check_path)
from ufotest.util import get_template
from ufotest.util import cerror, cresult, ctitle, csubtitle, cprint, cparams
from ufotest.util import HTMLTemplateMixin
from ufotest.util import format_byte_size
from ufotest.install import (mock_install_repository,
install_dependencies,
install_fastwriter,
install_pcitools,
install_libufodecode,
install_libuca,
install_uca_ufo,
install_ipecamera)
from ufotest.camera import AbstractCamera, UfoCamera, MockCamera
from ufotest.testing import TestRunner, TestContext, TestReport
from ufotest.ci.build import BuildRunner, BuildReport, BuildLock, build_context_from_config
from ufotest.ci.server import server, BuildWorker
CONFIG = Config()
class PluginCommands(click.Group):
def __init__(self, name=None, commands=None, **attrs):
click.Group.__init__(self, name, commands, **attrs)
self.config = Config()
def get_command(self, ctx, cmd_name):
commands = self.config.pm.apply_filter('plugin_commands',
value=self.commands,
config=self.config,
context=ctx)
return commands[cmd_name]
def list_commands(self, ctx):
commands = self.config.pm.apply_filter('plugin_commands',
value=self.commands,
config=self.config,
context=ctx)
return sorted(commands)
# == COMMANDS ==
# https://click.palletsprojects.com/en/8.0.x/complex/
# https://click.palletsprojects.com/en/8.0.x/complex/#interleaved-commands
pass_config = click.make_pass_decorator(Config)
@click.group(invoke_without_command=True)
@click.option('--version', is_flag=True, help='Print the version of the program')
@click.option('--verbose', '-v', is_flag=True, help='Print additional console output for the command')
@click.option('--conf', '-c', type=click.STRING, multiple=True, help='Overwrite config variables')
@click.option('--mock', '-m', is_flag=True, help='Using the mock camera class for all actions')
@click.pass_context
def cli(ctx, version, verbose, conf, mock):
"""
UfoTest command line interface
The main way to use UfoTest's functionality is by invoking the appropriate command. Each command has it's own set
of arguments and options. To list these options and to show an explanation of the commands purpose, use the
--help option which is available for every command:
ufotest <subcommand> --help
"""
# If the version option of the base command is invoked, this means that we simply want to print the version of the
# project and then terminate execution
if version:
# "get_version" reads the version of the software from the corresponding file in the source folder.
version = get_version()
click.secho(version, bold=True)
sys.exit(0)
# We acquire an instance of the config object here in the base command and then simply pass it as a context to each
# respective sub command. Sure, the Config class is a singleton anyways and we could also invoke it in every
# sub command, but like this we can do something cool. We simply add a --verbose option to this base command and
# then save the value in the config, since we pass it along this also affects all sub commands and we dont need
# to implement the --verbose option for every individual sub command.
config = Config()
config['context']['verbose'] = verbose
ctx.obj = config
# This fixes an important bug: Previously when any command was executed, the program attempted to call the prepare
# method which would then in turn load the plugins. But that caused a problem when initially attempting to install
# ufotest. For an initial installation there is not config file yet, but "prepare" and the init of the script and
# plugin manager need certain config values! Thus ufotest could never be installed. Now we will treat the
# installation command "init" as a special case which does not need the use the plugin system.
if ctx.invoked_subcommand != 'init':
# "prepare" sets up the correct jinja environment and initializes the plugin manager and the
# script manager
config.prepare()
# Usually I wouldnt want to have to add the custom filters here but, sadly I have to due to pythons import
# system. I would have liked to do it in "prepare" but in that module i cannot import anything from util (where
# the actual method comes from) since util imports from that module...
config.template_environment.filters['format_byte_size'] = format_byte_size
# This hook can be used to execute generic functionality before any command specific code is executed
config.pm.do_action('pre_command', config=config, namespace=globals(), context=ctx)
for overwrite_string in conf:
try:
config.apply_overwrite(overwrite_string)
except Exception:
if config.verbose():
cerror((
f'Could not apply config overwrite for value {overwrite_string}. Please check if the string is '
f'formatted correctly. The correct formatting would be "key.subkey=value". Also check if the '
f'variable even exists in the config file.'
))
if mock:
# The "--mock" option for the main ufotest command implies that the mock camera class is to be used for the
# execution of all sub commands. The first thing we need to do for this is to set the context flag "mock" to
# True. This flag can be used by sub commands to check if the mock option has been invoked.
# We could also check for the class of the camera, but that would be unreliable because technically a plugin
# could change the mock camera class!
config['context']['mock'] = True
# This is what I meant: The exact camera class used as the mock is also subject to change by filter hook. On
# default it will be MockCamera, but a plugin could decide to extend this class by subclassing or replace it
# with something completely different
mock_camera_class = config.pm.apply_filter('mock_camera_class', MockCamera)
# Then of course we modify the main "camera_class" filter to actually inject this mock camera class to be used
# in all following scenarios.
config.pm.register_filter('camera_class', lambda value: mock_camera_class, 1)
# -- Commands related to the installation of dependencies
#: A dictionary whose keys are possible string argument names for installable dependencies and the values are function
#: objects, which actually perform the installation of that dependency. Each of these functions should accept a single
#: positional argument which is the folder path into which they are supposed to be installed.
DEPENDENCY_INSTALL_FUNCTIONS = {
'pcitool': install_pcitools,
'fastwriter': install_fastwriter,
'libufodecode': install_libufodecode,
'libuca': install_libuca,
'ipecamera': install_ipecamera
}
# TODO: Add force flag
@click.command('install', short_help='Install a dependency for the ufo camera')
# https://click.palletsprojects.com/en/8.0.x/options/#choice-options
@click.argument('dependency', type=click.Choice(['pcitool', 'fastwriter', 'libufodecode', 'libuca', 'ipecamera']))
@click.argument('path', type=click.Path(exists=True, file_okay=False, dir_okay=True, writable=True))
@click.option('--save-json', '-j', is_flag=True, help=(
'Whether or not to create a JSON output file as a result of the installation process. The file will be located in '
'the current working directory and be named "install.json" it will contain the keys: "success" (bool), '
'"path": (string), "git": (string).'
))
@click.option('--skip', is_flag=True, help='Does not perform the actual installation. For testing.')
@pass_config
def install(config, dependency, path, save_json, skip):
"""
Installs a given DEPENDENCY into the folder provided as PATH.
This command is used to install individual dependencies for running the ufo camera system on the local machine.
"""
# The path sting which is passed into this function could also be a relative path such as ".." which stands for
# "the parent folder relative to the current one from which I am executing this". All functions expect an
# absolute path and "realpath" converts these relative expressions into absolute paths
path = os.path.realpath(path)
# The "skip" flag is mainly for testing the CLI. It is supposed to prevent the actual functionality of
# the command to be executed so the test case does not take so long. So in this case we do not actually
# run the installation function, but still have to create a mock results dict
if skip:
result = mock_install_repository(path)
else:
# Each install function takes a single argument which is the folder path of the folder into which the
# dependency (repo) is to be installed. They return a dict which describes the outcome of the installation
# procedure with the following three fields: "success", "path", "git"
install_function = DEPENDENCY_INSTALL_FUNCTIONS[dependency]
result = install_function(path)
# If the the "--save-json" flag was provided with the command, we'll also save the result of the installation
# process as a JSON file to the current working directory.
if save_json:
try:
json_path = os.path.join(os.getcwd(), 'install.json')
with open(json_path, mode='w+') as file:
json.dump(result, file, indent=4, sort_keys=True)
except Exception as e:
cerror(f'Could not save "install.json" because: {str(e)}')
sys.exit(1)
sys.exit(0)
@click.command('install-all', short_help='Install all project dependencies.')
@click.argument('path', type=click.Path(exists=True, file_okay=False, dir_okay=True, writable=True))
@click.option('--no-dependencies', '-d', is_flag=True, help='Skip installation of required system packages')
@click.option('--save-json', '-j', is_flag=True, help=(
'Whether or not to create a JSON output file as a result of the installation process. The file will be located in '
'the current working directory and be named "install.json" it will contain the string names of the dependencies '
'as keys and the values will be dicts, which in turn have the following keys: "success" (bool), '
'"path": (string), "git": (string).'
))
@click.option('--skip', is_flag=True, help='Does not perform the actual installation. For testing.')
@pass_config
def install_all(config, path, no_dependencies, save_json, skip):
"""
Installing all dependencies for the ufo camera project into PATH
PATH has to be the path to an existing folder. The command installs all the required repositories into this folder.
Apart from the repositories, the command also installs the required system packages for the operation of the
UFO camera. For this it relies on the package installation method and operation system defined within the
ufotest config file.
"""
# The path sting which is passed into this function could also be a relative path such as ".." which stands for
# "the parent folder relative to the current one from which I am executing this". All functions expect an
# absolute path and "realpath" converts these relative expressions into absolute paths
path = os.path.realpath(path)
operating_system = CONFIG['install']['os']
ctitle('INSTALLING NECESSARY REQUIREMENTS')
cparams({
'operating system': operating_system,
'package install command': CONFIG['install'][operating_system]['package_install'],
'camera dimensions:': f'{CONFIG.get_sensor_width()} x {CONFIG.get_sensor_height()}'
})
results = {}
# We will only actually execute the installation procedures if the skip flag is not set
if not skip:
if no_dependencies:
cprint('Skipping system packages...')
else:
install_dependencies(verbose=config.verbose())
for dependency_name, install_function in DEPENDENCY_INSTALL_FUNCTIONS.items():
csubtitle(f'Installing "{dependency_name}"')
result = install_function(path)
results[dependency_name] = result
else:
results['mock'] = mock_install_repository(path)
# Creating the JSON file if the flag was set.
if save_json:
try:
json_path = os.path.join(os.getcwd(), 'install.json')
with open(json_path, mode='w+') as file:
json.dump(results, file, indent=4, sort_keys=True)
except Exception as e:
cerror(f'Could not save "install.json" because: {str(e)}')
sys.exit(1)
sys.exit(0)
@click.command('init', short_help='Initializes the installation folder and config file for the app')
@click.option('--force', '-f', is_flag=True, help='Deletes the current installation to reinstall')
@click.option('--update', '-u', is_flag=True, help='Only update the static assets, leave data and configuration intact')
def init(force, update):
"""
Initializes the installation folder for this application.
This folder will be located at "$HOME/.ufotest". The init furthermore includes the creation of the necessary
sub folder structures within the installation folder as well as the creation of the default config file and all the
static assets for the web interface.
The --force flag can be used to *overwrite* an existing installation. It will delete the existing installation,
if one exists, and then create an entirely new installation.
The --update flag can be used to perform an update rather than a complete installation. This can be invoked with an
installation present and will not overwrite custom configuration files. The only thing which will be replaced
during such an update will be the static files. The new static files from the current system package version of
ufotest will be copied to the active installation folder.
"""
installation_path = get_path()
ctitle('INITIALIZING UFOTEST INSTALLATION')
cparams({'installation path': installation_path})
if update:
if check_path(installation_path, is_dir=True):
update_install(installation_path)
cresult('Updated ufotest installation')
sys.exit(0)
else:
cerror('Cannot perform update without already existing installation!')
sys.exit(1)
if check_path(installation_path, is_dir=True):
if force:
shutil.rmtree(get_path())
cprint('Deleted old installation folder')
else:
cerror('An installation folder already exists at the given path!')
cerror('Please use the --force flag if you wish to forcefully replace the existing installation')
sys.exit(1)
else:
cprint(' Installation folder does not yet exist')
# This method actually executes the necessary steps.
init_install()
cresult('UfoTest successfully initialized, use the --help option for further commands')
sys.exit(0)
@click.command('config', short_help='Edit the ufotest configuration file')
@click.option('--editor', '-e', type=click.STRING, help='Specify the editor command used to open the config file')
@pass_config
def config(config, editor):
"""
Edit the ufotest configuration file.
Invoking this command without any additional options will open the ufotest config file located at
"$HOME/.ufotest/config.toml" with the text editor currently set as default on the system.
The --editor option can be used to overwrite the system preference for any one editor
"""
config_path = get_config_path()
click.edit(filename=config_path, editor=editor)
sys.exit(0)
@click.command('frame', short_help='Acquire and display a frame from the camera')
@click.option('--output', '-o', type=click.STRING,
help='Specify the output file path for the frame', default='/tmp/frame.png')
@click.option('--display', '-d', is_flag=True, help='display the frame in seperate window')
@pass_config
def frame(config, output, display):
"""
Capture a single frame from the camera.
If this command is invoked without any additional options, the frame will be captured from the camera and then
saved to the location "/tmp/frame.png".
The output location for the image file can be overwritten by using the --output option to specify another path.
The --display flag can be used to additionally display the image to the user after the frame has been captured.
This feature requires a graphical interface to be available to the system. The frame will be opened in a seperate
matplotlib figure window.
"""
config.pm.do_action(
'pre_command_frame',
config=config,
namespace=globals(),
output=output,
display=display
)
ctitle('CAPTURING FRAME')
cparams({
'output path': output,
'display frame': display,
'sensor_dimensions': f'{CONFIG.get_sensor_width()} x {CONFIG.get_sensor_height()}'
})
# Setup all the important environment variables and stuff
setup_environment()
exit_code, _ = run_command('rm /tmp/frame*')
if not exit_code:
cprint('Removed previous frame buffer')
# ~ GET THE FRAME FROM THE CAMERA
# "get_frame" handles the whole communication process with the camera, it requests the frame, saves the raw data,
# decodes it into an image and then returns the string path of the final image file.
try:
camera_class = config.pm.apply_filter('camera_class', UfoCamera)
camera = camera_class(config)
frame = camera.get_frame()
except PciError as error:
cerror('PCI communication with the camera failed!')
cerror(f'PciError: {str(error)}')
sys.exit(1)
except FrameDecodingError as error:
cerror('Decoding of the frame failed!')
cerror(f'FrameDecodingError: {str(error)}')
sys.exit(1)
# ~ Saving the frame as a file
_, file_extension = output.split('.')
if file_extension == 'raw':
cerror('Currently the frame cannot be saved as .raw format!')
else:
from PIL import Image
image = Image.fromarray(frame)
image.save(output)
# ~ Displaying the image if the flag is set
if display:
# An interesting thing is that matplotlib is imported in-time here and not at the top of the file. This actually
# had to be changed due to a bug. When using ufotest in a headless environment such as a SSH terminal session
# it would crash immediately, because a headless session does not work with the graphical matplotlib. Since
# it really only is needed for this small section here, it makes more sense to just import it in-time.
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
plt.imshow(frame)
plt.show()
sys.exit(0)
@click.command('setup', short_help="Enable the camera")
@pass_config
def setup(config):
"""
Executes the setup routine for the camera, which includes all the steps required to properly initialize the
camera such that all subsequent requests / frame captures should succeed.
"""
camera_class = config.pm.apply_filter('camera_class', UfoCamera)
camera: AbstractCamera = camera_class(config)
camera.set_up()
@click.command('teardown', short_help="Disable the camera. DO NOT USE")
@pass_config
def teardown(config):
"""
Executes the teardown routine for the camera, which includes all the steps required to properly end the usage.
"""
camera_class = config.pm.apply_filter('camera_class', UfoCamera)
camera: AbstractCamera = camera_class(config)
camera.tear_down()
@click.command('status', short_help="Outputs whether or not the camera is usable")
@pass_config
def status(config):
"""
Polls the camera to check if it is available for frame requests. This command outputs a single integer which is a 1
if the camera does indeed work properly and is accepting frame requests and a 0 if the camera does not.
More specifically this command instantiates a camera class and calls the "poll" method on it. The implementation of
how exactly the status is derived varies between camera class implementations. Also note that if verbosity is
enables, the poll method may produce additional console output.
"""
camera_class = config.pm.apply_filter('camera_class', UfoCamera)
camera: AbstractCamera = camera_class(config)
status_result = camera.poll()
# For this command no fancy output, we are literally only printing the integer status
# representation so that this command could be used in a pipeline or the like
click.echo(int(status_result))
# The status is True if the camera works and False if it does not work. That is exactle the other way around that
# the command exit codes work. This should be 1 in case of a problem.
sys.exit(not status_result)
@click.command('flash', short_help='Flash a new .BIT file to the FPGA memory')
@click.option('--type', '-t', type=click.Choice('bit'), default='bit',
help='Type of file to be used for flashing to the fpga board')
@click.argument('file', type=click.STRING)
@pass_config
def flash(config, file: str, type: str) -> None:
"""
Uses the given FILE to flash a new firmware configuration to the internal memory of the FPGA board, where FILE is
the string absolute path of the file which contains a valid specification of the fpga configuration.
The --type option can be used to select which kind of configuration file to be flashed. currently only BIT files
are supported.
"""
# -- ECHO CONFIGURATION
ctitle('FLASHING BITFILE TO FPGA')
click.secho('--| bitfile path: {}\n'.format(file))
# ~ SKIP FOR MOCK
# If the "--mock" option is active then we completely skip this command since presumably there is not actual
# camera connected to do the flashing.
# TODO: In the future we could add an action hook here to be able to inject come actual code for the case of
# mock camera + flash command.
if config['context']['mock']:
cresult('Skip flash when due to --mock option being enabled')
sys.exit(0)
# ~ CHECKING IF THE GIVEN FILE EVEN EXISTS
file_path = os.path.abspath(file)
file_exists = check_path(file_path, is_dir=False)
if not file_exists:
cerror('The given path for the bitfile does not exist')
sys.exit(1)
# ~ CHECKING IF THE FILE EVEN IS A BIT FILE
file_extension = file_path.split('.')[-1].lower()
is_bit_file = file_extension == 'bit'
if not is_bit_file:
cerror('The given path does not refer to file of the type ".bit"')
sys.exit(1)
# ~ CHECKING IF VIVADO IS INSTALLED
vivado_installed = check_vivado()
if not vivado_installed:
cerror('Vivado is not installed, please install Vivado to be able to flash the fpga!')
sys.exit(1)
if CONFIG.verbose():
cprint('Vivado installation found')
# ~ STARTING VIVADO SETTINGS
vivado_command = CONFIG['install']['vivado_settings']
run_command(vivado_command, cwd=os.getcwd())
if CONFIG.verbose():
cprint('Vivado setup completed')
# ~ FLASHING THE BIT FILE
flash_command = "{setup} ; {command} -nolog -nojournal -mode batch -source {tcl} -tclargs {file}".format(
setup=CONFIG['install']['vivado_settings'],
command=CONFIG['install']['vivado_command'],
tcl=CONFIG.sm.scripts['fpga_bitprog'].path,
file=file_path
)
exit_code, _ = run_command(flash_command)
if not exit_code:
cresult('Flashed FPGA with: {}'.format(file_path))
sys.exit(0)
else:
cerror('There was an error during the flashing of the FPGA')
sys.exit(1)
@click.command('test', short_help="Run a camera test")
@click.option('--suite', '-s', is_flag=True, help='Execute a test SUITE with the given name')
@click.argument('test_id', type=click.STRING)
@pass_config
def test(config, suite, test_id):
"""
Run the test "TEST_ID"
TEST_ID is a string, which identifies a certain test procedure. To view all these possible identifiers consult the
config file.
This command executes one or multiple camera test cases. These test cases interface with the camera to perform
various actions to confirm certain functionality of the camera and the fpga module. This process will most likely
take a good amount of time to finish. After all test cases are done, a test report will be generated and saved in
an according sub folder of the "archive"
The --suite flag can be used to execute a whole test suite (consisting of multiple test cases) instead. In case
this flag is passed, the TEST_ID argument will be interpreted as the string name identifier of the suite.
NOTE: To quickly assess a test case without actually having to interface with the camera itself it is possible to
use the --mock flag *on the ufotest base command* to use the mock camera to perform the test cases.
"""
ctitle(f'RUNNING TEST{" SUITE" if suite else ""}')
cparams({
'test identifier': test_id,
'is test suite': suite,
'verbose': config.verbose()
})
try:
with TestContext() as test_context:
# 1 -- DYNAMICALLY LOADING THE TESTS
test_runner = TestRunner(test_context)
test_runner.load()
# 2 -- EXECUTING THE TEST CASES
if suite:
click.secho(' Executing test suite: {}...'.format(test_id), bold=True)
test_runner.run_suite(test_id)
else:
click.secho(' Executing test: {}...'.format(test_id), bold=True)
test_runner.run_test(test_id)
# 3 -- SAVING THE RESULTS AS A REPORT
test_report = TestReport(test_context)
test_report.save(test_context.folder_path)
except Exception as e:
click.secho('[!] {}'.format(e), fg='red', bold=True)
sys.exit(1)
if config.verbose():
click.secho(test_report.to_string())
cresult('Test report saved to: {}'.format(test_context.folder_path))
cprint('View the report at: http://localhost/archive/{}/report.html'.format(test_context.folder_name))
sys.exit(0)
# == SCRIPTS COMMAND GROUP ==
@click.group('scripts', short_help='Command sub group for interacting with the scripts registered within ufotest')
@pass_config
def scripts(config):
pass
@click.command('invoke', short_help='Invokes a script which is registered in ufotest identified by its string name')
@click.option('--args', type=click.STRING, default='',
help=('This is a string which can contain additional arguments for the script itself. Depending on the '
'type of script, the concrete format of this may differ. For the default bash type, this string '
'is appended to the script call as it is.'))
@click.option('--fallback', is_flag=True, default=False,
help=('Boolean flag of whether or not to use the fallback version of the script. The fallback version '
'is the (generally) stable version of a script which comes shipped with ufotest itself and is '
'not subject to version control.'))
@click.argument('name', type=click.STRING)
@pass_config
def invoke_script(config, name, args, fallback):
"""
Invokes the script identified by it's string NAME.
On default this command will attempt to invoke the most recent version of the script, which is subject to version
control and came with the most recent CI build. To use the stable fallback version which comes with the
ufotest software itself use the --fallback flag
"""
ctitle('Invoking script')
cparams({
'script name': name,
'additional args': args,
'use fallback?': fallback,
})
try:
result = config.sm.invoke(name, args, use_fallback=fallback)
if result['exit_code'] == 0:
cresult(f'script "{name}" exits with code 0')
cprint('STDOUT:\n' + result['stdout'])
elif result['exit_code'] != 0:
cerror(f'script "{name}" exits with code 1')
cerror('STDERR:\n' + result['stderr'])
cprint('STDOUT:\n' + result['stdout'])
sys.exit(1)
except KeyError:
cerror(f'A script with name "{name}" is not registered with ufotest!')
sys.exit(1)
sys.exit(0)
@click.command('list', short_help='Displays a list of all scripts which are registered with ufotest')
@click.option('--full', is_flag=True, default=False,
help=('Boolean flag to show the full details of every script '))
@pass_config
def list_scripts(config, full):
"""
Displays a list of all scripts that are registered with ufotest.
Use the --detail flag to display more information about each script.
"""
ctitle('list registered scripts')
for script_name, script_wrapper in config.sm.scripts.items():
csubtitle(f'{script_name} ({script_wrapper.data["class"]})')
if full:
details = {
'description': script_wrapper.description,
'author': script_wrapper.author,
'path': script_wrapper.path,
'has fallback?': script_name in config.sm.fallback_scripts,
}
else:
details = {
'path': script_wrapper.path,
'has fallback?': script_name in config.sm.fallback_scripts
}
cparams(details)
sys.exit(0)
@click.command('details', short_help='Displays the full details of a registered script including its source code')
@click.argument('name', type=click.STRING)
@pass_config
def script_details(config, name):
"""
Shows the full details of the scripts identified by it's string NAME.
This command prints the full details for the given script, including its source code.
"""
# ~ Checking for eventual problems with the script
# First we need to check if a script with the given name even exists
if name in config.sm.scripts:
script = config.sm.scripts[name]
elif name in config.sm.fallback_scripts:
script = config.sm.fallback_scripts[name]
else:
cerror(f'A script identified by "{name}" is nor registered with ufotest!')
sys.exit(1)
# Then we need to check if the file even exists / the content can be read, since we also want to display the
# content of it
try:
with open(script.path, mode='r+') as file:
content = file.read()
except:
cerror(f'The file {script.path} does not exists and/or is not readable!')
sys.exit(1)
# ~ Displaying the results to the user in case there are no problems
ctitle(name)
cparams({
'type': script.data['class'],
'path': script.path,
'author': script.author
})
cprint('DESCRIPTION:\n' + script.description)
print()
cprint('CONTENT:\n' + content)
# == CONTINUOUS INTEGRATION COMMAND GROUP ==
# The 'ci' sub command for ufotest is actually a command group which itself contains various sub commands related to
# the CI functionality such as starting the CI server or triggering a new build process with the remote repository.
@click.group('ci', short_help='continuous integration related commands')
def ci():
pass
@click.command('build', short_help='Applies newest commit from remote repository and then executes test suite')
@click.option('--skip', '-s', is_flag=True, help='skip the cloning of the repository and flashing of the new bitfile')
@click.argument('suite', type=click.STRING)
@pass_config
def build(config, suite, skip) -> None:
"""
Start a new CI build process using the test suite SUITE.
A build process first clones the target repository, which was specified within the "ci" section of the config file.
Specifically, it checks out the branch, which is also defined in the config, and uses the most recent commit to
that branch. After the repository has been cloned, the bit file within is used to flash a new configuration onto
the FPGA hardware. Finally, the given test suite is executed and the results are being saved to the archive.
"""
# ~ PRINT CONFIGURATION
ctitle('BUILDING FROM REMOTE REPOSITORY')
cparams({
'repository url': CONFIG.get_ci_repository_url(),
'repository branch': CONFIG.get_ci_branch(),
'bitfile relative path': CONFIG.get_ci_bitfile_path(),
'test suite': suite
})
# ~ RUNNING THE BUILD PROCESS
try:
with build_context_from_config(CONFIG) as build_context:
# The "build_context_from_config" function builds the context object entirely on the basis of the
# configuration file, which means, that it also uses the default test suite defined there. Since the build
# function is meant to be able to pass the test suite as a parameter, we will have to overwrite this piece
# of config manually.
build_context.test_suite = suite
build_runner = BuildRunner(build_context)
build_runner.run(test_only=skip)
build_report = BuildReport(build_context)
build_report.save(build_context.folder_path)
sys.exit(0)
except BuildError as e:
cerror(f'An error has occurred during the build process...\n {str(e)}')
sys.exit(1)
@click.command('serve', short_help='Runs the CI server which serves the web interface and accepts build requests')
@click.option('--host', '-h', type=click.STRING, default='0.0.0.0', help='the host address for the server')
@pass_config
def serve(config, host):
"""
Starts the CI web server.
This web server serves the web interface for the application. Locally and on default configuration. This web
interface can be accessed through a browser at "http://localhost:8030". The homepage of this interface can for
example be used to view a status summary for ufotest, view the html pages of both test and build reports as well
as editing the config file.
Additionally the running web server exposes a web API, which accepts incoming notifications from github or gitlab
code repositories to information about a new push event to the firmware repository of the camera. Following such a
push notification a new build and subsequent test execution will be triggered automatically.
"""
# -- ECHO CONFIGURATION
click.secho('\n| | STARTING CI SERVER | |', bold=True)
click.secho('--| repository url: {}'.format(CONFIG.get_ci_repository_url()))
click.secho('--| repository branch: {}'.format(CONFIG.get_ci_branch()))
click.secho('--| bitfile path: {}'.format(CONFIG.get_ci_bitfile_path()))
click.secho('--| host address: {}\n'.format(host))
# So this might be confusing: Here we get the 'hostname', but the command also has an option called 'host'. The
# 'host' option is an IP address. This IP address is the one, which the flask server will be bound to. It has to
# be the IP address of the PC in the target *local* network, where it will receive the requests from a possibly
# port-forwarded router. The 'hostname' is the domain name under which the server is addressed from the *outside*
hostname = CONFIG.get_hostname()
port = CONFIG.get_port()
click.secho('(+) Visit the server at http://{}:{}/'.format(hostname, port), fg='green')
# -- STARTING BUILD WORKER
# The flask server does not actually process the actual builds. It simply accepts the requests and based on the
# information within these requests it schedules a new build by putting the information into a queue. The actual
# build will then be started by this separate build worker process. This is because builds can take a very long
# time and they should not block the web server from handling other requests.
build_worker = BuildWorker()
process = Process(target=build_worker.run)
process.start()
# -- STARTING THE SERVER
server.run(port=port, host=host)
@click.command('recompile', short_help='Updates all the HTML test reports')
@pass_config
def recompile(config):
"""
This command recompiles all the static HTML files of the test reports.
All test reports are actually static HTML files, which are created from a template after the corresponding test run
finishes. This presents an issue if any web interface related changes are made to the config or if the html
templates are updated with a new release version. In such a case the test report html pages would not reflect the
changes. In this case, the "recompile" command can be used to recreate the static html files using the current
config / template versions.
"""
# THE PROBLEM
# So this is the problem: Test reports are actually static html files. These html templates for each test reports
# are rendered once the test run finishes and then they are just html files. In contrary to dynamically creating
# the html content whenever the corresponding request is made. And I would like to keep it like this, because the
# it is easier to handle in other regards, but this poses the following problem: If certain changes are made to the
# server these are not reflected within the rest report html pages. The most pressing problem is if the URL changes
# This will break all links on the test report pages. Another issue is when a new version of ufotest introduces
# changes to the report template, which wont be reflected in older reports.
# THE IDEA
# The "recompile" command should fix this by recreating all the test report static html files with the current
# version of the report template based on the info in the report.json file
ctitle('RECOMPILE TEST REPORT HTML')
cparams({
'archive folder': config.get_archive_path()
})
count = 0
for root, folders, files in os.walk(config.get_archive_path()):
for folder in folders:
folder_path = os.path.join(root, folder)
report_json_path = os.path.join(folder_path, 'report.json')
report_html_path = os.path.join(folder_path, 'report.html')
if not os.path.exists(report_json_path):
continue
with open(report_json_path, mode='r+') as file:
report_data = json.load(file)
with open(report_html_path, mode='w+') as file:
# "report_data" is only the dict representation of the test report. This is problematic because we
# cannot call the "to_html" method then. But the test report class and all the test result classes
# implement the HTMLTemplateMixin class, which enables to render the html template from just this dict
# representation using the static method "html_from_dict". This is possible because the dict itself
# saves the entire template string in one of its fields.
html = HTMLTemplateMixin.html_from_dict(report_data)
file.write(html)
cprint(f'Recompiled test report {folder}')
count += 1
break
cresult(f'Recompiled {count} test reports!')
sys.exit(0)
# TODO: Which commands do I even want?
@click.group('devices', short_help='devices related command group')
def devices():
pass
# Registering the commands within the "ci" group. The ci group is a sub command group which contains the commands
# relating to the "continuous integration" functionality.
ci.add_command(build)
ci.add_command(serve)
ci.add_command(recompile)
# Registering the commands with the "scripts" group.
scripts.add_command(invoke_script)
scripts.add_command(list_scripts)
scripts.add_command(script_details)
# Registering the commands within the click group
cli.add_command(init)
cli.add_command(config)
cli.add_command(install)
cli.add_command(install_all)
cli.add_command(frame)
cli.add_command(setup)
cli.add_command(teardown)
cli.add_command(status)
cli.add_command(list_scripts)
cli.add_command(flash)
cli.add_command(test)
# Registering the sub groups
cli.add_command(ci)
cli.add_command(scripts)
# 2.0.0 - 29.11.2021
# "MiscCommands" is a special click command group which uses a filter hook from the
# plugin manager to dynamically load commands after the startup sequence!
plugin_commands = PluginCommands(name='plugin', help='Commands added by plugins')
cli.add_command(plugin_commands)
if __name__ == "__main__":
sys.exit(cli()) # pragma: no cover
|
from unittest import mock
from typing import Dict
from fastapi.testclient import TestClient
from app.core.config import settings
@mock.patch('app.utils.message_bus.quick_send')
def test_message_bus_default(
mock_send, client: TestClient, api_key_headers: Dict[str, str]) -> None:
_topic = "test"
params = {
"topic": _topic
}
_body = {
"body": "SAMPLE MESSAGE"
}
r = client.post(f"{settings.API_V1_STR}/message_bus",
json=_body,
params=params,
allow_redirects=True,
headers=api_key_headers)
assert r.status_code == 200
assert r.text == '{"msg":"Message have been sent"}'
|
# coding=utf-8
import csv
import logging
from unit.exporters.base import BaseExporter
from unit.particle import Particle
class CsvExporter(BaseExporter):
"""
Exports particles as CSV format into given fileobj.
"""
def export(self):
writer = csv.writer(
self._file_obj,
dialect='excel',
delimiter=',',
)
logging.debug('Exporting {} particles.'.format(len(self._particles)))
writer.writerow(Particle.HEADER_FIELD_NAMES)
writer.writerows(
(p.width, p.height, p.max_length, p.thickness)
for i, p
in enumerate(self._particles, start=1)
if p.width and p.thickness and p.height and p.max_length
)
|
from appJar import gui
import _thread
#import driveGUI
from driveGUI import calc_steering,reset_stop_flag,set_stop_flag,set_autonomer_modus,set_manueller_modus,lese_von_ST,set_Gaspedal_Stellung,show_Frame,get_model_steering_angle,set_Fummelfaktor_Stellwinkel
app = gui("control panel","550x550")
import time
Start=False
dir_path="Noch kein Model ausgewählt"
##################################################################################################
############ Funktionen die bei anklicken der Buttons aktiviert werden ##########################
##################################################################################################
def pressSelectModel(button):
global Puffer_dir_path
global dir_path
print("|...Neuen Model Ladeort setzen")
Puffer_dir_path=app.openBox(title="model file", dirName=None, parent=None)
if (str(Puffer_dir_path) == "None") or(str(Puffer_dir_path) =="()") or(str(Puffer_dir_path) ==""): #wenn man das[x] anklickt oder [cancel]
print("|... abgebrochen")
else:
dir_path=Puffer_dir_path # Wenn ein gültige Pfad angegeben wurde die globale Variable überschreiben
print("|... Neuer Ladeort: "+ str(dir_path))
app.setLabel("SaveDirectory", dir_path)
##################################################################################################
def pressStart(button):
global Start
global dir_path
if not Start: # nur ausführen, wenn zum ersten mal start gedrückt wurde
if not str(dir_path) == 'Noch kein Model ausgewählt': # nur ausführen, wenn es einen gültigen pfad gibt
print("|\n|\n|\n|...LADE Model: "+ str(dir_path))
reset_stop_flag()
_thread.start_new_thread( calc_steering, (dir_path,) )
app.setButton("Start Model", "Stop Model")
Start=True
app.setButtonBg("Start Model", "LimeGreen")
else:
print ("|...Es wurde kein gültiger Pfad angeben")
app.errorBox("Obacht, kein gültiger Pfad", "\nEs wurde noch kein Model ausgewählt.\n\nMit dem Button [Select Model] muss erst noch eine model.h5 Datei ausgewählt werden ", parent=None)
else: # Wenn schon mal Start gedrückt wurde Button Text invertieren und Thread stoppen
set_stop_flag()
app.setButton("Start Model", "Start Model")
Start=False
print("|...Model gestoppt"+ str(Puffer_dir_path))
app.setButtonBg("Start Model", "LightCoral")
##################################################################################################
def pressModus(button):
if not Status: #wenn manueller modus
set_autonomer_modus()
else:
set_manueller_modus()
##################################################################################################
def pressGaspedal(button):
set_Gaspedal_Stellung(app.getScale("Gaspedal"))
##################################################################################################
def pressStream(button):
_thread.start_new_thread( show_Frame, () ) # auf seperaten Thread das aktuelle input Bild ins netz zeigen... muss aber parallel zur Hauptschleife in der driveGUI.py laufen, sonst wird die Hauptschleife langsamer
##################################################################################################
def pressFummelfaktorStellwinkel(button):
set_Fummelfaktor_Stellwinkel(app.getScale("Fummelfaktor_Stellwinkel")/100) #TODO Funktion in dirveGui.py zum setzen des Faktors
##################################################################################################
##################################################################################################
############ Seperate Funktionen ###############################################################
##################################################################################################
def aktualisiere_Gui_mit_Daten_von_ST():
global Status
Flanke= False
while True:
UartEmpfang=lese_von_ST()
Status=UartEmpfang['Bit_Modus_manuell_oder_autonom']
ms_MomentanGeschwindigkeit=UartEmpfang['MomentanGeschwindigkeit']
if Status and not Flanke:
app.setButtonBg("Modus", "LimeGreen")
app.setButton("Modus", "Stoppe autonomen Modus")
print("|...< Status autonomer Modus von ST empfangen")
Flanke=True
if not Status and Flanke:
app.setButtonBg("Modus", "LightCoral")
app.setButton("Modus", "Starte autonomen Modus")
print("|...< Status manueller Modus von ST empfangen")
Flanke=False
app.setLabel("AusgabeMomentanGeschwindigkeit",str( "%.2f" % ms_MomentanGeschwindigkeit)+ " m/s")
app.setLabel("AusgabeStellwinkel",str("%.2f" % get_model_steering_angle()) + " °")
##################################################################################################
############ Gui Layout erzeugen ################################################################
##################################################################################################
## Zeige Pfad zu aktuellem Model an
app.addLabel("SaveDirectory",dir_path,0,0,4)
app.getLabelWidget("SaveDirectory").config(font="Helvetica 10")
app.setLabelBg("SaveDirectory", "DarkGray")
## Button zum auswählen eines Modells
app.addButtons(["SelectModel"], pressSelectModel,1,0,2)
app.getButtonWidget("SelectModel").config(font="Helvetica 12")
## Button zum Starten eines Modells
app.addButtons(["Start Model"], pressStart,1,2,4)
app.getButtonWidget("Start Model").config(font="Helvetica 12")
app.setButtonBg("Start Model", "LightCoral")
## Slider zum steuern der Geschwindigkeit
app.addScale("Gaspedal",2,0,2)
app.setScale("Gaspedal", 10, callFunction=True)
app.setScaleChangeFunction("Gaspedal", pressGaspedal)
app.setScaleRange("Gaspedal" ,0, 100, curr=12)
app.showScaleValue("Gaspedal", show=True)
app.getScale("Gaspedal")
app.showScaleIntervals("Gaspedal", 25)
## Button zum Starten des autonomen Modus
app.addButtons(["Modus"], pressModus,2,2,4)
app.getButtonWidget("Modus").config(font="Helvetica 12")
app.setButton("Modus", "Starte autonomen Modus")
app.setButtonBg("Modus", "LightCoral")
## Anzeige der Geschwindigkeit
app.addLabel("AusgabeMomentanGeschwindigkeit",dir_path,4,0,2)
app.getLabelWidget("AusgabeMomentanGeschwindigkeit").config(font="Helvetica 12")
app.setLabel("AusgabeMomentanGeschwindigkeit", "0.00 m/s")
## Anzeige des Stellwinkels
app.addLabel("AusgabeStellwinkel",dir_path,4,2,4)
app.getLabelWidget("AusgabeStellwinkel").config(font="Helvetica 12")
app.setLabel("AusgabeStellwinkel", "0.00 °")
## zeige stream
app.addButtons(["zeigeStream"], pressStream,5,0,4)
app.getButtonWidget("zeigeStream").config(font="Helvetica 12")
app.setButton("zeigeStream", "Starte Stream")
## Fummelfaktor Stellwinkel
app.addScale("Fummelfaktor_Stellwinkel",6,0,4)
app.setScale("Fummelfaktor_Stellwinkel",1, callFunction=True)
app.setScaleChangeFunction("Fummelfaktor_Stellwinkel", pressFummelfaktorStellwinkel)
app.setScaleRange("Fummelfaktor_Stellwinkel" ,100.0, 300.0, curr=10)
app.showScaleValue("Fummelfaktor_Stellwinkel", show=True)
app.getScale("Fummelfaktor_Stellwinkel")
app.showScaleIntervals("Fummelfaktor_Stellwinkel", 50)
_thread.start_new_thread( aktualisiere_Gui_mit_Daten_von_ST, () ) #soll parallel immer laufen und Gui aktualisieren
app.go()
|
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flaskblog.config import Config
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_manager.login_message_category = 'info'
mail = Mail()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
bcrypt.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
from flaskblog.users.routes import users
from flaskblog.posts.routes import posts
from flaskblog.main.routes import main
app.register_blueprint(users)
app.register_blueprint(posts)
app.register_blueprint(main)
return app
|
'''22. Sabe-se que o quilowatt de energia custa um quinto do salário mínimo. Faça um programa que
receba o valor do salário mínimo e a quantidade de quilowatts consumida por uma residência.
Calcule e mostre:
o valor de cada quilowatt;
o valor a ser pago por essa residência;
o valor a ser pago com desconto de 15%.'''
#saida
salario = float(input("Informe o sálario: "))
quantidade_quilowatts = float(input("Informe a quantidade de quilowatts: "))
#processamento
valor_de_quilowatts = salario / 5
valor_em_reais = valor_de_quilowatts * quantidade_quilowatts
valor_descontado = valor_em_reais * 15 / 100
valor_com_desconto = valor_em_reais - valor_descontado
#saida
print("Valor de quilowatts: ",valor_de_quilowatts)
print("Valor em reais: ",valor_em_reais)
print("Valor com desconto: ",valor_com_desconto) |
# -*- coding: utf-8 -*-
UNICA_BASE_URL = "http://www.unica.fi"
UNICA_RESTAURANTS = []
def append_to(list, this):
list.append(this)
UNICA_ASSARI = {
"name": "Assarin ullakko",
"id": "assarin_ullakko",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/assarin-ullakko/",
"url_en": UNICA_BASE_URL + "/en/restaurants/assarin-ullakko/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/assarin-ullakko/"
}
append_to(UNICA_RESTAURANTS, UNICA_ASSARI)
UNICA_BRYGGE = {
"name": "Brygge",
"id": "brygge",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/brygge/",
"url_en": UNICA_BASE_URL + "/en/restaurants/brygge/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/brygge/"
}
append_to(UNICA_RESTAURANTS, UNICA_BRYGGE)
UNICA_DELICA = {
"name": "Delica",
"id": "delica",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/delica/",
"url_en": UNICA_BASE_URL + "/en/restaurants/delica/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/delica/"
}
append_to(UNICA_RESTAURANTS, UNICA_DELICA)
UNICA_DELIPHARMA = {
"name": "Delipharma",
"id": "delipharma",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/deli-pharma/",
"url_en": UNICA_BASE_URL + "/en/restaurants/deli-pharma/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/deli-pharma/"
}
append_to(UNICA_RESTAURANTS, UNICA_DELIPHARMA)
UNICA_DENTAL = {
"name": "Dental",
"id": "dental",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/dental/",
"url_en": UNICA_BASE_URL + "/en/restaurants/dental/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/dental/"
}
append_to(UNICA_RESTAURANTS, UNICA_DENTAL)
UNICA_MACCIAVELLI = {
"name": "Macciavelli",
"id": "macciavelli",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/macciavelli/",
"url_en": UNICA_BASE_URL + "/en/restaurants/macciavelli/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/macciavelli/"
}
append_to(UNICA_RESTAURANTS, UNICA_MACCIAVELLI)
UNICA_MIKRO = {
"name": "Mikro",
"id": "mikro",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/mikro/",
"url_en": UNICA_BASE_URL + "/en/restaurants/mikro/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/mikro/"
}
append_to(UNICA_RESTAURANTS, UNICA_MIKRO)
UNICA_MYSSY = {
"name": "Galilei",
"id": "galilei",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/galilei/",
"url_en": UNICA_BASE_URL + "/en/restaurants/galilei/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/galilei/"
}
append_to(UNICA_RESTAURANTS, UNICA_MYSSY)
UNICA_NUTRITIO = {
"name": "Nutritio",
"id": "nutritio",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/nutritio/",
"url_en": UNICA_BASE_URL + "/en/restaurants/nutritio/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/nutritio/"
}
append_to(UNICA_RESTAURANTS, UNICA_NUTRITIO)
UNICA_RUOKAKELLO = {
"name": "Ruokakello",
"id": "ruokakello",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/ruokakello/",
"url_en": UNICA_BASE_URL + "/en/restaurants/ruokakello/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/ruokakello/"
}
append_to(UNICA_RESTAURANTS, UNICA_RUOKAKELLO)
UNICA_TOTTISALMI = {
"name": "Tottisalmi",
"id": "tottisalmi",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/tottisalmi/",
"url_en": UNICA_BASE_URL + "/en/restaurants/tottisalmi/",
"url_swe": UNICA_BASE_URL + "/se/restauranger/tottisalmi/"
}
append_to(UNICA_RESTAURANTS, UNICA_TOTTISALMI)
|
### https://github.com/RomelTorres/alpha_vantage
from key import KEY
symbol = "GOOGL"
def intrday_timeseries(key, symbol):
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key=KEY, output_format="pandas", indexing_type="date")
# Get json object with the intraday data and another with the call's metadata
# data, meta_data = ts.get_intraday(symbol)
data, meta_data = ts.get_daily(symbol)
print(f"Data:\n{data}\nmeta_data:\n{meta_data}")
# intrday_timeseries(KEY, symbol)
def bollinger_bands(key, symbol):
from alpha_vantage.techindicators import TechIndicators
import matplotlib.pyplot as plt
ti = TechIndicators(key=key, output_format="pandas")
data, meta_data = ti.get_bbands(symbol=symbol, interval="60min", time_period=60)
data.plot()
plt.title("BBbands indicator for MSFT stock (60 min)")
plt.show()
# bollinger_bands(KEY, symbol)
def sector_performance_graph(key):
from alpha_vantage.sectorperformance import SectorPerformances
import matplotlib.pyplot as plt
sp = SectorPerformances(key=key, output_format="pandas")
data, meta_data = sp.get_sector()
data["Rank A: Real-Time Performance"].plot(kind="bar")
plt.title("Real Time Performance (%) per Sector")
plt.tight_layout()
plt.grid()
plt.show()
# sector_performance_graph(KEY)
def crypto_currencies(key, symbol, market="CNY"):
from alpha_vantage.cryptocurrencies import CryptoCurrencies
import matplotlib.pyplot as plt
cc = CryptoCurrencies(key=key, output_format="pandas")
data, meta_data = cc.get_digital_currency_daily(symbol=symbol, market=market)
data["4b. close (USD)"].plot()
plt.tight_layout()
plt.title("Daily close value for bitcoin (BTC)")
plt.grid()
plt.show()
crypto_currencies(KEY, "BTC")
|
from pyspark import SparkContext, SparkConf
if __name__ == "__main__":
'''
"in/nasa_19950701.tsv" file contains 10000 log lines from one of NASA's apache server for July 1st, 1995.
"in/nasa_19950801.tsv" file contains 10000 log lines for August 1st, 1995
Create a Spark program to generate a new RDD which contains the hosts which are accessed on BOTH days.
Save the resulting RDD to "out/nasa_logs_same_hosts.csv" file.
Example output:
vagrant.vf.mmc.com
www-a1.proxy.aol.com
.....
Keep in mind, that the original log files contains the following header lines.
host logname time method url response bytes
Make sure the head lines are removed in the resulting RDD.
'''
conf = SparkConf().setAppName("sameHosts").setMaster("local[1]")
sc = SparkContext(conf=conf)
julyFirstLogs = sc.textFile("inputs/nasa_19950701.tsv")
augustFirstLogs = sc.textFile("inputs/nasa_19950801.tsv")
julyFirstHosts = julyFirstLogs.map(lambda line: line.split("\t")[0])
augustFirstHosts = augustFirstLogs.map(lambda line: line.split("\t")[0])
intersection = julyFirstHosts.intersection(augustFirstHosts)
cleanedHostIntersection = intersection.filter(lambda host: host != "host")
cleanedHostIntersection.saveAsTextFile("outputs/nasa_logs_same_hosts.csv")
|
from validator_views import BaseValidatorView
from payload_validator import CreateTeamValidator
class CreateTeam(BaseValidatorView):
payload_validator = CreateTeamValidator
|
#!/usr/bin/python3.7
import argparse
import base64
import hashlib
import json
import re
import os
import yaml
from PIL import Image
import common
import oauth2
SECRET_KEY_LENGTH = 16
BASE_IMG = "map_base{}.png"
CLOUD_IMG = "cloud{}.png"
def upload_file(path, options, processor=None):
ext = os.path.splitext(path)[1].lower()
if ext not in common.CONTENT_TYPES:
raise ValueError(f"Don't know Content-Type for '{path}'.")
with open(path, "rb") as f:
data = f.read()
if processor: data = processor(data)
h = hashlib.sha256()
h.update(data)
name = base64.urlsafe_b64encode(h.digest()).decode("ascii")[:SECRET_KEY_LENGTH]
target_path = f"{name}{ext}"
url = f"https://{options.public_host}/{target_path}"
common.upload_object(path, options.bucket, target_path, common.CONTENT_TYPES[ext],
data, options.credentials)
return url
def get_image_size(path):
im = Image.open(path)
return im.size
def convert_map(shortname, d, options):
out = {"title": d["title"]}
def copyif(k):
if k in d: out[k] = d[k]
copyif("symbol")
copyif("land_order")
copyif("color")
copyif("guess_interval")
copyif("guess_max")
copyif("open_at")
copyif("initial_puzzles")
copyif("order")
copyif("additional_order")
copyif("base_min_puzzles")
print(f"Parsing {shortname} \"{d['title']}\"...")
base_img = os.path.join(options.input_assets, shortname,
BASE_IMG.format(""))
if os.path.exists(base_img):
out["base_size"] = get_image_size(base_img)
out["base_img"] = upload_file(base_img, options)
else:
i = 0
out["base_size"] = []
out["base_img"] = []
while True:
base_img = os.path.join(options.input_assets, shortname,
BASE_IMG.format(i))
if not os.path.exists(base_img): break
out["base_size"].append(get_image_size(base_img))
out["base_img"].append(upload_file(base_img, options))
i += 1
assert out["base_img"]
i = 0
out["cloud_img"] = []
while True:
cloud_img = os.path.join(options.input_assets, shortname,
CLOUD_IMG.format(i))
if not os.path.exists(cloud_img): break
out["cloud_img"].append(upload_file(cloud_img, options))
i += 1
if not i: out.pop("cloud_img")
if "logo" in d:
src_image = os.path.join(options.input_assets, shortname,
d["logo"])
url = upload_file(src_image, options)
out["logo"] = url
assignments = d.get("assignments", {})
if assignments:
out["assignments"] = assignments
offsets = d.get("offsets", {})
icons = d.get("icons", None)
if icons:
out_icons = {}
out["icons"] = out_icons
for name, ic in icons.items():
oic = {}
out_icons[name] = oic
if name in offsets:
oic["offset"] = offsets[name]
if name in assignments and "headerimage" in assignments[name]:
src = os.path.join(options.input_assets, shortname,
assignments[name]["headerimage"])
oic["headerimage"] = upload_file(src, options)
for variant in ("image", "mask", "under",
"emptypipe0", "fullpipe0",
"emptypipe1", "fullpipe1",
"emptypipe2", "fullpipe2"):
icon_image = os.path.join(options.input_assets, shortname,
f"{variant}_{name}.png")
if not os.path.exists(icon_image): continue
voic = dict(ic[variant])
oic[variant] = voic
voic["url"] = upload_file(icon_image, options)
# If poly isn't specified, make a rectangle covering the whole icon.
if "poly" not in voic and "pos" in voic:
x, y = voic["pos"]
w, h = voic["size"]
voic["poly"] = f"{x},{y},{x+w},{y},{x+w},{y+h},{x},{y+h}"
return out
def convert_static_files(out, options, lands):
print("Processing static assets...")
def css_processor(data):
text = data.decode("utf-8")
def replacer(m):
return out.get(m.group(1), m.group(1))[0]
text = re.sub(r"@@STATIC:([^@]+)@@", replacer, text)
return text.encode("utf-8")
base = os.getenv("HUNT2020_BASE")
absbase = os.path.abspath(base) + "/"
to_convert = []
for land in list(lands) + ["runaround", "workshop"]:
land_dir = os.path.join(options.input_assets, land)
for fn in os.listdir(land_dir):
if fn.startswith("land_") and fn.endswith(".png"):
to_convert.append((os.path.join(land, fn), os.path.join(land_dir, fn)))
for xfn in ("land.css", "land-compiled.css", "solve.mp3", "fastpass.png"):
fn = os.path.join(options.input_assets, land, xfn)
if os.path.exists(fn):
to_convert.append((os.path.join(land, xfn), fn))
to_convert.extend([
("end_solve.mp3", os.path.join(options.input_assets, "end_solve.mp3")),
("events_solve.mp3", os.path.join(options.input_assets, "events_solve.mp3")),
("reveal.mp3", os.path.join(options.input_assets, "reveal.mp3")),
("reveal_over.png", os.path.join(options.input_assets, "reveal_over.png")),
("reveal_under.png", os.path.join(options.input_assets, "reveal_under.png")),
])
to_convert.extend([("mute.png", f"{base}/snellen/static/mute.png"),
("emojisprite.png", f"{base}/snellen/static/emojisprite.png"),
("pennypass.png", f"{base}/snellen/static/pennypass.png"),
("ppicon1.png", f"{base}/snellen/static/ppicon1.png"),
("ppicon2.png", f"{base}/snellen/static/ppicon2.png"),
("ppicon3.png", f"{base}/snellen/static/ppicon3.png"),
("remote16.png", f"{base}/snellen/static/remote16.png"),
("admin-compiled.js", f"{base}/snellen/bin/admin-compiled.js"),
("visit-compiled.js", f"{base}/snellen/bin/visit-compiled.js"),
("client-compiled.js", f"{base}/snellen/bin/client-compiled.js"),
("admin.css", f"{base}/snellen/static/admin.css"),
("admin-lite.css", f"{base}/snellen/static/admin-lite.css"),
("event.css", f"{base}/snellen/static/event.css"),
("event-compiled.css", f"{base}/snellen/bin/event-compiled.css"),
("default.css", f"{base}/snellen/static/default.css"),
("default-compiled.css", f"{base}/snellen/bin/default-compiled.css"),
("login.css", f"{base}/snellen/static/login.css"),
("login-compiled.css", f"{base}/snellen/bin/login-compiled.css"),
("notopen.css", f"{base}/snellen/static/notopen.css"),
("notopen-compiled.css", f"{base}/snellen/bin/notopen-compiled.css"),
("logo.png", f"{base}/snellen/static/logo.png"),
("logo-nav.png", f"{base}/snellen/static/logo-nav.png"),
("emoji.json", f"{base}/snellen/static/emoji.json"),
("opening.mp4", f"{base}/media/opening.mp4"),
# ("video1.mp4", f"{base}/media/video1.mp4"),
# ("video2.mp4", f"{base}/media/video2.mp4"),
# ("video3.mp4", f"{base}/media/video3.mp4"),
# ("video4.mp4", f"{base}/media/video4.mp4"),
# ("video5.mp4", f"{base}/media/video5.mp4"),
# ("video6.mp4", f"{base}/media/video6.mp4"),
("thumb1.png", f"{base}/media/thumb1.png"),
("thumb2.png", f"{base}/media/thumb2.png"),
("thumb3.png", f"{base}/media/thumb3.png"),
("thumb4.png", f"{base}/media/thumb4.png"),
("thumb5.png", f"{base}/media/thumb5.png"),
("thumb6.png", f"{base}/media/thumb6.png"),
# ("poster1.png", f"{base}/media/poster1.png"),
# ("poster2.png", f"{base}/media/poster2.png"),
# ("poster3.png", f"{base}/media/poster3.png"),
# ("poster4.png", f"{base}/media/poster4.png"),
# ("poster5.png", f"{base}/media/poster5.png"),
# ("poster6.png", f"{base}/media/poster6.png"),
("admin_fav_green/favicon-32x32.png",
f"{base}/snellen/static/admin_fav_green/favicon-32x32.png"),
("admin_fav_green/favicon-16x16.png",
f"{base}/snellen/static/admin_fav_green/favicon-16x16.png"),
("admin_fav_amber/favicon-32x32.png",
f"{base}/snellen/static/admin_fav_amber/favicon-32x32.png"),
("admin_fav_amber/favicon-16x16.png",
f"{base}/snellen/static/admin_fav_amber/favicon-16x16.png"),
("admin_fav_red/favicon-32x32.png",
f"{base}/snellen/static/admin_fav_red/favicon-32x32.png"),
("admin_fav_red/favicon-16x16.png",
f"{base}/snellen/static/admin_fav_red/favicon-16x16.png"),
("admin_fav_blue/favicon-32x32.png",
f"{base}/snellen/static/admin_fav_blue/favicon-32x32.png"),
("admin_fav_blue/favicon-16x16.png",
f"{base}/snellen/static/admin_fav_blue/favicon-16x16.png"),
("favicon-32x32.png", f"{base}/snellen/static/favicon-32x32.png"),
("favicon-16x16.png", f"{base}/snellen/static/favicon-16x16.png"),
])
for rp in ("safari.jpg", "space.jpg", "cascade_flow.png", "cascade_grid.png",
"cascade_start.jpg", "canyon.jpg", "studios_seal.png",
"studios_coins.png", "studios_wall.png", "yesterday_start.png"):
to_convert.append((f"runaround/{rp}", f"{base}/media/runaround/{rp}"))
for mp in ("thinkfun", "gr8ergood", "cluekeeper", "janestreet", "grandmaster",
"judy", "penny",
"jeon_paisa", "kobo", "centime", "luma", "dirham", "kopek"):
to_convert.append((f"{mp}.png", f"{base}/media/{mp}.png"))
# Process .css files last.
to_convert.sort(key=lambda x: (1 if x[0].endswith(".css") else 0, x[0]))
for key, fn in to_convert:
processor = css_processor if fn.endswith(".css") else None
outfn = os.path.abspath(fn)
assert outfn.startswith(absbase)
outfn = outfn[len(absbase):]
out[key] = (upload_file(fn, options, processor=processor), outfn)
def main():
parser = argparse.ArgumentParser(
description="Process an event yaml file and upload assets to GCS.")
parser.add_argument("--input_dir", help="Directory with inputs to process.")
parser.add_argument("--output_dir", help="Directory to receive output.")
parser.add_argument("--credentials", help="Private key for google cloud service account.")
parser.add_argument("--bucket", help="Google cloud bucket to use.")
parser.add_argument("--public_host", help="Hostname for assets in urls.")
parser.add_argument("--skip_upload", action="store_true",
help="Don't actually upload to GCS.")
options = parser.parse_args()
assert os.getenv("HUNT2020_BASE")
options.input_assets = os.path.join(options.input_dir, "assets")
if not options.public_host:
options.public_host = options.bucket + ".storage.googleapis.com"
options.credentials = oauth2.Oauth2Token(options.credentials)
common.load_object_cache(options.bucket, options.credentials)
print("Loading map_config.yaml...")
with open(os.path.join(options.input_dir, "map_config.yaml")) as f:
y = yaml.safe_load(f)
for land in y.keys():
if land in ("events", "workshop", "runaround", "constants", "videos"): continue
print(f"Loading assets/{land}/land.yaml...")
with open(os.path.join(options.input_dir, "assets", land, "land.yaml")) as f:
y[land].update(yaml.safe_load(f))
output_file = os.path.join(options.output_dir, "map_config.json")
output = {}
output["maps"] = {}
for shortname, d in y.items():
if shortname in ("events", "workshop", "runaround", "constants", "videos"): continue
output["maps"][shortname] = convert_map(shortname, d, options)
output["static"] = {}
convert_static_files(output["static"], options, output["maps"].keys())
output["static"]["emoji"] = f"https://{options.public_host}/emoji/"
output["events"] = y.get("events", {})
output["workshop"] = y.get("workshop", {})
output["runaround"] = y.get("runaround", {})
output["constants"] = y.get("constants", {})
output["videos"] = y.get("videos", [])
with open(output_file, "w") as f:
json.dump(output, f, sort_keys=True, indent=2)
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
"""
/***************************************************************************
RemoteRenderer
A QGIS plugin
Communicates with other programs via websockets and renders requested extents
-------------------
begin : 2019-08-19
copyright : (C) 2019-2021 by BOKU ILEN, MR, CG
email : christoph.graf@boku.ac.at
git sha : $Format:%H$
***************************************************************************/
This script initializes the plugin, making it known to QGIS.
"""
# Load RemoteRenderer class from file RemoteRenderer
def classFactory(iface):
from .remote_renderer import RemoteRenderer
return RemoteRenderer(iface)
|
import pytest
import re
class TestMismatchedBrackets:
def test_it_knows_about_mismatched_square_from_parenthesis(self):
original = """
def wat(self:
pass
things = "]"
def things]self:
pass
"""
expected = re.escape(
"Trying to close the wrong type of bracket. Found ']' (line 6, column 10) instead of closing a '(' (line 1, column 7)"
)
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
def test_it_knows_about_mismatched_square_from_curly(self):
original = """
def wat{self:
pass
def things]self:
pass
"""
expected = re.escape(
"Trying to close the wrong type of bracket. Found ']' (line 4, column 10) instead of closing a '{' (line 1, column 7)"
)
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
def test_it_knows_about_mismatched_parenthesis_from_square(self):
original = """
def wat[self:
pass
def things)self:
pass
"""
expected = re.escape(
"Trying to close the wrong type of bracket. Found ')' (line 4, column 10) instead of closing a '[' (line 1, column 7)"
)
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
def test_it_knows_about_hanging_square(self):
original = """
def wat(self):
pass
def things]self:
pass
"""
expected = re.escape("Found a hanging ']' on line 4, column 10")
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
def test_it_knows_about_hanging_parenthesis(self):
original = """
def wat(self)):
pass
"""
expected = re.escape("Found a hanging ')' on line 1, column 13")
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
def test_it_knows_about_hanging_curly(self):
original = """
class Wat:
def __init__(self):
self.d = {1: 2}}
"""
expected = re.escape("Found a hanging '}' on line 3, column 23")
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
def test_it_knows_about_unclosed_parenthesis(self):
original = """
def thing(self):
pass
def wat(self:
pass
"""
expected = re.escape("Found an open '(' (line 4, column 7) that wasn't closed")
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
def test_it_knows_about_unclosed_square(self):
original = """
def thing(self):
pass
things = [1, 2
"""
expected = re.escape("Found an open '[' (line 4, column 9) that wasn't closed")
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
def test_it_knows_about_unclosed_curly(self):
original = """
def thing(self):
pass
things = [1, 2]
stuff = {1: 2
"""
expected = re.escape("Found an open '{' (line 6, column 8) that wasn't closed")
with pytest.raises(SyntaxError, match=expected):
pytest.helpers.assert_conversion(original, "")
|
# Generated by Django 3.2.3 on 2021-07-13 08:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0012_alter_user_name'),
('authentication', '0003_auto_20210709_1926'),
]
operations = [
migrations.RenameModel(
old_name='GmailAuthentication',
new_name='GoogleAuthentication',
),
]
|
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from profiles.models import Profile
from protocols.models import Protocol, Step, Action, Component
# from steps.models import Step
from organization.models import Organization, Membership
from protocols.tests.core import AutoBaseTest
class ProtocolViewTests(AutoBaseTest):
def setUp(self):
super(ProtocolViewTests, self).setUp()
self.user = self.createUserInstance(username="testuser", password="pass", email="test@example.com") # USER SETUP
self.userTwo = self.createUserInstance(username="test2user", password="pass", email="test2@example.com") # USER SETUP
self.profile = self.createModelInstance(Profile, user=self.user) # USER PROFILE SETUP
self.org = self.createModelInstance(Organization, name="TestOrg") # CREATE THE ORGANIZATION
self.orgTwo = self.createModelInstance(Organization, name="TestOrgTwo") # CREATE THE ORGANIZATION
self.member = self.createModelInstance(Membership, user=self.user, org=self.org, role="a") # ADD THE MEMBERSHIP
self.protocol = self.createModelInstance(Protocol, name="Test Protocol", owner=self.org, author=self.user) # CREATE PROTOCOL
self.protocolTwo = self.createModelInstance(Protocol, name="Test Protocol Two", owner=self.orgTwo, author=self.userTwo) # CREATE PROTOCOL
def test_create_protocol(self):
url = reverse("protocol_create", kwargs={'owner_slug': self.org.slug})
self.assertTrue(self.client.login(username='testuser', password='pass'))
data = dict(name="Test Protoco 2l", raw="blag nlag")
response = self.client.post(url, data, follows=True)
def test_protocol_detail(self):
self.assertTrue(self.client.login(username='testuser', password='pass'))
url = self.protocol.get_absolute_url()
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
# self.assertContains(response, '<td><a href="/protocols/test-protocol/steps/test-step/">Test Step</a></td>')
def test_protocol_update(self):
self.assertTrue(self.client.login(username='testuser', password='pass'))
url = self.protocol.protocol_update_url()
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_protocol_no_update(self):
self.assertTrue(self.client.login(username='testuser', password='pass'))
url = self.protocolTwo.protocol_update_url()
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_index(self):
resp = self.client.get('/')
self.assertEqual(resp.status_code, 200)
|
from graphviz import Digraph
from model.process import Process
dot = Digraph(comment='Microservices Process Roadmap', format='png')
process = Process()
process.build(dot)
dot.render('images/microservices-process-roadmap.gv')
|
# 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 mock
from nova.api.openstack.compute import console_auth_tokens
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit.policies import base
class ConsoleAuthTokensPolicyTest(base.BasePolicyTest):
"""Test Console Auth Tokens APIs policies with all possible context.
This class defines the set of context with different roles
which are allowed and not allowed to pass the policy checks.
With those set of context, it will call the API operation and
verify the expected behaviour.
"""
def setUp(self):
super(ConsoleAuthTokensPolicyTest, self).setUp()
self.controller = console_auth_tokens.ConsoleAuthTokensController()
self.req = fakes.HTTPRequest.blank('', version='2.31')
# Check that system reader is able to get console connection
# information.
# NOTE(gmann): Until old default rule which is admin_api is
# deprecated and not removed, project admin and legacy admin
# will be able to get console. This make sure that existing
# tokens will keep working even we have changed this policy defaults
# to reader role.
self.reader_authorized_contexts = [
self.system_admin_context, self.system_member_context,
self.system_reader_context, self.legacy_admin_context,
self.project_admin_context]
# Check that non-admin is not able to get console connection
# information.
self.reader_unauthorized_contexts = [
self.system_foo_context, self.other_project_member_context,
self.project_foo_context, self.project_member_context,
self.project_reader_context]
@mock.patch('nova.objects.ConsoleAuthToken.validate')
def test_console_connect_info_token_policy(self, mock_validate):
rule_name = "os_compute_api:os-console-auth-tokens"
self.common_policy_check(self.reader_authorized_contexts,
self.reader_unauthorized_contexts,
rule_name, self.controller.show,
self.req, fakes.FAKE_UUID)
class ConsoleAuthTokensScopeTypePolicyTest(ConsoleAuthTokensPolicyTest):
"""Test Console Auth Tokens APIs policies with system scope enabled.
This class set the nova.conf [oslo_policy] enforce_scope to True
so that we can switch on the scope checking on oslo policy side.
It defines the set of context with scoped token
which are allowed and not allowed to pass the policy checks.
With those set of context, it will run the API operation and
verify the expected behaviour.
"""
def setUp(self):
super(ConsoleAuthTokensScopeTypePolicyTest, self).setUp()
self.flags(enforce_scope=True, group="oslo_policy")
# Check that system reader is able to get console connection
# information.
self.reader_authorized_contexts = [
self.system_admin_context, self.system_member_context,
self.system_reader_context]
# Check that non-system-reader is not able to get console connection
# information.
self.reader_unauthorized_contexts = [
self.legacy_admin_context, self.system_foo_context,
self.project_admin_context, self.project_member_context,
self.other_project_member_context,
self.project_foo_context, self.project_reader_context
]
|
# pattern.py -- Rename pattern
"""Pattern base module"""
import re
import os
from morph.errors import (
PatternModeError,
)
MODE_APPEND = "append"
MODE_REPLACE = "replace"
MODE_INSERT = "insert"
MODES = [MODE_APPEND, MODE_REPLACE, MODE_INSERT]
def generatePattern(pat, mode=MODE_APPEND):
if isinstance(pat, str):
if re.match('^#+$', pat):
return NumericCounterPattern(padding=len(pat), mode=mode)
else:
return LiteralPattern(pat, mode=mode)
else:
raise TypeError(pat)
class Pattern(object):
"""A Rename Pattern"""
def apply_to_string(self, original, new, position):
raise NotImplementedError()
def reset(self):
raise NotImplementedError()
class LiteralPattern(Pattern):
def __init__(self, literal=None, mode=MODE_APPEND, position=0):
super(LiteralPattern, self).__init__()
if literal is None:
raise ValueError('literal needed')
self.literal = literal
self.mode = mode
self.position = int(position)
def __eq__(self, other):
return isinstance(other, LiteralPattern) and \
self.literal == other.literal and \
self.mode == other.mode
def apply_to_string(self, original, new, position):
dirname, basename = os.path.split(new)
if self.mode == MODE_APPEND:
name = basename + self.literal
elif self.mode == MODE_INSERT:
name = basename[:self.position] + \
self.literal + basename[self.position:]
elif self.mode == MODE_REPLACE:
name = self.literal
else:
raise PatternModeError(self.mode)
return os.path.join(dirname, name)
def reset(self):
pass
def __str__(self):
if self.mode == MODE_APPEND:
return 'Literal (%s, %s)' % (self.mode, self.literal)
elif self.mode == MODE_INSERT:
return 'Literal (%s, %d, %s)' % (self.mode, self.position, self.literal)
elif self.mode == MODE_REPLACE:
return 'Literal (%s, %s)' % (self.mode, self.literal)
else:
raise PatternModeError(self.mode)
class NumericCounterPattern(Pattern):
def __init__(self, start=1, padding=2, mode=MODE_APPEND, position=0):
super(NumericCounterPattern, self).__init__()
self.start = int(start)
self.counter = int(start)
self.padding = int(padding)
self.mode = mode
self.position = int(position)
def __eq__(self, other):
return isinstance(other, NumericCounterPattern) and \
self.start == other.start and \
self.padding == other.padding and \
self.mode == other.mode
def apply_to_string(self, original, new, position):
dirname, basename = os.path.split(new)
self.counter += 1
counterstr = ('%%0%dd' % self.padding) % (self.counter - 1)
if self.mode == MODE_APPEND:
name = basename + counterstr
elif self.mode == MODE_INSERT:
name = basename[:self.position] + \
counterstr + basename[self.position:]
elif self.mode == MODE_REPLACE:
name = counterstr
else:
raise PatternModeError(self.mode)
return os.path.join(dirname, name)
def reset(self):
self.counter = self.start
def __str__(self):
if self.mode == MODE_APPEND:
return 'NumericCounter (%s, %d, %d, %d)' % (self.mode, self.start, self.counter, self.padding)
elif self.mode == MODE_INSERT:
return 'NumericCounter (%s, %d, %d, %d, %d)' % (self.mode, self.position,
self.start, self.counter, self.padding)
elif self.mode == MODE_REPLACE:
return 'NumericCounter (%s, %d, %d, %d)' % (self.mode, self.start, self.counter, self.padding)
else:
raise PatternModeError(self.mode)
patternmap = {
'literal': LiteralPattern,
'numericcounter' : NumericCounterPattern,
}
|
# 数据库吧code拿出来
import pymysql
def get_code(problem_id, problem_name, challenge=False):
if challenge:
sql = "SELECT pc.code from problem_code pc join problem p WHERE p.id = pc.problem_id and p.title=%s"
else:
sql = "SELECT code_python FROM dim_subject_problem WHERE id=%s"
tup_code = execute_sql(sql, problem_id, problem_name, challenge)
try:
code = tup_code[0][0]
except IndexError:
code = '没有查询到题目代码'
except Exception as e:
code = f'{e}, 查询代码异常'
return code
def get_choice(problem_id, problem_name, challenge=False):
sql = "SELECT answer from dim_subject_choice WHERE id=%s"
tup_choice = execute_sql(sql, problem_id, problem_name, challenge)
try:
choice = tup_choice[0][0]
except IndexError:
choice = '没有查询到答案'
except BaseException as e:
choice = f'{e},查询答案异常'
return choice
def execute_sql(sql, problem_id, problem_name, challenge):
db = pymysql.connect('sh-cdb-9emlkgqw.sql.tencentcdb.com', 'root', 'zsyl@2020', 'pt_edu3', 61227)
cursor = db.cursor()
if challenge:
cursor.execute(sql, (problem_name,))
else:
cursor.execute(sql, (problem_id,))
data = cursor.fetchall()
db.close()
return data
# print(get_code(problem_id=9317, problem_name=None, challenge=False))
# print(get_choice(problem_id=438, problem_name=None, challenge=False))
|
#!/usr/bin/env python
"""
############################################
Similiar Item Analysis Module Work Book View
############################################
"""
# -*- coding: utf-8 -*-
#
# rtk.analyses.similiar_item.gui.gtk.WorkBook.py is part of The RTK
# Project
#
# All rights reserved.
# Copyright 2007 - 2017 Andrew Rowland andrew.rowland <AT> reliaqual <DOT> com
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
# Import modules for localization support.
import gettext
import locale
# Modules required for the GUI.
from lxml import etree
import pango
try:
import pygtk
pygtk.require('2.0')
except ImportError:
sys.exit(1)
try:
import gtk
except ImportError:
sys.exit(1)
try:
import gtk.glade
except ImportError:
sys.exit(1)
try:
import gobject
except ImportError:
sys.exit(1)
# Import other RTK modules.
try:
import Configuration
import Utilities
import gui.gtk.Widgets as Widgets
except ImportError:
import rtk.Configuration as Configuration
import rtk.Utilities as Utilities
import rtk.gui.gtk.Widgets as Widgets
__author__ = 'Andrew Rowland'
__email__ = 'andrew.rowland@reliaqual.com'
__organization__ = 'ReliaQual Associates, LLC'
__copyright__ = 'Copyright 2007 - 2015 Andrew "weibullguy" Rowland'
try:
locale.setlocale(locale.LC_ALL, Configuration.LOCALE)
except locale.Error:
locale.setlocale(locale.LC_ALL, '')
_ = gettext.gettext
class WorkView(gtk.HBox): # pylint: disable=R0902
"""
The Work Book view displays all the attributes for the selected Similar
Item Analysis. The attributes of a Similar Item Analysis Work Book view
are:
:ivar list _lst_handler_id: default value: []
:ivar :py:class:`rtk.analyses.similar_item.SimilarItem.SimilarItem` dtcSimilarItem:
the Similar Item Analysis data controller.
:ivar gtk.Button btnEditFunction: the gtk.Button() to launch the function
editor.
:ivar gtk.Button btnCalculate: the gtk.Button() to calculate the Similar
Item Analysis.
:ivar gtk.Button btnSave: the gtk.Button() to save the Similar Item
Analysis.
:ivar gtk.ComboBox cmbSimilarItemMethod: the gtk.ComboBox() to select the
the Similar Item Analysis method.
:ivar gtk.ComboBox cmbFromQuality: the gtk.ComboBox() to select the
surrogate system's quality.
:ivar gtk.ComboBox cmbToQuality: the gtk.ComboBox() to select the new
system's quality.
:ivar gtk.ComboBox cmbFromEnvironment: the gtk.ComboBox() to select the
surrogate system's operating
environment.
:ivar gtk.ComboBox cmbToEnvironment: the gtk.ComboBox() to select the new
system's operating environment.
:ivar gtk.TreeView tvwSimilarItem: the gtk.TreeView() that displays the
Similar Item Analysis.
:ivar gtk.Entry txtFromTemperature: the gtk.Entry() to enter the
surrogate system's ambient temperature.
:ivar gtk.Entry txtToTemperature: the gtk.Entry() to enter the new system's
ambient temperature.
"""
def __init__(self, controller, modulebook):
"""
Method to initialize the Work Book view for the Similar Item Analysis
module.
:param controller: the :py:class`rtk.analyses.similar_item.SimilarItem.SimilarItem`
data controller.
:param modulebook: the :py:class:`rtk.hardware.ModuleBook` associated
with the Hazard.
"""
gtk.HBox.__init__(self)
# Define private dictionary attributes.
# Define private list attributes.
self._lst_handler_id = []
# Define private scalar attributes.
self._modulebook = modulebook
# Define public dictionary attributes.
# Define public list attributes.
# Define public scalar attributes.
self.dtcSimilarItem = controller
self.btnEditFunction = Widgets.make_button(width=35, image='edit')
self.btnCalculate = Widgets.make_button(width=35, image='calculate')
self.btnSave = Widgets.make_button(width=35, image='save')
self.cmbSimilarItemMethod = Widgets.make_combo(width=150)
self.cmbFromQuality = Widgets.make_combo(width=150)
self.cmbToQuality = Widgets.make_combo(width=150)
self.cmbFromEnvironment = Widgets.make_combo(width=150)
self.cmbToEnvironment = Widgets.make_combo(width=150)
self.txtFromTemperature = Widgets.make_entry(width=100)
self.txtToTemperature = Widgets.make_entry(width=100)
self.tvwSimilarItem = gtk.TreeView()
# Set tooltips for gtk.Widgets().
self.btnEditFunction.set_tooltip_text(_(u"Edit the user-defined "
u"similar item analyses."))
self.btnCalculate.set_tooltip_text(_(u"Calculates the similar item "
u"analysis for the selected "
u"hardware item."))
self.btnSave.set_tooltip_text(_(u"Saves the selected similiar item "
u"analysis."))
self.cmbSimilarItemMethod.set_tooltip_text(_(u"Selects the method for "
u"determining the "
u"reliability of the new "
u"design based on the "
u"reliability of a "
u"similar item."))
self.cmbFromQuality.set_tooltip_text(_(u"Selects the quality level of "
u"the baseline, similar item."))
self.cmbToQuality.set_tooltip_text(_(u"Selects the quality level of "
u"the new design."))
self.cmbFromEnvironment.set_tooltip_text(_(u"Selects the environment "
u"category of the "
u"baseline, similar item."))
self.cmbToEnvironment.set_tooltip_text(_(u"Selects the environment "
u"category of the new "
u"design."))
self.tvwSimilarItem.set_tooltip_text(_(u"Displays the similar items "
u"analysis for the selected "
u"assembly."))
self.txtFromTemperature.set_tooltip_text(_(u"Selects the operating, "
u"ambient temperature of "
u"the baseline, similar "
u"item."))
self.txtToTemperature.set_tooltip_text(_(u"Selects the operating, "
u"ambient temperature of "
u"the new design."))
# Connect to callback functions.
self._lst_handler_id.append(
self.btnEditFunction.connect('clicked',
self._on_button_clicked, 0))
self._lst_handler_id.append(
self.btnCalculate.connect('clicked', self._on_button_clicked, 1))
self._lst_handler_id.append(
self.btnSave.connect('clicked', self._on_button_clicked, 2))
self._lst_handler_id.append(
self.cmbSimilarItemMethod.connect('changed',
self._on_combo_changed, 3))
self._lst_handler_id.append(
self.cmbFromQuality.connect('changed', self._on_combo_changed, 4))
self._lst_handler_id.append(
self.cmbToQuality.connect('changed', self._on_combo_changed, 5))
self._lst_handler_id.append(
self.cmbFromEnvironment.connect('changed',
self._on_combo_changed, 6))
self._lst_handler_id.append(
self.cmbToEnvironment.connect('changed',
self._on_combo_changed, 7))
self._lst_handler_id.append(
self.txtFromTemperature.connect('focus-out-event',
self._on_focus_out, 8))
self._lst_handler_id.append(
self.txtToTemperature.connect('focus-out-event',
self._on_focus_out, 9))
self.show_all()
def create_page(self): # pylint: disable=R0914
"""
Method to create the Similar Item analysis gtk.Notebook() page for
displaying the similar item analysis for the selected Hardware.
:return: False if successful or True if an error is encountered.
:rtype: boolean
"""
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# Create the Similar Item Analysis gtk.TreeView(). #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
_path = "/root/tree[@name='SIA']/column/usertitle"
_heading = etree.parse(Configuration.RTK_FORMAT_FILE[6]).xpath(_path)
_path = "/root/tree[@name='SIA']/column/datatype"
_datatype = etree.parse(Configuration.RTK_FORMAT_FILE[6]).xpath(_path)
_path = "/root/tree[@name='SIA']/column/widget"
_widget = etree.parse(Configuration.RTK_FORMAT_FILE[6]).xpath(_path)
_path = "/root/tree[@name='SIA']/column/position"
_position = etree.parse(Configuration.RTK_FORMAT_FILE[6]).xpath(_path)
_path = "/root/tree[@name='SIA']/column/editable"
_editable = etree.parse(Configuration.RTK_FORMAT_FILE[6]).xpath(_path)
_path = "/root/tree[@name='SIA']/column/visible"
_visible = etree.parse(Configuration.RTK_FORMAT_FILE[6]).xpath(_path)
# Create a list of GObject datatypes to pass to the model.
_types = []
for i in range(len(_position)):
_types.append(_datatype[i].text)
_gobject_types = []
_gobject_types = [gobject.type_from_name(_types[i])
for i in range(len(_types))]
# Create the model and treeview.
_model = gtk.TreeStore(*_gobject_types)
self.tvwSimilarItem.set_model(_model)
_columns = int(len(_heading))
for i in range(_columns):
_column = gtk.TreeViewColumn()
# self._col_order.append(int(_position_[i].text))
if _widget[i].text == 'spin':
_cell = gtk.CellRendererSpin()
_adjustment = gtk.Adjustment(upper=5.0, step_incr=0.05)
_cell.set_property('adjustment', _adjustment)
_cell.set_property('digits', 2)
else:
_cell = gtk.CellRendererText()
_cell.set_property('editable', int(_editable[i].text))
if int(_editable[i].text) == 0:
_cell.set_property('background', 'light gray')
else:
_cell.set_property('background', Configuration.RTK_COLORS[6])
_cell.set_property('foreground', Configuration.RTK_COLORS[7])
_cell.set_property('wrap-width', 250)
_cell.set_property('wrap-mode', pango.WRAP_WORD)
_cell.connect('edited', self._on_cell_edit,
int(_position[i].text))
_label = gtk.Label()
_label.set_line_wrap(True)
_label.set_alignment(xalign=0.5, yalign=0.5)
_label.set_justify(gtk.JUSTIFY_CENTER)
_label.set_markup("<span weight='bold'>" +
_heading[i].text.replace(" ", "\n") + "</span>")
_label.set_use_markup(True)
_label.show_all()
_column.set_visible(int(_visible[i].text))
_column.pack_start(_cell, True)
_column.set_attributes(_cell, text=int(_position[i].text))
_column.set_widget(_label)
_column.set_cell_data_func(_cell, Widgets.format_cell,
(int(_position[i].text),
_datatype[i].text))
_column.set_resizable(True)
_column.connect('notify::width', Widgets.resize_wrap, _cell)
if i > 0:
_column.set_reorderable(True)
self.tvwSimilarItem.append_column(_column)
self.tvwSimilarItem.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# Build-up the containers for the tab. #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
_bbox = gtk.VButtonBox()
_bbox.set_layout(gtk.BUTTONBOX_START)
self.pack_start(_bbox, False, True)
_vbox = gtk.VBox()
self.pack_end(_vbox, True, True)
_fixed = gtk.Fixed()
_vbox.pack_start(_fixed, False, True)
_scrollwindow = gtk.ScrolledWindow()
_scrollwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
_scrollwindow.add(self.tvwSimilarItem)
_frame = Widgets.make_frame(label=_(u"Similar Item Analysis"))
_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_frame.add(_scrollwindow)
_vbox.pack_end(_frame, True, True)
_bbox.pack_start(self.btnEditFunction, False, False)
_bbox.pack_start(self.btnCalculate, False, False)
_bbox.pack_start(self.btnSave, False, False)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# Place the widgets used to display the similar item analysis. #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# Load the gtk.Combo()
_results = [[_(u"Topic 6.3.3"), 0],
[_(u"User-Defined"), 1]]
Widgets.load_combo(self.cmbSimilarItemMethod, _results)
_results = [[_(u"Space"), 0],
[_(u"Full Military"), 1],
[_(u"Ruggedized"), 2],
[_(u"Commercial"), 3]]
Widgets.load_combo(self.cmbFromQuality, _results)
Widgets.load_combo(self.cmbToQuality, _results)
_results = [[_(u"Ground, Benign"), 0], [_(u"Ground, Mobile"), 1],
[_(u"Naval, Sheltered"), 2],
[_(u"Airborne, Inhabited, Cargo"), 3],
[_(u"Airborne, Rotary Wing"), 4], [_(u"Space, Flight"), 5]]
Widgets.load_combo(self.cmbFromEnvironment, _results)
Widgets.load_combo(self.cmbToEnvironment, _results)
_labels = [_(u"Similar Item Method:"), _(u"From Quality:"),
_(u"To Quality:"), _(u"From Environment:"),
_(u"To Environment:"), _(u"From Temperature:"),
_("To Temperature:")]
_x_pos = 5
_label = Widgets.make_label(_labels[0], width=-1)
_fixed.put(_label, _x_pos, 5)
_x_pos = _x_pos + _label.size_request()[0] + 25
_fixed.put(self.cmbSimilarItemMethod, _x_pos, 5)
_x_pos = 350
_label = Widgets.make_label(_labels[1], width=-1)
_fixed.put(_label, _x_pos, 5)
_width = _label.size_request()[0]
_label = Widgets.make_label(_labels[3], width=-1)
_fixed.put(_label, _x_pos, 40)
_width = max(_width, _label.size_request()[0])
_label = Widgets.make_label(_labels[5], width=-1)
_fixed.put(_label, _x_pos, 75)
_width = max(_width, _label.size_request()[0])
_x_pos = _x_pos + _width + 25
_fixed.put(self.cmbFromQuality, _x_pos, 5)
_fixed.put(self.cmbFromEnvironment, _x_pos, 40)
_fixed.put(self.txtFromTemperature, _x_pos, 75)
_x_pos = 650
_label = Widgets.make_label(_labels[2], width=-1)
_fixed.put(_label, _x_pos, 5)
_width = _label.size_request()[0]
_label = Widgets.make_label(_labels[4], width=-1)
_fixed.put(_label, _x_pos, 40)
_width = max(_width, _label.size_request()[0])
_label = Widgets.make_label(_labels[6], width=-1)
_fixed.put(_label, _x_pos, 75)
_width = max(_width, _label.size_request()[0])
_x_pos = _x_pos + _width + 25
_fixed.put(self.cmbToQuality, _x_pos, 5)
_fixed.put(self.cmbToEnvironment, _x_pos, 40)
_fixed.put(self.txtToTemperature, _x_pos, 75)
return False
def load_page(self, controller, hardware_id, path=None):
"""
Method to load the widgets on the Similar Item Analysis page.
:param `rtk.hardware.Hardware.Hardware` controller: the Hardware data
controller instance
being used by RTK.
:param int hardware_id: the Hardware ID to load the Similar Item
Analysis for.
:keyword str path: the path of the parent hardware item in the Similar
Item Analysis gtk.TreeView().
:return: False if successful or True if an error occurs.
:rtype: bool
"""
_model = self.tvwSimilarItem.get_model()
_model.clear()
# Find all the similar items for the selected Hardware Item.
_similar_items = [self.dtcSimilarItem.dicSimilarItem[_a]
for _a in self.dtcSimilarItem.dicSimilarItem.keys()
if self.dtcSimilarItem.dicSimilarItem[_a].parent_id == hardware_id]
parent_row = None
for _similar_item in _similar_items:
_hardware = controller.dicHardware[_similar_item.hardware_id]
_hazard_rate = _hardware.hazard_rate_logistics
_name = _hardware.name
_data = [_similar_item.hardware_id, _similar_item.sia_id, _name,
_hazard_rate, _similar_item.from_quality,
_similar_item.to_quality, _similar_item.from_environment,
_similar_item.to_environment,
_similar_item.from_temperature,
_similar_item.to_temperature, _similar_item.change_desc_1,
_similar_item.change_factor_1,
_similar_item.change_desc_2,
_similar_item.change_factor_2,
_similar_item.change_desc_3,
_similar_item.change_factor_3,
_similar_item.change_desc_4,
_similar_item.change_factor_4,
_similar_item.change_desc_5,
_similar_item.change_factor_5,
_similar_item.change_desc_6,
_similar_item.change_factor_6,
_similar_item.change_desc_7,
_similar_item.change_factor_7,
_similar_item.change_desc_8,
_similar_item.change_factor_8,
_similar_item.change_desc_9,
_similar_item.change_factor_9,
_similar_item.change_desc_10,
_similar_item.change_factor_10,
_similar_item.function_1, _similar_item.function_2,
_similar_item.function_3, _similar_item.function_4,
_similar_item.function_5, _similar_item.result_1,
_similar_item.result_2, _similar_item.result_3,
_similar_item.result_4, _similar_item.result_5,
_similar_item.user_blob_1, _similar_item.user_blob_2,
_similar_item.user_blob_3, _similar_item.user_blob_4,
_similar_item.user_blob_5, _similar_item.user_float_1,
_similar_item.user_float_2, _similar_item.user_float_3,
_similar_item.user_float_4, _similar_item.user_float_5,
_similar_item.user_int_1, _similar_item.user_int_2,
_similar_item.user_int_3, _similar_item.user_int_4,
_similar_item.user_int_5, _similar_item.parent_id]
_model.append(parent_row, _data)
if path is None:
_root = _model.get_iter_root()
try:
path = _model.get_path(_root)
except TypeError:
return False
_column = self.tvwSimilarItem.get_column(0)
self.tvwSimilarItem.set_cursor(path, None, False)
self.tvwSimilarItem.row_activated(path, _column)
self.tvwSimilarItem.expand_all()
self.cmbSimilarItemMethod.set_active(_similar_items[0].method)
self.cmbFromQuality.set_active(_similar_items[0].from_quality)
self.cmbToQuality.set_active(_similar_items[0].to_quality)
self.cmbFromEnvironment.set_active(_similar_items[0].from_environment)
self.cmbToEnvironment.set_active(_similar_items[0].to_environment)
self.txtFromTemperature.set_text(
str('{0:0.0f}'.format(_similar_items[0].from_temperature)))
self.txtToTemperature.set_text(
str('{0:0.0f}'.format(_similar_items[0].to_temperature)))
return False
def _edit_function(self):
"""
Method to edit the Similar Item Analysis functions.
:returns: False if successful or True if an error is encountered.
:rtype: boolean
"""
(_model, _row) = self.tvwSimilarItem.get_selection().get_selected()
_title = _(u"RTK - Edit Similar Item Analysis Functions")
_label = Widgets.make_label(_(u"You can define up to five functions. "
u"You can use the system failure rate, "
u"selected assembly failure rate, the "
u"change factor, the user float, the "
u"user integer values, and results of "
u"other functions.\n\n \
System hazard rate is hr_sys\n \
Assembly hazard rate is hr\n \
Change factor is pi[1-8]\n \
User float is uf[1-3]\n \
User integer is ui[1-3]\n \
Function result is res[1-5]"), width=600, height=-1, wrap=True)
_label2 = Widgets.make_label(_(u"For example, pi1*pi2+pi3, multiplies "
u"the first two change factors and "
u"adds the value to the third change "
u"factor."),
width=600, height=-1, wrap=True)
# Build the dialog assistant.
_dialog = Widgets.make_dialog(_title)
_fixed = gtk.Fixed()
_y_pos = 10
_fixed.put(_label, 5, _y_pos)
_y_pos += _label.size_request()[1] + 10
_fixed.put(_label2, 5, _y_pos)
_y_pos += _label2.size_request()[1] + 10
_label = Widgets.make_label(_(u"User function 1:"))
_txtFunction1 = Widgets.make_entry()
_txtFunction1.set_text(_model.get_value(_row, 30))
_fixed.put(_label, 5, _y_pos)
_fixed.put(_txtFunction1, 195, _y_pos)
_y_pos += 30
_label = Widgets.make_label(_(u"User function 2:"))
_txtFunction2 = Widgets.make_entry()
_txtFunction2.set_text(_model.get_value(_row, 31))
_fixed.put(_label, 5, _y_pos)
_fixed.put(_txtFunction2, 195, _y_pos)
_y_pos += 30
_label = Widgets.make_label(_(u"User function 3:"))
_txtFunction3 = Widgets.make_entry()
_txtFunction3.set_text(_model.get_value(_row, 32))
_fixed.put(_label, 5, _y_pos)
_fixed.put(_txtFunction3, 195, _y_pos)
_y_pos += 30
_label = Widgets.make_label(_(u"User function 4:"))
_txtFunction4 = Widgets.make_entry()
_txtFunction4.set_text(_model.get_value(_row, 33))
_fixed.put(_label, 5, _y_pos)
_fixed.put(_txtFunction4, 195, _y_pos)
_y_pos += 30
_label = Widgets.make_label(_(u"User function 5:"))
_txtFunction5 = Widgets.make_entry()
_txtFunction5.set_text(_model.get_value(_row, 34))
_fixed.put(_label, 5, _y_pos)
_fixed.put(_txtFunction5, 195, _y_pos)
_y_pos += 30
_chkApplyAll = gtk.CheckButton(label=_(u"Apply to all assemblies."))
_fixed.put(_chkApplyAll, 5, _y_pos)
_fixed.show_all()
_dialog.vbox.pack_start(_fixed) # pylint: disable=E1101
# Run the dialog and apply the changes if the 'OK' button is pressed.
if _dialog.run() == gtk.RESPONSE_ACCEPT:
# Widgets.set_cursor(self._app, gtk.gdk.WATCH)
if _chkApplyAll.get_active():
_row = _model.get_iter_root()
while _row is not None:
_hardware_id = _model.get_value(_row, 0)
_similar_item = self.dtcSimilarItem.dicSimilarItem[_hardware_id]
_similar_item.function_1 = _txtFunction1.get_text()
_similar_item.function_2 = _txtFunction2.get_text()
_similar_item.function_3 = _txtFunction3.get_text()
_similar_item.function_4 = _txtFunction4.get_text()
_similar_item.function_5 = _txtFunction5.get_text()
_model.set_value(_row, 30, _similar_item.function_1)
_model.set_value(_row, 31, _similar_item.function_2)
_model.set_value(_row, 32, _similar_item.function_3)
_model.set_value(_row, 33, _similar_item.function_4)
_model.set_value(_row, 34, _similar_item.function_5)
_row = _model.iter_next(_row)
else:
_hardware_id = _model.get_value(_row, 0)
_similar_item = self.dtcSimilarItem.dicSimilarItem[_hardware_id]
_similar_item.function_1 = _txtFunction1.get_text()
_similar_item.function_2 = _txtFunction2.get_text()
_similar_item.function_3 = _txtFunction3.get_text()
_similar_item.function_4 = _txtFunction4.get_text()
_similar_item.function_5 = _txtFunction5.get_text()
_model.set_value(_row, 30, _similar_item.function_1)
_model.set_value(_row, 31, _similar_item.function_2)
_model.set_value(_row, 32, _similar_item.function_3)
_model.set_value(_row, 33, _similar_item.function_4)
_model.set_value(_row, 34, _similar_item.function_5)
# Widgets.set_cursor(self._app, gtk.gdk.LEFT_PTR)
_dialog.destroy()
return False
def _on_button_clicked(self, __button, index):
"""
Method to respond to gtk.Button() 'clicked' signals and call the
correct function or method, passing any parameters as needed.
:param gtk.Button __button: the gtk.Button() that called this method.
:param int index: the index in the handler ID list of the callback
signal associated with the gtk.Button() that called
this method.
:return: False if successful or True if an error is encountered.
:rtype: bool
"""
_return = False
if index == 0: # Edit functions.
self._edit_function()
elif index == 1: # Calculate the analysis.
_model = self.tvwSimilarItem.get_model()
_row = _model.get_iter_root()
# Retrieve the method of the parent Hardware Item.
_hardware_id = _model.get_value(_row, 0)
_similar_item = self.dtcSimilarItem.dicSimilarItem[_hardware_id]
_method = _similar_item.method
while _row is not None:
_hardware_id = _model.get_value(_row, 0)
_hazard_rate = _model.get_value(_row, 3)
self.dtcSimilarItem.calculate(_hardware_id, _hazard_rate,
_method)
_similar_item = self.dtcSimilarItem.dicSimilarItem[_hardware_id]
_model.set_value(_row, 35, _similar_item.result_1)
_model.set_value(_row, 36, _similar_item.result_2)
_model.set_value(_row, 37, _similar_item.result_3)
_model.set_value(_row, 38, _similar_item.result_4)
_model.set_value(_row, 39, _similar_item.result_5)
_row = _model.iter_next(_row)
elif index == 2: # Save the analysis.
_error_codes = self.dtcSimilarItem.save_all_similar_item()
_error_codes = [_code for _code in _error_codes if _code[1] != 0]
if len(_error_codes) != 0:
for __, _code in enumerate(_error_codes):
_content = "rtk.analyses.similar_item.gui.gtk.WorkBook._on_button_clicked: " \
"Received error code {1:d} while saving " \
"Similar Item for Hardware item " \
"{0:d}.".format(_code[0], _code[1])
self._modulebook.mdcRTK.debug_log.error(_content)
_prompt = _(u"One or more errors occurred while attempting to "
u"save Similar Item Analysis.")
Widgets.rtk_error(_prompt)
_return = True
return _return
def _on_cell_edit(self, cell, path, new_text, index): # pylint: disable=R0912
"""
Method to respond to gtk.CellRenderer() 'edited' signals from the
Similar Item gtk.TreeView().
:param gtk.CellRenderer cell: the gtk.CellRenderer() that called this
method.
:param str path: the path of the selected gtk.TreeIter().
:param str new_text: the new text in the gtk.CellRenderer() that called
this method.
:param int index: the position of the gtk.CellRenderer() in the
gtk.TreeModel().
:return: False if successful or True if an error is encountered.
:rtype: bool
"""
# FIXME: Refactor _on_cell_edit; current McCabe Complexity metric = 40.
(_model, _row) = self.tvwSimilarItem.get_selection().get_selected()
_hardware_id = _model.get_value(_row, 0)
_similar_item = self.dtcSimilarItem.dicSimilarItem[_hardware_id]
_convert = gobject.type_name(_model.get_column_type(index))
if new_text is None:
_model[path][index] = not cell.get_active()
elif _convert == 'gchararray':
_model[path][index] = str(new_text)
elif _convert == 'gint':
_model[path][index] = int(new_text)
elif _convert == 'gfloat':
_model[path][index] = float(new_text)
if index == 10:
_similar_item.change_desc_1 = new_text
elif index == 11:
_similar_item.change_factor_1 = float(new_text)
elif index == 12:
_similar_item.change_desc_2 = new_text
elif index == 13:
_similar_item.change_factor_2 = float(new_text)
elif index == 14:
_similar_item.change_desc_3 = new_text
elif index == 15:
_similar_item.change_factor_3 = float(new_text)
elif index == 16:
_similar_item.change_desc_4 = new_text
elif index == 17:
_similar_item.change_factor_4 = float(new_text)
elif index == 18:
_similar_item.change_desc_5 = new_text
elif index == 19:
_similar_item.change_factor_5 = float(new_text)
elif index == 20:
_similar_item.change_desc_6 = new_text
elif index == 21:
_similar_item.change_factor_6 = float(new_text)
elif index == 22:
_similar_item.change_desc_7 = new_text
elif index == 23:
_similar_item.change_factor_7 = float(new_text)
elif index == 24:
_similar_item.change_desc_8 = new_text
elif index == 25:
_similar_item.change_factor_8 = float(new_text)
elif index == 26:
_similar_item.change_desc_9 = new_text
elif index == 27:
_similar_item.change_factor_9 = float(new_text)
elif index == 28:
_similar_item.change_desc_10 = new_text
elif index == 29:
_similar_item.change_factor_10 = float(new_text)
elif index == 40:
_similar_item.user_blob_1 = new_text
elif index == 41:
_similar_item.user_blob_2 = new_text
elif index == 42:
_similar_item.user_blob_3 = new_text
elif index == 43:
_similar_item.user_blob_4 = new_text
elif index == 44:
_similar_item.user_blob_5 = new_text
elif index == 45:
_similar_item.user_float_1 = float(new_text)
elif index == 46:
_similar_item.user_float_2 = float(new_text)
elif index == 47:
_similar_item.user_float_3 = float(new_text)
elif index == 48:
_similar_item.user_float_4 = float(new_text)
elif index == 49:
_similar_item.user_float_5 = float(new_text)
elif index == 50:
_similar_item.user_int_1 = int(new_text)
elif index == 51:
_similar_item.user_int_2 = int(new_text)
elif index == 52:
_similar_item.user_int_3 = int(new_text)
elif index == 53:
_similar_item.user_int_4 = int(new_text)
elif index == 54:
_similar_item.user_int_5 = int(new_text)
return False
def _on_combo_changed(self, combo, index):
"""
Method to respond to gtk.ComboBox() 'changed' signals and call the
correct function or method, passing any parameters as needed.
:param gtk.ComboBox combo: the gtk.ComboBox() that called this method.
:param int index: the index in the handler ID list of the callback
signal associated with the gtk.ComboBox() that
called this method.
:return: False if successful or True is an error is encountered.
:rtype: bool
"""
(_model, _row) = self.tvwSimilarItem.get_selection().get_selected()
_hardware_id = _model.get_value(_row, 0)
_similar_item = self.dtcSimilarItem.dicSimilarItem[_hardware_id]
combo.handler_block(self._lst_handler_id[index])
if index == 3: # SIA method
_similar_item.method = combo.get_active()
elif index == 4: # From quality
_similar_item.from_quality = combo.get_active()
elif index == 5: # To quality.
_similar_item.to_quality = combo.get_active()
elif index == 6: # From environment.
_similar_item.from_environment = combo.get_active()
elif index == 7: # To environment.
_similar_item.to_environment = combo.get_active()
combo.handler_unblock(self._lst_handler_id[index])
return False
def _on_focus_out(self, entry, __event, index):
"""
Method to respond to gtk.Entry() 'focus_out' signals and call the
correct function or method, passing any parameters as needed.
:param gtk.Entry entry: the gtk.Entry() that called this method.
:param gtk.gdk.Event __event: the gtk.gdk.Event() that called this
method.
:param int index: the index in the handler ID list of the callback
signal associated with the gtk.Entry() that
called this method.
:return: False if successful or True is an error is encountered.
:rtype: bool
"""
(_model, _row) = self.tvwSimilarItem.get_selection().get_selected()
_hardware_id = _model.get_value(_row, 0)
_similar_item = self.dtcSimilarItem.dicSimilarItem[_hardware_id]
entry.handler_block(self._lst_handler_id[index])
if index == 8: # From temperature.
_similar_item.from_temperature = float(entry.get_text())
elif index == 9: # To temperature.
_similar_item.to_temperature = float(entry.get_text())
entry.handler_unblock(self._lst_handler_id[index])
return False
|
import numpy as np # type: ignore
def load_data(filename: str) -> np.array:
with open(filename) as f:
X = f.readlines()
# remove \n at end of line
X = [x.strip() for x in X]
return np.array(X, dtype=np.str)
def do_step_right(pos: int, step: int, width: int) -> int:
"""Takes current position and do 3 steps to the
right. Be aware of overflow as the board limit
on the right is reached."""
new_pos = (pos + step) % width
return new_pos
def do_step_down(pos: int, step: int, height: int) -> int:
new_pos = pos + step
if new_pos >= height:
return -1
else:
return new_pos
def count_trees(X: np.array, step_right: int, step_down: int) -> int:
no_trees = col = row = 0
height, width = X.size, len(X[0])
while row >= 0:
if X[row][col] == "#":
no_trees += 1
col = do_step_right(col, step_right, width)
row = do_step_down(row, step_down, height)
return no_trees
if __name__ == "__main__":
# filename = "./data/test_data03.txt"
filename = "./data/data03.txt"
X = load_data(filename)
"""
List of moves:
Right 1, down 1.
Right 3, down 1. (This is the slope you already checked.)
Right 5, down 1.
Right 7, down 1.
Right 1, down 2.
"""
moves = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
multi = 1
for move in moves:
multi *= count_trees(X, *move)
print(count_trees(X, *move))
print(multi)
|
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import sys
from google.appengine.ext import ndb
from dashboard import post_data_handler
from dashboard.models import histogram
class GetDiagnosticsHandler(post_data_handler.PostDataHandler):
"""URL endpoint to get diagnostics by guid or test path."""
def post(self):
"""Fetches a diagnostic by guid or test path and start and end revisions.
Request parameters:
guid: GUID of requested diagnostic.
start_revision: Start revision of requested diagnostic(s).
end_revision: End revision of requested diagnostic(s).
test_path: Test path of requested diagnostic(s).
name: Name of requested diagnostic(s).
Outputs:
List of diagnostics.
"""
guid = self.request.get('guid')
start_revision = self.request.get('start_revision')
end_revision = self.request.get('end_revision')
test_path = self.request.get('test_path')
name = self.request.get('name')
if guid:
if start_revision or end_revision or test_path or name:
self.ReportError(
'Fetching by GUID requires no additional parameters', status=400)
return
results = self._FetchByGuid(guid)
elif test_path:
results = self._FetchByTestPath(test_path,
start_revision,
end_revision,
name)
else:
self.ReportError('Missing parameter', status=400)
return
diagnostics = []
for result in results:
diagnostics.append(
{
'start_revision': result.start_revision,
'end_revision': result.end_revision,
'test_path': result.test.id(),
'name': result.name,
'data': result.data,
}
)
self.response.out.write(json.dumps(diagnostics))
def _FetchByGuid(self, guid):
try:
diagnostic = ndb.Key('SparseDiagnostic', guid).get()
except AssertionError:
# Thrown if accessing internal_only as an external user.
self.ReportError('Diagnostic not found', status=400)
return []
if not diagnostic:
self.ReportError('Diagnostic not found', status=400)
return []
return [diagnostic]
def _FetchByTestPath(self, test_path, start_revision, end_revision, name):
query = histogram.SparseDiagnostic.query()
query = query.filter(
histogram.SparseDiagnostic.test == ndb.Key('TestMetadata', test_path))
filter_again = False
if end_revision == 'last':
query = query.filter(
histogram.SparseDiagnostic.end_revision == sys.maxint)
elif start_revision and end_revision:
query = query.filter(
histogram.SparseDiagnostic.end_revision >= int(start_revision))
filter_again = True
else:
self.ReportError('Missing parameter', status=400)
return []
query = query.order(-histogram.SparseDiagnostic.end_revision)
results = list(query.fetch(500))
if name:
results = [result for result in results if result.name == name]
if filter_again:
# Workaround because appengine doesn't support two inequality filters
results = [result for result in results if
result.start_revision <= int(end_revision)]
if not results:
self.ReportError('Diagnostic(s) not found', status=400)
return []
return results
|
from __future__ import unicode_literals
from frappe import _
def get_data(data):
non_standard_fieldnames=data['non_standard_fieldnames']
non_standard_fieldnames['Job Order CT']='sales_order_reference'
data['non_standard_fieldnames']=non_standard_fieldnames
transactions=data['transactions']
transactions[3].update({'label': _('Manufacturing'),
'items': ['Work Order', 'Job Order CT']})
data['transactions']=transactions
return data |
#!/usr/bin/env python3
import sys
maxval = 0
maxfile = None
for line in sys.stdin:
data = line.strip().split("\t")
if len(data) != 2:
continue
k, v = data
if maxval < int(k):
maxval = int(k)
maxfile = v
if maxfile:
print('{0}\t{1}'.format(maxfile, maxval))
|
#!/usr/bin/env python3
# Apache License, Version 2.0
import argparse
import os
import shutil
import subprocess
import sys
import time
import tempfile
class COLORS_ANSI:
RED = '\033[00;31m'
GREEN = '\033[00;32m'
ENDC = '\033[0m'
class COLORS_DUMMY:
RED = ''
GREEN = ''
ENDC = ''
COLORS = COLORS_DUMMY
def printMessage(type, status, message):
if type == 'SUCCESS':
print(COLORS.GREEN, end="")
elif type == 'FAILURE':
print(COLORS.RED, end="")
status_text = ...
if status == 'RUN':
status_text = " RUN "
elif status == 'OK':
status_text = " OK "
elif status == 'PASSED':
status_text = " PASSED "
elif status == 'FAILED':
status_text = " FAILED "
else:
status_text = status
print("[{}]" . format(status_text), end="")
print(COLORS.ENDC, end="")
print(" {}" . format(message))
sys.stdout.flush()
def render_file(filepath):
dirname = os.path.dirname(filepath)
basedir = os.path.dirname(dirname)
subject = os.path.basename(dirname)
if subject == 'opengl':
command = (
BLENDER,
"--window-geometry", "0", "0", "1", "1",
"-noaudio",
"--factory-startup",
"--enable-autoexec",
filepath,
"-E", "CYCLES",
# Run with OSL enabled
# "--python-expr", "import bpy; bpy.context.scene.cycles.shading_system = True",
"-o", TEMP_FILE_MASK,
"-F", "PNG",
'--python', os.path.join(basedir,
"util",
"render_opengl.py")
)
else:
command = (
BLENDER,
"--background",
"-noaudio",
"--factory-startup",
"--enable-autoexec",
filepath,
"-E", "CYCLES",
# Run with OSL enabled
# "--python-expr", "import bpy; bpy.context.scene.cycles.shading_system = True",
"-o", TEMP_FILE_MASK,
"-F", "PNG",
"-f", "1",
)
try:
output = subprocess.check_output(command)
if VERBOSE:
print(output.decode("utf-8"))
return None
except subprocess.CalledProcessError as e:
if os.path.exists(TEMP_FILE):
os.remove(TEMP_FILE)
if VERBOSE:
print(e.output.decode("utf-8"))
if b"Error: engine not found" in e.output:
return "NO_CYCLES"
elif b"blender probably wont start" in e.output:
return "NO_START"
return "CRASH"
except BaseException as e:
if os.path.exists(TEMP_FILE):
os.remove(TEMP_FILE)
if VERBOSE:
print(e)
return "CRASH"
def test_get_name(filepath):
filename = os.path.basename(filepath)
return os.path.splitext(filename)[0]
def verify_output(filepath):
testname = test_get_name(filepath)
dirpath = os.path.dirname(filepath)
reference_dirpath = os.path.join(dirpath, "reference_renders")
reference_image = os.path.join(reference_dirpath, testname + ".png")
failed_image = os.path.join(reference_dirpath, testname + ".fail.png")
if not os.path.exists(reference_image):
return False
command = (
IDIFF,
"-fail", "0.015",
"-failpercent", "1",
reference_image,
TEMP_FILE,
)
try:
subprocess.check_output(command)
failed = False
except subprocess.CalledProcessError as e:
if VERBOSE:
print(e.output.decode("utf-8"))
failed = e.returncode != 1
if failed:
shutil.copy(TEMP_FILE, failed_image)
elif os.path.exists(failed_image):
os.remove(failed_image)
return not failed
def run_test(filepath):
testname = test_get_name(filepath)
spacer = "." * (32 - len(testname))
printMessage('SUCCESS', 'RUN', testname)
time_start = time.time()
error = render_file(filepath)
status = "FAIL"
if not error:
if not verify_output(filepath):
error = "VERIFY"
time_end = time.time()
elapsed_ms = int((time_end - time_start) * 1000)
if not error:
printMessage('SUCCESS', 'OK', "{} ({} ms)" .
format(testname, elapsed_ms))
else:
if error == "NO_CYCLES":
print("Can't perform tests because Cycles failed to load!")
return False
elif error == "NO_START":
print('Can not perform tests because blender fails to start.',
'Make sure INSTALL target was run.')
return False
elif error == 'VERIFY':
print("Rendered result is different from reference image")
else:
print("Unknown error %r" % error)
printMessage('FAILURE', 'FAILED', "{} ({} ms)" .
format(testname, elapsed_ms))
return error
def blend_list(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.lower().endswith(".blend"):
filepath = os.path.join(dirpath, filename)
yield filepath
def run_all_tests(dirpath):
passed_tests = []
failed_tests = []
all_files = list(blend_list(dirpath))
all_files.sort()
printMessage('SUCCESS', "==========",
"Running {} tests from 1 test case." . format(len(all_files)))
time_start = time.time()
for filepath in all_files:
error = run_test(filepath)
testname = test_get_name(filepath)
if error:
if error == "NO_CYCLES":
return False
elif error == "NO_START":
return False
failed_tests.append(testname)
else:
passed_tests.append(testname)
time_end = time.time()
elapsed_ms = int((time_end - time_start) * 1000)
print("")
printMessage('SUCCESS', "==========",
"{} tests from 1 test case ran. ({} ms total)" .
format(len(all_files), elapsed_ms))
printMessage('SUCCESS', 'PASSED', "{} tests." .
format(len(passed_tests)))
if failed_tests:
printMessage('FAILURE', 'FAILED', "{} tests, listed below:" .
format(len(failed_tests)))
failed_tests.sort()
for test in failed_tests:
printMessage('FAILURE', "FAILED", "{}" . format(test))
return False
return True
def create_argparse():
parser = argparse.ArgumentParser()
parser.add_argument("-blender", nargs="+")
parser.add_argument("-testdir", nargs=1)
parser.add_argument("-idiff", nargs=1)
return parser
def main():
parser = create_argparse()
args = parser.parse_args()
global COLORS
global BLENDER, ROOT, IDIFF
global TEMP_FILE, TEMP_FILE_MASK, TEST_SCRIPT
global VERBOSE
if os.environ.get("CYCLESTEST_COLOR") is not None:
COLORS = COLORS_ANSI
BLENDER = args.blender[0]
ROOT = args.testdir[0]
IDIFF = args.idiff[0]
TEMP = tempfile.mkdtemp()
TEMP_FILE_MASK = os.path.join(TEMP, "test")
TEMP_FILE = TEMP_FILE_MASK + "0001.png"
TEST_SCRIPT = os.path.join(os.path.dirname(__file__), "runtime_check.py")
VERBOSE = os.environ.get("BLENDER_VERBOSE") is not None
ok = run_all_tests(ROOT)
# Cleanup temp files and folders
if os.path.exists(TEMP_FILE):
os.remove(TEMP_FILE)
os.rmdir(TEMP)
sys.exit(not ok)
if __name__ == "__main__":
main()
|
from model import Nu_NN
import torch
import numpy as np
from math import exp
class Algo_Param():
def __init__(self, gamma=0.9):
self.gamma = gamma
class Wasserstein():
def __init__(self, nu_param, algo_param, lamda_lr=0.0003, deterministic_env=True, averege_next_nu = True,
discrete_policy=True, save_path = "temp", load_path="temp",
continuous_policy_sample_size = 30):
self.nu_param = nu_param
self.algo_param = algo_param
self.lamda_lr = lamda_lr
self.target_hard_update_interval = self.algo_param.hard_update_interval
#log_ratio estimator
self.nu_network = Nu_NN(nu_param, save_path=save_path, load_path=load_path)
self.nu_network_target = Nu_NN(nu_param, save_path=save_path, load_path=load_path)
self.nu_optimizer = torch.optim.Adam(self.nu_network.parameters(), lr=self.nu_param.l_r)
self.Lamda = torch.zeros(1, requires_grad=True, device=self.nu_param.device)
self.Lamda_optimizer = torch.optim.Adam([self.Lamda] ,lr=self.lamda_lr)
self.hard_update(source=self.nu_network, target=self.nu_network_target)
self.nu_base_lr = self.nu_param.l_r
self.current_lr = self.nu_base_lr
self.deterministic_env = deterministic_env
self.average_next_nu = averege_next_nu
self.discrete_poliy = discrete_policy
# exponential fucntion
self.f = lambda x: torch.exp(x)
self.current_KL = 0
self.update_no = 0
self.continuous_policy_sample_size = continuous_policy_sample_size #this is the number of samples ot take when the policy is continuous
def compute_gradeint(self, data1, data2):
state1 = data1.state
action1 = data1.action
state2 = data2.state
action2 = data2.action
alpha = torch.Tensor(np.random.random(size=(state1.size[0], 1)))
#interpolate both state and action features
state = (state1*alpha + (1-alpha)*state2).requires_grad_(True)
action = (action1*alpha + (1-alpha)*action2).requires_grad_(True)
inp = torch.cat((state, action), dim=1)
out = self.nu_network(state, action)
val = torch.autograd.Variable(torch.Tensor(state.shape[0], 1).fill_(1.0), requires_grad=False)
grad = torch.autograd.grad(out,
inp,
grad_outputs=val,
retain_graph=True,
create_graph=True,
only_inputs=True)
grad = grad.view(grad.size(0), -1)
gradient_penalty = ((grad.norm(2, dim=1) - 1) ** 2).mean()
return gradient_penalty
def train_ratio(self, data1, data2, unweighted=True):
self.debug_V = {"exp":None, "log_exp":None}
self.update_no += 1
state1 = data1.state
action1 = data1.action
weight1 = torch.Tensor(self.algo_param.gamma ** data1.time_step).to(self.nu_param.device)
state2 = data2.state
action2 = data2.action
weight2 = torch.Tensor(self.algo_param.gamma ** data2.time_step).to(self.nu_param.device)
# reshaping the weight tensor to facilitate the elmentwise multiplication operation
no_data1 = weight1.size()[0]
no_data2 = weight2.size()[0]
weight1 = torch.reshape(weight1, [no_data1, 1])
weight2 = torch.reshape(weight2, [no_data2, 1])
unweighted_nu_loss_1 = self.f(self.nu_network(state1, action1))
unweighted_nu_loss_2 = self.nu_network(state2, action2)
if unweighted:
loss_1 = torch.log(torch.sum(unweighted_nu_loss_1)) / len(data1.state)
loss_2 = torch.sum(unweighted_nu_loss_2) / len(data2.state)
else:
loss_1 = torch.log(torch.sum(weight1 * unweighted_nu_loss_1) / torch.sum(weight1))
loss_2 = torch.sum(weight2 * unweighted_nu_loss_2) / torch.sum(weight2)
neg_KL = loss_1 - loss_2
#main function
loss = neg_KL
self.nu_optimizer.zero_grad()
loss.backward()
self.nu_optimizer.step()
if self.update_no%self.target_hard_update_interval == 0:
self.hard_update(source=self.nu_network, target=self.nu_network_target)
self.current_KL = (neg_KL.item())
self.loss1 = loss_1
self.loss2 = loss_2
self.u_loss1 = unweighted_nu_loss_1
self.u_loss2 = unweighted_nu_loss_2
self.x = self.nu_network(state1, action1)
def get_KL(self, data1, data2, unweighted=True):
state1 = data1.state
action1 = data1.action
weight1 = torch.Tensor(self.algo_param.gamma ** data1.time_step).to(self.nu_param.device)
state2 = data2.state
action2 = data2.action
weight2 = torch.Tensor(self.algo_param.gamma ** data2.time_step).to(self.nu_param.device)
# reshaping the weight tensor to facilitate the elmentwise multiplication operation
no_data1 = weight1.size()[0]
no_data2 = weight2.size()[0]
weight1 = torch.reshape(weight1, [no_data1, 1])
weight2 = torch.reshape(weight2, [no_data2, 1])
unweighted_nu_loss_1 = self.f(self.nu_network(state1, action1))
unweighted_nu_loss_2 = self.nu_network(state2, action2)
if unweighted:
loss_1 = torch.log(torch.sum(unweighted_nu_loss_1))/len(data1.state)
loss_2 = torch.sum(unweighted_nu_loss_2)/len(data2.state)
else:
loss_1 = torch.log(torch.sum(weight1 * unweighted_nu_loss_1) / torch.sum(weight1))
loss_2 = torch.sum(weight2 * unweighted_nu_loss_2) / torch.sum(weight2)
neg_KL = loss_1 - loss_2
return neg_KL
def debug(self):
return self.debug_V["exp"], self.debug_V["log_exp"], self.debug_V["linear"]
def get_log_state_action_density_ratio(self, data, target_policy, limiter_network=True):
#since this is just the evaluation and don't need inital state, action we can simply use the q learning memory.
nu = self.nu_network(data.state, data.action)
return nu
def hard_update(self, source, target):
target.load_state_dict(source.state_dict())
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from .basic_modules import *
class AttentionModule(nn.Module):
"""
Corresponding CLEVR programs: 'filter_<att>'
Output: attention
"""
def __init__(self, **kwargs):
super().__init__()
self.dim_v = kwargs['dim_v']
self.attendNode = AttendNodeModule()
self.attnAnd = AndModule()
def forward(self, attn, feat, query):
"""
Args:
attn [Tensor] (num_node, ) : attention weight produced by previous module
feat [Tensor] (num_node, dim_v) : node features
query [Tensor] (dim_v, ) : embedding of <att>, such as 'red'
"""
new_attn = self.attendNode(feat, query)
out = self.attnAnd(attn, new_attn)
return out
class SameModule(nn.Module):
"""
Corresponding CLEVR programs: 'same_<cat>'
Output: attention
"""
def __init__(self, **kwargs):
super().__init__()
dim_v = kwargs['dim_v']
self.query = QueryModule(**kwargs)
self.attend = AttentionModule(**kwargs)
self.attnNot = NotModule()
def forward(self, attn, feat, query):
"""
Args:
attn [Tensor] (num_node, ) : attention weight produced by previous module
feat [Tensor] (num_node, dim_v) : node features
query [Tensor] (dim_v, ) : embedding of <cat>, such as 'color'
"""
# map category query to corresponding value query, such as, 'color' -> 'red'
value_query = self.query(attn, feat, query)
# find other red objects
out = self.attend(self.attnNot(attn), feat, value_query)
return out
class ExistOrCountModule(nn.Module):
"""
Corresponding CLEVR programs: 'exist', 'count'
Output: encoding
"""
def __init__(self, **kwargs):
super().__init__()
dim_v = kwargs['dim_v']
self.projection = nn.Sequential(
nn.Linear(1, 128),
nn.ReLU(),
nn.Linear(128, dim_v)
)
def forward(self, attn, feat, query):
# sum up the node attention
out = self.projection(torch.sum(attn, dim=0, keepdim=True))
return out
class RelateModule(nn.Module):
"""
Corresponding CLEVR programs: 'relate_<cat>'
Output: attention
"""
def __init__(self, **kwargs):
super().__init__()
self.attendEdge = AttendEdgeModule()
self.transfer = TransferModule()
def forward(self, attn, feat, query, edge_feat):
"""
Args:
attn [Tensor] (num_node, ) : attention weight produced by previous module
feat [Tensor] (num_node, dim_v) : node features
query [Tensor] (dim_v, ), embedding of <cat>, specifying a relationship category, such as 'left'
edge_feat [Tensor] (num_node, num_node, dim_v) : edge features
"""
edge_attn = self.attendEdge(edge_feat, query)
out = self.transfer(attn, edge_attn)
return out
class QueryModule(nn.Module):
"""
Corresponding CLEVR programs: 'query_<cat>'
Output: encoding
"""
def __init__(self, **kwargs):
super().__init__()
dim_v = kwargs['dim_v']
K = kwargs['k_attr'] # given attribute category number
self.query_to_weight = nn.Sequential(
nn.Linear(dim_v, K),
nn.Softmax(dim=0),
)
# K different mappings to project node features into different aspects
self.mappings = nn.Parameter(torch.zeros((K, dim_v, dim_v)))
nn.init.normal_(self.mappings.data, mean=0, std=0.01)
def forward(self, attn, feat, query):
"""
Args:
attn [Tensor] (num_node, ) : attention weight produced by previous module
feat [Tensor] (num_node, dim_v) : node features
query [Tensor] (dim_v, ) : embedding of <cat>, specifying an attribute category, such as 'color'
"""
out = torch.matmul(attn, feat)
# compute a probability distribution over K aspects
weight = self.query_to_weight(query)
mapping = torch.sum(self.mappings * weight.view(-1,1,1), dim=0) # (dim_v, dim_v)
out = torch.matmul(mapping, out)
return out
class ComparisonModule(nn.Module):
"""
Corresponding CLEVR programs: 'equal_<cat>', 'equal_integer', 'greater_than' and 'less_than'
Output: encoding
"""
def __init__(self, **kwargs):
super().__init__()
dim_v = kwargs['dim_v']
self.projection = nn.Sequential(
nn.Linear(dim_v, 128),
nn.ReLU(),
nn.Linear(128, dim_v)
)
def forward(self, enc1, enc2):
"""
Args: two encodings from two QueryModule or two CountModule
"""
input = enc1 - enc2
out = self.projection(input)
return out
|
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.dist3}.
"""
from __future__ import division
import os
from twisted.trial.unittest import TestCase
from twisted.python.dist3 import modulesToInstall
class ModulesToInstallTests(TestCase):
"""
Tests for L{modulesToInstall}.
"""
def test_sanityCheck(self):
"""
L{modulesToInstall} includes some obvious module names.
"""
self.assertIn("twisted.internet.reactor", modulesToInstall)
self.assertIn("twisted.python.test.test_dist3", modulesToInstall)
def test_exist(self):
"""
All modules listed in L{modulesToInstall} exist.
"""
import twisted
root = os.path.dirname(os.path.dirname(twisted.__file__))
for module in modulesToInstall:
segments = module.split(".")
segments[-1] += ".py"
path = os.path.join(root, *segments)
alternateSegments = module.split(".") + ["__init__.py"]
packagePath = os.path.join(root, *alternateSegments)
self.assertTrue(os.path.exists(path) or
os.path.exists(packagePath),
"Module {0} does not exist".format(module))
|
from utils import JsonUtil
from pprint import pprint
import numpy as np
import re
from keras.utils.data_utils import get_file
from keras.layers.embeddings import Embedding
from keras.layers import Dense, Merge, Dropout, RepeatVector, merge
from keras.layers import recurrent, Input, Bidirectional, LSTM, Lambda
from keras.models import Sequential
from keras.preprocessing.sequence import pad_sequences
from rnnlayer import Attention
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras import backend as K
def loadGloveModel(gloveFile):
print "Loading Glove Model..."
f = open(gloveFile,'r')
embedding_index = {}
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embedding_index[word] = coefs
f.close()
print('Found %s word vectors.' % len(embedding_index))
return embedding_index
def tokenize(sent):
'''Return the tokens of a sentence including punctuation.
>>> tokenize('Bob dropped the apple. Where is the apple?')
['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple', '?']
'''
return [x.strip() for x in re.split('(\W+)?', sent) if x.strip()]
def splitDatasets(f):
'''Given a parsed Json data object, split the object into training context (paragraph), question, answer matrices,
and keep track of max context and question lengths.
'''
xContext = [] # list of contexts paragraphs
xQuestion = [] # list of questions
xAnswerBegin = [] # list of indices of the beginning word in each answer span
xAnswerEnd = [] # list of indices of the ending word in each answer span
xAnswerText = [] # list of the answer text
maxLenContext = 0
maxLenQuestion = 0
for data in f:
paragraphs = data._paragraphs_
for paragraph in paragraphs:
context = paragraph._context_
contextTokenized = tokenize(context)
contextLength = len(contextTokenized)
if contextLength > maxLenContext:
maxLenContext = contextLength
qas = paragraph._qas_
for qa in qas:
question = qa._question_
questionTokenized = tokenize(question)
if len(questionTokenized) > maxLenQuestion:
maxLenQuestion = len(questionTokenized)
question_id = qa._id_
answers = qa._answers_
for answer in answers:
answerText = answer._text_
answerTokenized = tokenize(answerText)
# find indices of beginning/ending words of answer span among tokenized context
contextToAnswerFirstWord = context[:answer._answer_start_ + len(answerTokenized[0])]
answerBeginIndex = len(tokenize(contextToAnswerFirstWord)) - 1
answerEndIndex = answerBeginIndex + len(answerTokenized) - 1
xContext.append(contextTokenized)
xQuestion.append(questionTokenized)
xAnswerBegin.append(answerBeginIndex)
xAnswerEnd.append(answerEndIndex)
xAnswerText.append(answerText)
return xContext, xQuestion, xAnswerBegin, xAnswerEnd, xAnswerText, maxLenContext, maxLenQuestion
def vectorizeData(xContext, xQuestion, xAnswerBeing, xAnswerEnd, word_index, context_maxlen, question_maxlen):
'''Vectorize the words to their respective index and pad context to max context length and question to max question length.
Answers vectors are padded to the max context length as well.
'''
X = []
Xq = []
YBegin = []
YEnd = []
for i in xrange(len(xContext)):
x = [word_index[w] for w in xContext[i]]
xq = [word_index[w] for w in xQuestion[i]]
# map the first and last words of answer span to one-hot representations
y_Begin = np.zeros(len(xContext[i]))
y_Begin[xAnswerBeing[i]] = 1
y_End = np.zeros(len(xContext[i]))
y_End[xAnswerEnd[i]] = 1
X.append(x)
Xq.append(xq)
YBegin.append(y_Begin)
YEnd.append(y_End)
return pad_sequences(X, maxlen=context_maxlen, padding='post'), pad_sequences(Xq, maxlen=question_maxlen, padding='post'), pad_sequences(YBegin, maxlen=context_maxlen, padding='post'), pad_sequences(YEnd, maxlen=context_maxlen, padding='post')
# Note: Need to download and unzip Glove pre-train model files into same file as this script
GloveDimOption = '50' # this could be 50 (171.4 MB), 100 (347.1 MB), 200 (693.4 MB), or 300 (1 GB)
embeddings_index = loadGloveModel('../data/glove.6B/glove.6B.' + GloveDimOption + 'd.txt')
# load training data, parse, and split
print('Loading in training data...')
#trainData = JsonUtil.import_qas_data('../data/test.json')
trainData = JsonUtil.import_qas_data('../data/train-v1.1.json')
tContext, tQuestion, tAnswerBegin, tAnswerEnd, tAnswerText, maxLenTContext, maxLenTQuestion = splitDatasets(trainData)
# load validation data, parse, and split
print('Loading in Validation data...')
#valData = JsonUtil.import_qas_data('../data/test.json')
valData = JsonUtil.import_qas_data('../data/dev-v1.1.json')
vContext, vQuestion, vAnswerBegin, vAnswerEnd, vAnswerText, maxLenVContext, maxLenVQuestion = splitDatasets(valData)
print('Building vocabulary...')
# build a vocabular over all training and validation context paragraphs and question words
vocab = {}
for words in tContext + tQuestion + vContext + vQuestion:
for word in words:
if word not in vocab:
vocab[word] = 1
vocab = sorted(vocab.keys())
# Reserve 0 for masking via pad_sequences
vocab_size = len(vocab) + 1
word_index = dict((c, i + 1) for i, c in enumerate(vocab))
context_maxlen = max(maxLenTContext, maxLenVContext)
question_maxlen = max(maxLenTQuestion, maxLenVQuestion)
# vectorize training and validation datasets
print('Begin vectoring process...')
#tX: training Context, tXq: training Question, tYBegin: training Answer Begin ptr, tYEnd: training Answer End ptr
tX, tXq, tYBegin, tYEnd = vectorizeData(tContext, tQuestion, tAnswerBegin, tAnswerEnd, word_index, context_maxlen, question_maxlen)
#vX: validation Context, vXq: validation Question, vYBegin: validation Answer Begin ptr, vYEnd: validation Answer End ptr
vX, vXq, vYBegin, vYEnd = vectorizeData(vContext, vQuestion, vAnswerBegin, vAnswerEnd, word_index, context_maxlen, question_maxlen)
print('Vectoring process completed.')
print('tX.shape = {}'.format(tX.shape))
print('tXq.shape = {}'.format(tXq.shape))
print('tYBegin.shape = {}'.format(tYBegin.shape))
print('tYEnd.shape = {}'.format(tYEnd.shape))
print('vX.shape = {}'.format(vX.shape))
print('vXq.shape = {}'.format(vXq.shape))
print('vYBegin.shape = {}'.format(vYBegin.shape))
print('vYEnd.shape = {}'.format(vYEnd.shape))
print('context_maxlen, question_maxlen = {}, {}'.format(context_maxlen, question_maxlen))
print('Preparing embedding matrix.')
# prepare embedding matrix
nb_words = len(word_index)
EMBEDDING_DIM = int(GloveDimOption)
MAX_SEQUENCE_LENGTH = context_maxlen
embedding_matrix = np.zeros((nb_words, EMBEDDING_DIM))
for word, i in word_index.items():
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix[i] = embedding_vector
# load pre-trained word embeddings into an Embedding layer
embedding_layer = Embedding(nb_words,
EMBEDDING_DIM,
weights=[embedding_matrix],
input_length=MAX_SEQUENCE_LENGTH,
trainable=True, name='embedding')
print('Embedding matrix completed.')
# -------------- DNN goes after here ---------------------
cinput = Input(shape=(context_maxlen,), dtype='int32', name='cinput')
cembed = Embedding(nb_words, EMBEDDING_DIM, weights=[embedding_matrix],
input_length=maxLenTContext,
trainable=True, name='cembedding')(cinput)
qinput = Input(shape=(question_maxlen,), dtype='int32', name='qinput')
qembed = Embedding(nb_words, EMBEDDING_DIM, weights=[embedding_matrix],
input_length=maxLenTQuestion,
trainable=True, name='qembedding')(qinput)
qlstm1 = Bidirectional(LSTM(100, return_sequences=True, name='qlstm1'))(qembed)
#qlstm1 = Bidirectional(LSTM(100, return_sequences=True))(qembed)
print(qlstm1.shape)
clstm1 = Attention(100, qlstm1, 200, return_sequences=True, name='clstm1')(cembed)
qlstm2 = Attention(100, clstm1, 100, return_sequences=True, name='qlstm2')(qlstm1)
clstm2 = Attention(100, qlstm2, 100, return_sequences=True, name='clstm2')(clstm1)
qlstm3 = Attention(100, clstm2, 100, return_sequences=True, name='qlstm3')(qlstm2)
clstm3 = Attention(100, qlstm3, 100, return_sequences=False, name='clstm3')(clstm2)
qlstm4 = Bidirectional(LSTM(100, name='qlstm4'))(qlstm3)
h = merge([qlstm4, clstm3], mode='concat', name='merge1')
#qlstm3last = Lambda(lambda x: K.squeeze(x[:,-1,:], 1), output_shape=lambda s: (s[0], s[2]))(qlstm3)
#h = Lambda(lambda x, y: K.concatenate([x,y], axis=-1),
# output_shape=lambda s: (s[0], s[1]*2))(qlstm3last, clstm3)
#clstm3last = Lambda(lambda x: K.squeeze(x[:,-1,:], 1), output_shape=lambda s: (s[0], s[2]))(clstm3)
#h = merge([K.squeeze(qlstm3[:,-1,:], 1), clstm3], mode='concat', name='merge1')
#merged = Merge([clstm3, qlstm3], mode=lambda x: x[0] - x[1])
#clstm1 = Bidirectional(Attention(100, qlstm1, 200, return_sequences=True))(cembed)
#qlstm2 = Bidirectional(Attention(100, clstm1, 200, return_sequences=True))(qlstm1)
#clstm2 = Bidirectional(Attention(100, qlstm2, 200, return_sequences=True))(clstm1)
#h = merge([clstm2, K.repeat(K.mean(qlstm2, axis=1), n=maxLenTContext)], mode='concat', name='merge1')
#qlstm2reshap = K.reshape(K.repeat(K.mean(qlstm2, axis=1), n=maxLenTContext), (-1, 100))
#clstm2reshap = K.reshape(clstm2, (-1, 100))
#hreshap = merge([clstm2reshap, qlstm2reshap], mode='concat', name='merge1')
#h = K.reshape(hreshap, (-1, maxLenTContext, 200))
#hlstm = Bidirectional(LSTM(100, return_sequences=True, name='hlstm'))(h)
#hlstm1 = LSTM(100, name='hlstm1')(h)
output1 = Dense(context_maxlen, activation='softmax', name='output1')(h)
hmerge = merge([h, output1], mode='concat', name='merge2')
output2 = Dense(context_maxlen, activation='softmax', name='output2')(hmerge)
qnamodel = Model(input=[cinput, qinput], output=[output1, output2])
adam = Adam(lr=0.0003)
qnamodel.compile(optimizer=adam,
loss={'output1': 'categorical_crossentropy', 'output2': 'categorical_crossentropy'},
loss_weights={'output1': 1., 'output2': 1.},
metrics=['accuracy'])
qnamodel.summary()
best_model_file = './squad3e-4.h5'
best_model = ModelCheckpoint(best_model_file, monitor='val_output1_weighted_accuracy', verbose=1, save_best_only = True)
# and trained it via:
print(tX.shape, tXq.shape, tYBegin.shape, tYEnd.shape, vX.shape, vXq.shape,
vYBegin.shape, vYEnd.shape)
qnamodel.fit({'cinput': tX, 'qinput': tXq},
{'output1': tYBegin, 'output2': tYEnd},nb_epoch=100, batch_size=128,
validation_data=({'cinput': vX, 'qinput': vXq},
{'output1': vYBegin, 'output2': vYEnd}), callbacks=[best_model], verbose=2) |
import os
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
"""Get the environment variable or return exception."""
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the {} environment variable".format(var_name)
raise ImproperlyConfigured(error_msg)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# need to call os.path.dirname to go up one level in the path (like ../)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
JINJA2_DIR = os.path.join(BASE_DIR, 'templates/jinja2')
# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = set in local_settings.py
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'aggregator.apps.AggregatorConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'termsearch.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [ JINJA2_DIR,
],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'termsearch.jinja2utils.environment',
},
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'termsearch.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
# imported from local_settings.py
# Password validation
# https://docs.djangoproject.com/en/1.10/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.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
# top level static directory
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# ckeditor WYSIWYG stuff
MEDIA_URL = '/media/'
CKEDITOR_UPLOAD_PATH= 'uploads/'
# Logging settings
# Overwrite the default settings
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'formatters': {
'simple': {
'format': '[%(asctime)s] %(levelname)s %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'verbose': {
'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'
},
},
'handlers': {
'development_logfile': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_DIR, 'logs/django_dev.log'),
'filters': ['require_debug_true'],
'maxBytes': 1024 * 1024 * 15, # 15MB
'backupCount': 50,
'formatter': 'verbose',
},
'production_logfile': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filters': ['require_debug_false'],
'filename': os.path.join(BASE_DIR,'logs/django_production.log'),
'maxBytes': 1024 * 1024 * 15, # 15MB
'backupCount': 50,
'formatter': 'simple',
},
'dba_logfile': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_DIR,'logs/django_dba.log'),
'maxBytes': 1024 * 1024 * 15, # 15MB
'backupCount': 50,
'formatter': 'verbose',
},
'security_logfile': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filters': ['require_debug_false'],
'filename': os.path.join(BASE_DIR, 'logs/django_security.log'),
'maxBytes': 1024 * 1024 * 15, # 15MB
'backupCount': 50,
'formatter': 'verbose',
},
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
'null': {
'class': 'logging.NullHandler',
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'aggregator': {
'handlers': ['console', 'development_logfile', 'production_logfile'],
'level': 'DEBUG',
},
'dba': {
'handlers': ['console', 'dba_logfile'],
},
'django': {
'handlers': ['console', 'development_logfile', 'production_logfile'],
},
'django.security': {
'handlers': ['console', 'security_logfile'],
'propagate': False,
},
'py.warnings': {
'handlers': ['console', 'development_logfile'],
},
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.